Skip to content

Commit

Permalink
WorldClockTab: Add time in other cities
Browse files Browse the repository at this point in the history
This adds a button that pops up a window where you can select a city.
After chosing the city the city is added to the WorldClockTab and the
time in that spesific city is displayed.

the selected cities are currently saved in memory thus reloading the app
will cause the clock to forget what you've selected.
  • Loading branch information
mjarkk committed Mar 20, 2022
1 parent 669c92f commit 43844de
Show file tree
Hide file tree
Showing 8 changed files with 604 additions and 36 deletions.
40 changes: 5 additions & 35 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';

import './timer/tab.dart';
import './keyboard.dart';
import './worldClock/tab.dart';
import './worldClock/timezones.dart';
import './state.dart';

void main() {
setupTimezoneInfo();
appState = AppState.tryFromDisk();
runApp(new Clock());
}

Expand Down Expand Up @@ -141,38 +143,6 @@ class _ClockApp extends State<ClockApp> with TickerProviderStateMixin {
}
}

class WorldClockTab extends StatefulWidget {
@override
_WorldClockTabState createState() => _WorldClockTabState();
}

class _WorldClockTabState extends State<WorldClockTab> {
DateTime _datetime = DateTime.now();
Timer? _ctimer;

@override
void deactivate() {
_ctimer?.cancel();
super.deactivate();
}

@override
Widget build(BuildContext context) {
if (_ctimer == null)
_ctimer = Timer.periodic(Duration(seconds: 1), (me) {
_datetime = DateTime.now();
setState(() {});
});
return Material(
child: Center(
child: Text(
"${_datetime.hour}:${_datetime.minute < 10 ? "0" + _datetime.minute.toString() : _datetime.minute}:${_datetime.second < 10 ? "0" + _datetime.second.toString() : _datetime.second}",
style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
)),
);
}
}

class AlarmsTab extends StatelessWidget {
@override
Widget build(BuildContext context) {
Expand Down
135 changes: 135 additions & 0 deletions lib/state.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import 'dart:io';
import 'dart:convert';
import 'package:flutter/foundation.dart';

import './worldClock/timezones.dart';

// Config file contents:
/*
{
"timezones": ["Europe/Amsterdam"]
}
*/

var appState = AppState.empty();

enum _UnableToLoadReason {
IsWeb,
LocationUnknown,
FileDoesNotExist,
JsonDecode,
}

class AppState {
// Empty yields an empty instance of AppState
AppState.empty();

// Tries to load the appstate from the disk
AppState.tryFromDisk() {
if (kIsWeb) {
// We are on the web so we can't load the appstate from disk, return an empty AppState
_loadError = _UnableToLoadReason.IsWeb;
return;
}

if (_appConfigLocation == null) {
// The app config location is unknown, return an empty AppState
_loadError = _UnableToLoadReason.LocationUnknown;
return;
}

final File configFile = File(_appConfigLocation!);
if (!configFile.existsSync()) {
// Config file does not yet exist, return an empty AppState
_loadError = _UnableToLoadReason.FileDoesNotExist;
return;
}

try {
final String configContents = configFile.readAsStringSync();
dynamic config = jsonDecode(configContents);
if (!(config is Map)) {
throw 'config is not an object';
}

dynamic timezones = config['timezones'];
if (timezones is List) {
// Check if there are overlapping timezones from the config file and the timezones we know of
for (var cityTimezone in timezonesOfCities) {
for (var timezone in timezones) {
if (timezone is String && cityTimezone.key == timezone) {
_cityTimezones[timezone] = cityTimezone;
}
}
}
}
} catch (e) {
print("app state error: $e");
_loadError = _UnableToLoadReason.JsonDecode;
}
}

_UnableToLoadReason? _loadError;
Map<String, CityTimeZone> _cityTimezones = {};

_writeConfigToDisk() async {
// Check for errors that will prevent writing to disk
switch (_loadError) {
case _UnableToLoadReason.IsWeb:
case _UnableToLoadReason.LocationUnknown:
// Do not write the config with these errors
return;
default:
// Lets continue
break;
}

final File configFile = File(_appConfigLocation!);
try {
if (!await configFile.exists()) {
// The config file does not yet exist, lets create it
await configFile.create();
}
String configFileContents = jsonEncode({
'timezones': _cityTimezones.keys.toList(),
});
await configFile.writeAsString(configFileContents);
} catch (e) {
print("updating app config error: $e");
}
}

List<CityTimeZone> get cityTimezones => _cityTimezones.values.toList();

addCityTimezone(CityTimeZone entry) {
_cityTimezones[entry.key] = entry;
_writeConfigToDisk();
}

removeCityTimezone(CityTimeZone entry) {
_cityTimezones.remove(entry.key);
_writeConfigToDisk();
}
}

String? get _appConfigLocation {
String? homeDir =
Platform.environment[Platform.isWindows ? 'UserProfile' : 'HOME'];
return homeDir != null ? homeDir + "/.config/clock.json" : null;
}
131 changes: 131 additions & 0 deletions lib/worldClock/addTimezoneScreen.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
Copyright 2022 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import 'package:flutter/material.dart';

import './timezones.dart';

class AddTimezoneScreen extends StatefulWidget {
const AddTimezoneScreen({required this.onSelect});

final void Function(CityTimeZone cityTZ) onSelect;

@override
State<AddTimezoneScreen> createState() => _AddTimezoneScreenState();
}

class _AddTimezoneScreenState extends State<AddTimezoneScreen> {
List<CityTimeZone> options = timezonesOfCities;

onInput(String query) {
String normalizedQuery = query.toLowerCase();
options = timezonesOfCities
.where((e) => e.city.toLowerCase().contains(normalizedQuery))
.toList();
setState(() {});
}

onSearchSubmit() {
if (options.isNotEmpty) onSelect(options.first);
}

onSelect(CityTimeZone option) {
widget.onSelect(option);
Navigator.of(context).pop();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
elevation: 0,
toolbarHeight: 75,
title: Text('Choose a city'),
),
body: Column(
children: [
_SearchField(
onInput: onInput,
onSubmit: onSearchSubmit,
),
_Options(options: options, onSelect: onSelect),
],
),
);
}
}

class _Options extends StatelessWidget {
const _Options({required this.options, this.onSelect});

final List<CityTimeZone> options;
final void Function(CityTimeZone)? onSelect;

@override
Widget build(BuildContext context) {
return Expanded(
child: ListView.builder(
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final CityTimeZone option = options[index];

return TextButton(
key: Key(index.toString()),
style: TextButton.styleFrom(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.all(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
option.city,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
Text(
option.prettyUtcOffset,
style: TextStyle(fontSize: 12),
),
],
),
onPressed: onSelect != null ? () => onSelect!(option) : null,
);
},
),
);
}
}

class _SearchField extends StatelessWidget {
const _SearchField({required this.onInput, this.onSubmit});

final void Function(String s) onInput;
final void Function()? onSubmit;

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(24),
child: TextField(
autofocus: true,
decoration: InputDecoration(labelText: "City"),
onChanged: onInput,
onSubmitted: onSubmit != null ? (String s) => onSubmit!() : null,
),
);
}
}
Loading

0 comments on commit 43844de

Please sign in to comment.