Settings sync between the dashboard and the app
- Dashboard (settingsync.py): the plugins' settings go into a synced settings.db, one row per setting (the row id is the setting's key, so the phone and the dashboard edit the same row; the later change wins) plus each field as the plugin declares it. Fields marked "local" (addresses, paths on one machine) and the plugins' on / off stay out. Values set on another device are checked as the Settings page does before they're saved; a refused one is written back with the dashboard's value. - App 1.1.7: a Settings page (the gear on every tab) built from those fields, synced both ways. Food targets, the cycle, the work day and the body profile read the synced values; with a dashboard that doesn't sync settings yet, they still come from its Health summaries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
98b110dd56
commit
820aca7d92
25 changed files with 606 additions and 41 deletions
|
|
@ -13,6 +13,12 @@ What changed in each published build of the app. `tool/publish.sh` shows the ent
|
||||||
- The band's data goes with the phone's time zone, so the dashboard reads its times right without a
|
- The band's data goes with the phone's time zone, so the dashboard reads its times right without a
|
||||||
setting.
|
setting.
|
||||||
|
|
||||||
|
## 1.1.7 — 2026-10-26
|
||||||
|
|
||||||
|
- Settings (the gear at the top): the dashboard's Health, Cycle, Food and Work settings, synced both ways —
|
||||||
|
change them here or on the dashboard. Food's targets, the cycle's lengths, Work's day and the body
|
||||||
|
profile now follow them instead of fixed values in the app. A value the dashboard can't take is put back.
|
||||||
|
|
||||||
## 1.1.6 — 2026-10-26
|
## 1.1.6 — 2026-10-26
|
||||||
|
|
||||||
- Food: the arrows at the top go a week back / ahead; swiping sideways goes a day. The dashboard's arrows go
|
- Food: the arrows at the top go a week back / ahead; swiping sideways goes a day. The dashboard's arrows go
|
||||||
|
|
|
||||||
111
app/lib/app/prefs.dart
Normal file
111
app/lib/app/prefs.dart
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
// The dashboard's settings, synced both ways (the dashboard's settingsync.py): "settings.setting" rows
|
||||||
|
// {k "food.goal_rate", v JSON}, one per setting (the row id is k, so the phone and the dashboard edit the
|
||||||
|
// same row; the later change wins), and "settings.field" rows {k, plugin, title, pos, spec JSON} — each
|
||||||
|
// setting as the plugin declares it (label, type, options, min / max, help), so the Settings page needs no
|
||||||
|
// list of its own. The dashboard checks what arrives as its Settings page does; a value it refuses is
|
||||||
|
// written back with its own, which comes back here at the next sync.
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../sync/store.dart';
|
||||||
|
|
||||||
|
const tSetting = 'settings.setting', tField = 'settings.field';
|
||||||
|
|
||||||
|
class Prefs {
|
||||||
|
Prefs(this.store);
|
||||||
|
final SyncStore store;
|
||||||
|
|
||||||
|
/// The value of "plugin.key", or [d] while it hasn't come from the dashboard yet.
|
||||||
|
T get<T>(String k, T d) {
|
||||||
|
final r = store.row(tSetting, k);
|
||||||
|
if (r == null) return d;
|
||||||
|
try {
|
||||||
|
final v = jsonDecode(r['v'] as String);
|
||||||
|
if (v is T) return v;
|
||||||
|
if (d is double && v is num) return v.toDouble() as T;
|
||||||
|
if (d is int && v is num) return v.round() as T;
|
||||||
|
} catch (_) {}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
num number(String k, num d) => get<num>(k, d);
|
||||||
|
|
||||||
|
void set(String k, Object? v) {
|
||||||
|
final r = store.row(tSetting, k);
|
||||||
|
final enc = jsonEncode(v);
|
||||||
|
if (r != null && r['v'] == enc) return; // unchanged: nothing to send
|
||||||
|
store.put(tSetting, k, {'k': k, 'v': enc});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fields the dashboard shares, by plugin (in its order).
|
||||||
|
List<(String, String, List<Field>)> sections() {
|
||||||
|
final fs = [for (final r in store.rows(tField)) Field.of(r)]..sort((a, b) => a.pos.compareTo(b.pos));
|
||||||
|
final out = <(String, String, List<Field>)>[];
|
||||||
|
for (final f in fs) {
|
||||||
|
if (out.isEmpty || out.last.$1 != f.plugin) out.add((f.plugin, f.title, []));
|
||||||
|
out.last.$3.add(f);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One setting as the plugin declares it (pluginhost: META["settings"]).
|
||||||
|
class Field {
|
||||||
|
Field(this.k, this.plugin, this.title, this.pos, this.spec);
|
||||||
|
factory Field.of(Map<String, dynamic> r) {
|
||||||
|
Map<String, dynamic> spec;
|
||||||
|
try {
|
||||||
|
spec = jsonDecode(r['spec'] as String) as Map<String, dynamic>;
|
||||||
|
} catch (_) {
|
||||||
|
spec = {};
|
||||||
|
}
|
||||||
|
return Field(r['k'] as String, (r['plugin'] as String?) ?? '', (r['title'] as String?) ?? '', (r['pos'] as num?)?.toInt() ?? 0, spec);
|
||||||
|
}
|
||||||
|
final String k, plugin, title;
|
||||||
|
final int pos;
|
||||||
|
final Map<String, dynamic> spec;
|
||||||
|
|
||||||
|
String get key => spec['key'] as String? ?? k.split('.').last;
|
||||||
|
String get type => spec['type'] as String? ?? 'text';
|
||||||
|
String get label => spec['label'] as String? ?? key;
|
||||||
|
String? get help => spec['help'] as String?;
|
||||||
|
Object? get def => spec['default'];
|
||||||
|
num? get min => spec['min'] as num?;
|
||||||
|
num? get max => spec['max'] as num?;
|
||||||
|
bool get integer => spec['integer'] == true;
|
||||||
|
|
||||||
|
/// [(value, label)] of a select.
|
||||||
|
List<(Object?, String)> get options => [
|
||||||
|
for (final o in (spec['options'] as List?) ?? const [])
|
||||||
|
o is List ? (o.first, '${o.length > 1 ? o[1] : o.first}') : (o, '$o'),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The value checked as the dashboard will (pluginhost._value) → (value, null) or (null, why not).
|
||||||
|
(Object?, String?) check(Object? v) {
|
||||||
|
switch (type) {
|
||||||
|
case 'bool':
|
||||||
|
return (v == true, null);
|
||||||
|
case 'number':
|
||||||
|
final n = v is num ? v : num.tryParse('${v ?? ''}'.trim().replaceAll(',', '.'));
|
||||||
|
if (n == null) return (null, 'Must be a number.');
|
||||||
|
final lo = min ?? double.negativeInfinity, hi = max ?? double.infinity;
|
||||||
|
if (n < lo || n > hi) return (null, 'Must be between ${_g(lo)} and ${_g(hi)}.');
|
||||||
|
return (integer ? n.toInt() : n.toDouble(), null); // int() on the dashboard: cut, not rounded
|
||||||
|
case 'select':
|
||||||
|
for (final (o, _) in options) {
|
||||||
|
if ('$o' == '$v') return (o, null);
|
||||||
|
}
|
||||||
|
return (null, 'Pick one of the options.');
|
||||||
|
default:
|
||||||
|
final s = '${v ?? ''}'.trim();
|
||||||
|
final mx = (spec['max'] as num?)?.toInt() ?? 200;
|
||||||
|
if (s.length > mx) return (null, 'At most $mx characters.');
|
||||||
|
final p = spec['pattern'] as String?;
|
||||||
|
if (p != null && s.isNotEmpty && !RegExp('^(?:$p)\$').hasMatch(s)) {
|
||||||
|
return (null, spec['pattern_help'] as String? ?? 'Not a valid value.');
|
||||||
|
}
|
||||||
|
return (s, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _g(num n) => n == n.roundToDouble() ? n.round().toString() : '$n';
|
||||||
|
}
|
||||||
167
app/lib/app/settings_page.dart
Normal file
167
app/lib/app/settings_page.dart
Normal file
|
|
@ -0,0 +1,167 @@
|
||||||
|
// Settings: the dashboard's plugin settings (Health, Cycle, Food, Work …), built from the fields it shares
|
||||||
|
// (prefs.dart) and synced both ways. A switch or a pick is saved at once; a number or text opens a small
|
||||||
|
// editor that checks it as the dashboard will. Food's custom protein / carbs / fat are edited together
|
||||||
|
// (they must make 100 %) and only show with the "Custom" split.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'prefs.dart';
|
||||||
|
import 'sync_service.dart';
|
||||||
|
import 'theme.dart';
|
||||||
|
|
||||||
|
const _split = ['food.custom_protein', 'food.custom_carbs', 'food.custom_fat'];
|
||||||
|
|
||||||
|
class SettingsPage extends StatelessWidget {
|
||||||
|
const SettingsPage({super.key, required this.sync});
|
||||||
|
final SyncService sync;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Scaffold(
|
||||||
|
appBar: AppBar(title: const Text('Settings')),
|
||||||
|
body: ListenableBuilder(
|
||||||
|
listenable: sync,
|
||||||
|
builder: (context, _) {
|
||||||
|
final p = Prefs(sync.store);
|
||||||
|
final secs = p.sections();
|
||||||
|
if (secs.isEmpty) {
|
||||||
|
return const Padding(padding: EdgeInsets.all(16),
|
||||||
|
child: Text('The settings come from the dashboard with the next sync.', style: TextStyle(color: muted)));
|
||||||
|
}
|
||||||
|
return ListView(padding: const EdgeInsets.only(bottom: 24), children: [
|
||||||
|
for (final (_, title, fields) in secs) ...[
|
||||||
|
Padding(padding: const EdgeInsets.fromLTRB(16, 18, 16, 4),
|
||||||
|
child: Text(title, style: const TextStyle(color: accent, fontWeight: FontWeight.bold, fontSize: 15))),
|
||||||
|
for (final f in fields)
|
||||||
|
if (!_split.contains(f.k)) _tile(context, p, f)
|
||||||
|
else if (f.k == _split.first && p.get<String>('food.macro_preset', '') == 'custom') _splitTile(context, p, fields),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
void _set(Prefs p, String k, Object? v) {
|
||||||
|
p.set(k, v);
|
||||||
|
sync.changed(); // goes out with the next sync
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget? _info(Field f) => f.help == null
|
||||||
|
? null
|
||||||
|
: Tooltip(message: f.help!, triggerMode: TooltipTriggerMode.tap, showDuration: const Duration(seconds: 8),
|
||||||
|
child: const Padding(padding: EdgeInsets.all(8), child: Icon(Icons.info_outline, size: 18, color: muted)));
|
||||||
|
|
||||||
|
Widget _tile(BuildContext context, Prefs p, Field f) {
|
||||||
|
final v = p.get<Object?>(f.k, f.def);
|
||||||
|
switch (f.type) {
|
||||||
|
case 'bool':
|
||||||
|
return SwitchListTile(
|
||||||
|
title: Row(children: [Flexible(child: Text(f.label)), ?_info(f)]),
|
||||||
|
value: v == true,
|
||||||
|
onChanged: (x) => _set(p, f.k, x),
|
||||||
|
);
|
||||||
|
case 'select':
|
||||||
|
final opts = f.options;
|
||||||
|
final cur = opts.where((o) => '${o.$1}' == '$v').firstOrNull;
|
||||||
|
return ListTile(
|
||||||
|
title: Row(children: [Flexible(child: Text(f.label)), ?_info(f)]),
|
||||||
|
subtitle: DropdownButton<int>(
|
||||||
|
isExpanded: true,
|
||||||
|
value: cur == null ? null : opts.indexOf(cur),
|
||||||
|
underline: const SizedBox(),
|
||||||
|
dropdownColor: card2,
|
||||||
|
items: [for (var i = 0; i < opts.length; i++) DropdownMenuItem(value: i, child: Text(opts[i].$2))],
|
||||||
|
onChanged: (i) => i == null ? null : _set(p, f.k, opts[i].$1),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
final shown = v == null || '$v'.isEmpty ? '—' : f.type == 'number' && v is num && v == v.roundToDouble() ? '${v.round()}' : '$v';
|
||||||
|
return ListTile(
|
||||||
|
title: Row(children: [Flexible(child: Text(f.label)), ?_info(f)]),
|
||||||
|
subtitle: Text(shown, style: const TextStyle(color: muted)),
|
||||||
|
trailing: const Icon(Icons.edit_outlined, size: 18, color: muted),
|
||||||
|
onTap: () => _edit(context, p, [f]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _splitTile(BuildContext context, Prefs p, List<Field> fields) {
|
||||||
|
final fs = [for (final k in _split) fields.firstWhere((f) => f.k == k)];
|
||||||
|
final vs = [for (final f in fs) p.number(f.k, (f.def as num?) ?? 0).round()];
|
||||||
|
return ListTile(
|
||||||
|
title: const Text('Custom split: protein / carbs / fat'),
|
||||||
|
subtitle: Text('${vs[0]} / ${vs[1]} / ${vs[2]} % of the energy', style: const TextStyle(color: muted)),
|
||||||
|
trailing: const Icon(Icons.edit_outlined, size: 18, color: muted),
|
||||||
|
onTap: () => _edit(context, p, fs, total: 100),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A number / text editor for one field, or several edited together ([total]: they must add up to it).
|
||||||
|
Future<void> _edit(BuildContext context, Prefs p, List<Field> fs, {num? total}) => showModalBottomSheet(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
backgroundColor: card,
|
||||||
|
builder: (_) => _Editor(fields: fs, values: [for (final f in fs) p.get<Object?>(f.k, f.def)], total: total,
|
||||||
|
onSave: (vs) {
|
||||||
|
for (var i = 0; i < fs.length; i++) {
|
||||||
|
_set(p, fs[i].k, vs[i]);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Editor extends StatefulWidget {
|
||||||
|
const _Editor({required this.fields, required this.values, required this.onSave, this.total});
|
||||||
|
final List<Field> fields;
|
||||||
|
final List<Object?> values;
|
||||||
|
final num? total;
|
||||||
|
final void Function(List<Object?>) onSave;
|
||||||
|
@override
|
||||||
|
State<_Editor> createState() => _EditorState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _EditorState extends State<_Editor> {
|
||||||
|
late final ctl = [
|
||||||
|
for (final v in widget.values) TextEditingController(text: v == null ? '' : v is num && v == v.roundToDouble() ? '${v.round()}' : '$v'),
|
||||||
|
];
|
||||||
|
String? error;
|
||||||
|
|
||||||
|
void _save() {
|
||||||
|
final out = <Object?>[];
|
||||||
|
for (var i = 0; i < widget.fields.length; i++) {
|
||||||
|
final (v, err) = widget.fields[i].check(ctl[i].text);
|
||||||
|
if (err != null) return setState(() => error = '${widget.fields[i].label}: $err');
|
||||||
|
out.add(v);
|
||||||
|
}
|
||||||
|
final t = widget.total;
|
||||||
|
if (t != null) {
|
||||||
|
final sum = out.fold<num>(0, (a, v) => a + (v as num));
|
||||||
|
if (sum != t) return setState(() => error = 'They make ${sum.round()} %, not ${t.round()}.');
|
||||||
|
}
|
||||||
|
widget.onSave(out);
|
||||||
|
Navigator.pop(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
|
||||||
|
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||||
|
for (var i = 0; i < widget.fields.length; i++)
|
||||||
|
TextField(
|
||||||
|
controller: ctl[i],
|
||||||
|
autofocus: i == 0,
|
||||||
|
keyboardType: widget.fields[i].type == 'number' ? const TextInputType.numberWithOptions(decimal: true, signed: true) : null,
|
||||||
|
decoration: InputDecoration(labelText: widget.fields[i].label, helperText: _range(widget.fields[i])),
|
||||||
|
onSubmitted: (_) => _save(),
|
||||||
|
),
|
||||||
|
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
static String? _range(Field f) {
|
||||||
|
if (f.type != 'number' || (f.min == null && f.max == null)) return null;
|
||||||
|
String g(num n) => n == n.roundToDouble() ? '${n.round()}' : '$n';
|
||||||
|
return '${f.min == null ? '' : g(f.min!)} – ${f.max == null ? '' : g(f.max!)}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -23,6 +23,7 @@ import '../health/range.dart';
|
||||||
import '../health/sleep_page.dart';
|
import '../health/sleep_page.dart';
|
||||||
import '../sync/client.dart';
|
import '../sync/client.dart';
|
||||||
import '../sync/kick.dart' show piUrl;
|
import '../sync/kick.dart' show piUrl;
|
||||||
|
import 'settings_page.dart';
|
||||||
import 'sync_service.dart';
|
import 'sync_service.dart';
|
||||||
import 'updater.dart';
|
import 'updater.dart';
|
||||||
import 'theme.dart';
|
import 'theme.dart';
|
||||||
|
|
@ -71,7 +72,7 @@ class _ShellState extends State<Shell> {
|
||||||
color: card2,
|
color: card2,
|
||||||
onSelected: (k) {
|
onSelected: (k) {
|
||||||
if (k == 'doctor') {
|
if (k == 'doctor') {
|
||||||
Navigator.push(context, MaterialPageRoute(builder: (_) => DoctorPage(sync: widget.sync, settings: const CycleSettings())));
|
Navigator.push(context, MaterialPageRoute(builder: (_) => DoctorPage(sync: widget.sync, settings: CycleSettings.of(widget.sync.store))));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
itemBuilder: (_) => const [PopupMenuItem(value: 'doctor', child: Text('For your doctor'))],
|
itemBuilder: (_) => const [PopupMenuItem(value: 'doctor', child: Text('For your doctor'))],
|
||||||
|
|
@ -96,6 +97,12 @@ class _ShellState extends State<Shell> {
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
Widget _settingsIcon() => IconButton(
|
||||||
|
tooltip: 'Settings',
|
||||||
|
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => SettingsPage(sync: widget.sync))),
|
||||||
|
icon: const Icon(Icons.settings_outlined),
|
||||||
|
);
|
||||||
|
|
||||||
static const sections = [
|
static const sections = [
|
||||||
(Icons.favorite_border, Icons.favorite, 'Health'),
|
(Icons.favorite_border, Icons.favorite, 'Health'),
|
||||||
(Icons.restaurant_outlined, Icons.restaurant, 'Food'),
|
(Icons.restaurant_outlined, Icons.restaurant, 'Food'),
|
||||||
|
|
@ -115,8 +122,8 @@ class _ShellState extends State<Shell> {
|
||||||
length: healthTabs.length,
|
length: healthTabs.length,
|
||||||
child: Scaffold(
|
child: Scaffold(
|
||||||
appBar: wide
|
appBar: wide
|
||||||
? AppBar(titleSpacing: 0, title: tabs, actions: [_syncIcon(), _healthMenu()])
|
? AppBar(titleSpacing: 0, title: tabs, actions: [_syncIcon(), _settingsIcon(), _healthMenu()])
|
||||||
: AppBar(title: const Text('Health'), actions: [_syncIcon(), _healthMenu()], bottom: tabs),
|
: AppBar(title: const Text('Health'), actions: [_syncIcon(), _settingsIcon(), _healthMenu()], bottom: tabs),
|
||||||
body: TabBarView(children: [
|
body: TabBarView(children: [
|
||||||
OverviewPage(sync: widget.sync, onFood: () => setState(() => section = 1)),
|
OverviewPage(sync: widget.sync, onFood: () => setState(() => section = 1)),
|
||||||
CyclePage(sync: widget.sync),
|
CyclePage(sync: widget.sync),
|
||||||
|
|
@ -127,10 +134,10 @@ class _ShellState extends State<Shell> {
|
||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
1 => Scaffold(appBar: AppBar(title: const Text('Food'), actions: [_syncIcon(), _foodMenu()]), body: FoodPage(sync: widget.sync)),
|
1 => Scaffold(appBar: AppBar(title: const Text('Food'), actions: [_syncIcon(), _settingsIcon(), _foodMenu()]), body: FoodPage(sync: widget.sync)),
|
||||||
2 => WorkPage(sync: widget.sync, actions: [_syncIcon(), _workMenu()]), // its own bar: in landscape the week's ‹ CW › is in it
|
2 => WorkPage(sync: widget.sync, actions: [_syncIcon(), _settingsIcon(), _workMenu()]), // its own bar: in landscape the week's ‹ CW › is in it
|
||||||
3 => NotesPage(sync: widget.sync, actions: [_syncIcon()]), // its own bar: the title picks folder / tag
|
3 => NotesPage(sync: widget.sync, actions: [_syncIcon(), _settingsIcon()]), // its own bar: the title picks folder / tag
|
||||||
_ => WeatherPage(sync: widget.sync, actions: [_syncIcon()]), // its own bar: the place is the title's dropdown
|
_ => WeatherPage(sync: widget.sync, actions: [_syncIcon(), _settingsIcon()]), // its own bar: the place is the title's dropdown
|
||||||
};
|
};
|
||||||
void go(int i) => setState(() => section = i);
|
void go(int i) => setState(() => section = i);
|
||||||
if (wide) {
|
if (wide) {
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@
|
||||||
// note, source} — imported ones have id "vital:<t>", ones typed here a random id.
|
// note, source} — imported ones have id "vital:<t>", ones typed here a random id.
|
||||||
import 'dart:math';
|
import 'dart:math';
|
||||||
|
|
||||||
|
import '../app/prefs.dart';
|
||||||
import '../sync/store.dart';
|
import '../sync/store.dart';
|
||||||
import 'cycle_model.dart' show iso, parseDay, daysBetween, today;
|
import 'cycle_model.dart' show iso, parseDay, daysBetween, today;
|
||||||
import 'summaries.dart';
|
import 'summaries.dart';
|
||||||
|
|
@ -27,9 +28,18 @@ const fields = {
|
||||||
};
|
};
|
||||||
const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'};
|
const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'};
|
||||||
|
|
||||||
/// The values set on the dashboard (Settings ▸ Health), from its person summary (profileOf).
|
/// The dashboard's Settings ▸ Health (synced: prefs.dart); until they've come, its person summary (profileOf).
|
||||||
class Profile {
|
class Profile {
|
||||||
const Profile({this.sex = female, this.birth, this.height});
|
const Profile({this.sex = female, this.birth, this.height});
|
||||||
|
|
||||||
|
static Profile of(SyncStore store) {
|
||||||
|
final p = Prefs(store), s = profileOf(store);
|
||||||
|
final b = DateTime.tryParse(p.get<String>('health.birth_date', ''));
|
||||||
|
final h = p.number('health.height', 0).toDouble();
|
||||||
|
return Profile(sex: p.get<String>('health.sex', s.sex), birth: b == null ? s.birth : DateTime.utc(b.year, b.month, b.day),
|
||||||
|
height: h > 0 ? h : s.height);
|
||||||
|
}
|
||||||
|
|
||||||
final String sex;
|
final String sex;
|
||||||
final DateTime? birth;
|
final DateTime? birth;
|
||||||
final double? height;
|
final double? height;
|
||||||
|
|
|
||||||
|
|
@ -47,13 +47,13 @@ class _BodyPageState extends State<BodyPage> {
|
||||||
backgroundColor: accent,
|
backgroundColor: accent,
|
||||||
foregroundColor: bg,
|
foregroundColor: bg,
|
||||||
tooltip: 'Add measurements',
|
tooltip: 'Add measurements',
|
||||||
onPressed: () => _edit(BodyView(widget.sync.store, profileOf(widget.sync.store)), null),
|
onPressed: () => _edit(BodyView(widget.sync.store, Profile.of(widget.sync.store)), null),
|
||||||
child: const Icon(Icons.add),
|
child: const Icon(Icons.add),
|
||||||
),
|
),
|
||||||
body: ListenableBuilder(
|
body: ListenableBuilder(
|
||||||
listenable: Listenable.merge([widget.sync, widget.range]),
|
listenable: Listenable.merge([widget.sync, widget.range]),
|
||||||
builder: (context, _) {
|
builder: (context, _) {
|
||||||
final v = BodyView(widget.sync.store, profileOf(widget.sync.store));
|
final v = BodyView(widget.sync.store, Profile.of(widget.sync.store));
|
||||||
if (v.rows.isEmpty) {
|
if (v.rows.isEmpty) {
|
||||||
return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted)));
|
return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted)));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@
|
||||||
// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises).
|
// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises).
|
||||||
import 'dart:math';
|
import 'dart:math';
|
||||||
|
|
||||||
|
import '../app/prefs.dart';
|
||||||
import '../sync/store.dart';
|
import '../sync/store.dart';
|
||||||
|
|
||||||
const history = 12; // cycles averaged (at most)
|
const history = 12; // cycles averaged (at most)
|
||||||
|
|
@ -58,10 +59,17 @@ String iso(DateTime d) => d.toIso8601String().substring(0, 10);
|
||||||
int daysBetween(DateTime a, DateTime b) => b.difference(a).inDays; // b - a
|
int daysBetween(DateTime a, DateTime b) => b.difference(a).inDays; // b - a
|
||||||
DateTime plus(DateTime d, int n) => d.add(Duration(days: n));
|
DateTime plus(DateTime d, int n) => d.add(Duration(days: n));
|
||||||
|
|
||||||
|
/// The dashboard's Settings ▸ Cycle (synced: prefs.dart); its defaults until they've come.
|
||||||
class CycleSettings {
|
class CycleSettings {
|
||||||
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = true});
|
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = false});
|
||||||
final int cycleLength, periodLength;
|
final int cycleLength, periodLength;
|
||||||
final bool showFertile;
|
final bool showFertile;
|
||||||
|
|
||||||
|
static CycleSettings of(SyncStore store) {
|
||||||
|
final p = Prefs(store);
|
||||||
|
return CycleSettings(cycleLength: p.number('cycle.cycle_length', 28).round(),
|
||||||
|
periodLength: p.number('cycle.period_length', 5).round(), showFertile: p.get<bool>('cycle.show_fertile', false));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class DayLog {
|
class DayLog {
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ class CyclePage extends StatefulWidget {
|
||||||
|
|
||||||
class _CyclePageState extends State<CyclePage> {
|
class _CyclePageState extends State<CyclePage> {
|
||||||
int offset = 0; // months from this one
|
int offset = 0; // months from this one
|
||||||
final settings = const CycleSettings(); // TODO: from synced settings once those sync (Pi: 28 / 5 / fertile on)
|
CycleSettings get settings => CycleSettings.of(widget.sync.store); // the dashboard's, synced
|
||||||
|
|
||||||
void _save(DateTime d, Map<String, dynamic> fields) {
|
void _save(DateTime d, Map<String, dynamic> fields) {
|
||||||
saveDay(widget.sync.store, d, fields);
|
saveDay(widget.sync.store, d, fields);
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,9 @@ import 'package:flutter/services.dart';
|
||||||
import 'package:path_provider/path_provider.dart';
|
import 'package:path_provider/path_provider.dart';
|
||||||
import 'package:sqlite3/sqlite3.dart';
|
import 'package:sqlite3/sqlite3.dart';
|
||||||
|
|
||||||
|
import '../app/prefs.dart';
|
||||||
import '../sync/store.dart';
|
import '../sync/store.dart';
|
||||||
import 'body_model.dart' show BodyView, bmrMifflin, female, profileOf;
|
import 'body_model.dart' show BodyView, Profile, bmrMifflin, female;
|
||||||
import 'cycle_model.dart' show iso;
|
import 'cycle_model.dart' show iso;
|
||||||
import 'sugar.dart' show fold;
|
import 'sugar.dart' show fold;
|
||||||
import 'summaries.dart';
|
import 'summaries.dart';
|
||||||
|
|
@ -33,7 +34,10 @@ const foodCols = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat'
|
||||||
const reuseSources = {'manual', 'parsed'}; // entries worth offering again (imports are too rough)
|
const reuseSources = {'manual', 'parsed'}; // entries worth offering again (imports are too rough)
|
||||||
const generic = {'tbsp (15 ml)': 15.0, 'tsp (5 ml)': 5.0}; // spoons every food can be measured in (ml as g)
|
const generic = {'tbsp (15 ml)': 15.0, 'tsp (5 ml)': 5.0}; // spoons every food can be measured in (ml as g)
|
||||||
|
|
||||||
/// The dashboard's Settings ▸ Food, as its Health summary brings it (meta:food); its defaults until then.
|
/// Macro presets: % of the energy from protein / carbs / fat (views.PRESETS; "custom" = the custom fields).
|
||||||
|
const macroPresets = {'balanced': (20, 50, 30), 'high_protein': (30, 40, 30), 'mediterranean': (20, 45, 35), 'lower_carb': (30, 25, 45)};
|
||||||
|
|
||||||
|
/// The dashboard's Settings ▸ Food (synced: prefs.dart); its defaults until they've come.
|
||||||
class FoodSettings {
|
class FoodSettings {
|
||||||
const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25,
|
const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25,
|
||||||
this.sugarMax = 50, this.sodiumMax = 2000});
|
this.sugarMax = 50, this.sodiumMax = 2000});
|
||||||
|
|
@ -41,7 +45,21 @@ class FoodSettings {
|
||||||
final (int, int, int) split; // protein / carbs / fat % of the energy
|
final (int, int, int) split; // protein / carbs / fat % of the energy
|
||||||
final int kcalTarget, fiberMin, sugarMax, sodiumMax;
|
final int kcalTarget, fiberMin, sugarMax, sodiumMax;
|
||||||
|
|
||||||
|
/// views.split: the preset's split, or the custom one.
|
||||||
static FoodSettings of(SyncStore store) {
|
static FoodSettings of(SyncStore store) {
|
||||||
|
if (store.row(tSetting, 'food.macro_preset') == null) return _summary(store); // a dashboard without settings sync
|
||||||
|
final p = Prefs(store);
|
||||||
|
int n(String k, int d) => p.number('food.$k', d).round();
|
||||||
|
final preset = p.get<String>('food.macro_preset', 'balanced');
|
||||||
|
final split = preset == 'custom'
|
||||||
|
? (n('custom_protein', 20), n('custom_carbs', 50), n('custom_fat', 30))
|
||||||
|
: macroPresets[preset] ?? macroPresets['balanced']!;
|
||||||
|
return FoodSettings(goalRate: p.number('food.goal_rate', 0).toDouble(), split: split, kcalTarget: n('kcal_target', 0),
|
||||||
|
fiberMin: n('fiber_min', 25), sugarMax: n('sugar_max', 50), sodiumMax: n('sodium_max', 2000));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Older dashboards: Settings ▸ Food as its Health summary brings it (meta:food).
|
||||||
|
static FoodSettings _summary(SyncStore store) {
|
||||||
final m = Summaries(store).meta('food');
|
final m = Summaries(store).meta('food');
|
||||||
if (m == null) return const FoodSettings();
|
if (m == null) return const FoodSettings();
|
||||||
final sp = (m['split'] as List?)?.map((v) => (v as num).toInt()).toList();
|
final sp = (m['split'] as List?)?.map((v) => (v as num).toInt()).toList();
|
||||||
|
|
@ -494,7 +512,7 @@ class Plan {
|
||||||
/// averaged over 28 days with step data — at least 7) minus the weight goal; resting × 1.4 until then.
|
/// averaged over 28 days with step data — at least 7) minus the weight goal; resting × 1.4 until then.
|
||||||
Plan plan(SyncStore store, FoodSettings s) {
|
Plan plan(SyncStore store, FoodSettings s) {
|
||||||
final e = Summaries(store).meta('energy') ?? {};
|
final e = Summaries(store).meta('energy') ?? {};
|
||||||
final b = BodyView(store, profileOf(store));
|
final b = BodyView(store, Profile.of(store));
|
||||||
final w = (e['weight'] as num?)?.toDouble() ?? b.weight;
|
final w = (e['weight'] as num?)?.toDouble() ?? b.weight;
|
||||||
final bmr = (e['bmr'] as num?)?.toDouble() ?? bmrMifflin(w, b.p.height, b.p.sex, b.age);
|
final bmr = (e['bmr'] as num?)?.toDouble() ?? bmrMifflin(w, b.p.height, b.p.sex, b.age);
|
||||||
if (s.kcalTarget > 0) return Plan(s.kcalTarget, null, 'set by hand', 0, false);
|
if (s.kcalTarget > 0) return Plan(s.kcalTarget, null, 'set by hand', 0, false);
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ class FoodPage extends StatefulWidget {
|
||||||
class _FoodPageState extends State<FoodPage> {
|
class _FoodPageState extends State<FoodPage> {
|
||||||
DateTime d = today();
|
DateTime d = today();
|
||||||
FoodDb? fdb;
|
FoodDb? fdb;
|
||||||
FoodSettings get s => FoodSettings.of(widget.sync.store); // Settings ▸ Food on the dashboard
|
FoodSettings get s => FoodSettings.of(widget.sync.store); // the dashboard's, synced
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ class _OverviewPageState extends State<OverviewPage> {
|
||||||
final last = nights.isNotEmpty && nights.last.day == now;
|
final last = nights.isNotEmpty && nights.last.day == now;
|
||||||
final steps = sm.day(iso(now))?['steps'] as num?;
|
final steps = sm.day(iso(now))?['steps'] as num?;
|
||||||
final week = [for (var k = 1; k <= 7; k++) sm.day(iso(plus(now, -k)))?['steps'] as num?].whereType<num>().toList();
|
final week = [for (var k = 1; k <= 7; k++) sm.day(iso(plus(now, -k)))?['steps'] as num?].whereType<num>().toList();
|
||||||
final cv = CycleView(widget.sync.store, const CycleSettings());
|
final cv = CycleView(widget.sync.store, CycleSettings.of(widget.sync.store));
|
||||||
var (head, sub) = cycleStatus(cv);
|
var (head, sub) = cycleStatus(cv);
|
||||||
if (cv.status == Status.wait) head = cv.daysToNext == 0 ? 'today' : 'in ${cv.daysToNext} ${cv.daysToNext == 1 ? 'day' : 'days'}';
|
if (cv.status == Status.wait) head = cv.daysToNext == 0 ? 'today' : 'in ${cv.daysToNext} ${cv.daysToNext == 1 ? 'day' : 'days'}';
|
||||||
if (cv.status == Status.period) head = 'day ${cv.cycleDay}';
|
if (cv.status == Status.period) head = 'day ${cv.cycleDay}';
|
||||||
|
|
|
||||||
|
|
@ -17,9 +17,9 @@ IconData kindIcon(Node n) => n.kind == 'task'
|
||||||
: Icons.business;
|
: Icons.business;
|
||||||
|
|
||||||
class CustomersPage extends StatefulWidget {
|
class CustomersPage extends StatefulWidget {
|
||||||
const CustomersPage({super.key, required this.sync, this.s = const WorkSettings()});
|
const CustomersPage({super.key, required this.sync});
|
||||||
final SyncService sync;
|
final SyncService sync;
|
||||||
final WorkSettings s;
|
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||||
@override
|
@override
|
||||||
State<CustomersPage> createState() => _CustomersPageState();
|
State<CustomersPage> createState() => _CustomersPageState();
|
||||||
}
|
}
|
||||||
|
|
@ -30,7 +30,7 @@ class _CustomersPageState extends State<CustomersPage> {
|
||||||
void _edit({String? id, String kind = 'client', String? parent}) => Navigator.push(
|
void _edit({String? id, String kind = 'client', String? parent}) => Navigator.push(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute(
|
MaterialPageRoute(
|
||||||
builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: id, kind: kind, parent: parent),
|
builder: (_) => NodeEditor(sync: widget.sync, nodeId: id, kind: kind, parent: parent),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -112,9 +112,9 @@ class _CustomersPageState extends State<CustomersPage> {
|
||||||
|
|
||||||
/// One node's editor (new when [nodeId] is null: a [kind] under [parent]).
|
/// One node's editor (new when [nodeId] is null: a [kind] under [parent]).
|
||||||
class NodeEditor extends StatefulWidget {
|
class NodeEditor extends StatefulWidget {
|
||||||
const NodeEditor({super.key, required this.sync, this.s = const WorkSettings(), this.nodeId, this.kind = 'client', this.parent});
|
const NodeEditor({super.key, required this.sync, this.nodeId, this.kind = 'client', this.parent});
|
||||||
final SyncService sync;
|
final SyncService sync;
|
||||||
final WorkSettings s;
|
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||||
final String? nodeId, kind, parent;
|
final String? nodeId, kind, parent;
|
||||||
@override
|
@override
|
||||||
State<NodeEditor> createState() => _NodeEditorState();
|
State<NodeEditor> createState() => _NodeEditorState();
|
||||||
|
|
|
||||||
|
|
@ -26,12 +26,12 @@ Future<void> openEntry(
|
||||||
int? endMin,
|
int? endMin,
|
||||||
String? node,
|
String? node,
|
||||||
String note = '',
|
String note = '',
|
||||||
WorkSettings s = const WorkSettings(),
|
WorkSettings? s,
|
||||||
}) => showModalBottomSheet(
|
}) => showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
isScrollControlled: true,
|
isScrollControlled: true,
|
||||||
backgroundColor: card,
|
backgroundColor: card,
|
||||||
builder: (_) => EntrySheet(sync: sync, entry: entry, day: day, startMin: startMin, endMin: endMin, node: node, note: note, s: s),
|
builder: (_) => EntrySheet(sync: sync, entry: entry, day: day, startMin: startMin, endMin: endMin, node: node, note: note, s: s ?? WorkSettings.of(sync.store)),
|
||||||
);
|
);
|
||||||
|
|
||||||
class EntrySheet extends StatefulWidget {
|
class EntrySheet extends StatefulWidget {
|
||||||
|
|
|
||||||
|
|
@ -10,9 +10,9 @@ import 'entry_sheet.dart';
|
||||||
import 'work_model.dart';
|
import 'work_model.dart';
|
||||||
|
|
||||||
class ReportPage extends StatefulWidget {
|
class ReportPage extends StatefulWidget {
|
||||||
const ReportPage({super.key, required this.sync, this.s = const WorkSettings()});
|
const ReportPage({super.key, required this.sync});
|
||||||
final SyncService sync;
|
final SyncService sync;
|
||||||
final WorkSettings s;
|
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||||
@override
|
@override
|
||||||
State<ReportPage> createState() => _ReportPageState();
|
State<ReportPage> createState() => _ReportPageState();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@
|
||||||
// "workload.entry" {node_id, start, end 'YYYY-MM-DD HH:MM' local, billable 0/1, note, created, updated}
|
// "workload.entry" {node_id, start, end 'YYYY-MM-DD HH:MM' local, billable 0/1, note, created, updated}
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../app/prefs.dart';
|
||||||
import '../sync/store.dart';
|
import '../sync/store.dart';
|
||||||
|
|
||||||
const kinds = ['client', 'project', 'task'];
|
const kinds = ['client', 'project', 'task'];
|
||||||
|
|
@ -20,7 +21,7 @@ const palette = ['#ffb33a', '#5cc8ff', '#7fd6a3', '#ff6b7a', '#c792ea', '#ff9d5c
|
||||||
const epoch = '0000-01-01'; // a rate "since" this applies to all work
|
const epoch = '0000-01-01'; // a rate "since" this applies to all work
|
||||||
const tNode = 'workload.node', tRate = 'workload.rate', tEntry = 'workload.entry';
|
const tNode = 'workload.node', tRate = 'workload.rate', tEntry = 'workload.entry';
|
||||||
|
|
||||||
/// Until settings sync: the dashboard's Settings ▸ Work defaults.
|
/// The dashboard's Settings ▸ Work (synced: prefs.dart); its defaults until they've come.
|
||||||
class WorkSettings {
|
class WorkSettings {
|
||||||
const WorkSettings({
|
const WorkSettings({
|
||||||
this.currency = 'EUR',
|
this.currency = 'EUR',
|
||||||
|
|
@ -34,6 +35,13 @@ class WorkSettings {
|
||||||
final double defaultRate;
|
final double defaultRate;
|
||||||
final int dayStart, dayEnd, defaultMinutes;
|
final int dayStart, dayEnd, defaultMinutes;
|
||||||
final double weekTarget;
|
final double weekTarget;
|
||||||
|
|
||||||
|
static WorkSettings of(SyncStore store) {
|
||||||
|
final p = Prefs(store);
|
||||||
|
return WorkSettings(currency: p.get<String>('workload.currency', 'EUR'), defaultRate: p.number('workload.default_rate', 0).toDouble(),
|
||||||
|
dayStart: p.number('workload.day_start', 7).round(), dayEnd: p.number('workload.day_end', 19).round(),
|
||||||
|
defaultMinutes: p.number('workload.default_minutes', 60).round(), weekTarget: p.number('workload.week_target', 40).toDouble());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Invalid implements Exception {
|
class Invalid implements Exception {
|
||||||
|
|
|
||||||
|
|
@ -54,9 +54,9 @@ Widget _hold({
|
||||||
);
|
);
|
||||||
|
|
||||||
class WorkPage extends StatefulWidget {
|
class WorkPage extends StatefulWidget {
|
||||||
const WorkPage({super.key, required this.sync, this.s = const WorkSettings(), this.actions = const []});
|
const WorkPage({super.key, required this.sync, this.actions = const []});
|
||||||
final SyncService sync;
|
final SyncService sync;
|
||||||
final WorkSettings s;
|
WorkSettings get s => WorkSettings.of(sync.store); // the dashboard's, synced
|
||||||
final List<Widget> actions; // the shell's (sync icon, ⋮) — Work has its own bar: in landscape the week's ‹ CW › sits in it
|
final List<Widget> actions; // the shell's (sync icon, ⋮) — Work has its own bar: in landscape the week's ‹ CW › sits in it
|
||||||
@override
|
@override
|
||||||
State<WorkPage> createState() => _WorkPageState();
|
State<WorkPage> createState() => _WorkPageState();
|
||||||
|
|
@ -202,7 +202,7 @@ class _WorkPageState extends State<WorkPage> {
|
||||||
onPressed: () => Navigator.push(
|
onPressed: () => Navigator.push(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute(
|
MaterialPageRoute(
|
||||||
builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id),
|
builder: (_) => NodeEditor(sync: widget.sync, nodeId: c.node.id),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
@ -299,7 +299,7 @@ class _WorkPageState extends State<WorkPage> {
|
||||||
onPressed: () => Navigator.push(
|
onPressed: () => Navigator.push(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute(
|
MaterialPageRoute(
|
||||||
builder: (_) => CustomersPage(sync: widget.sync, s: widget.s),
|
builder: (_) => CustomersPage(sync: widget.sync),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
icon: const Icon(Icons.add),
|
icon: const Icon(Icons.add),
|
||||||
|
|
@ -407,7 +407,7 @@ class _WorkPageState extends State<WorkPage> {
|
||||||
onPressed: () => Navigator.push(
|
onPressed: () => Navigator.push(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute(
|
MaterialPageRoute(
|
||||||
builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id),
|
builder: (_) => NodeEditor(sync: widget.sync, nodeId: c.node.id),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.1.6+10
|
version: 1.1.7+11
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
|
|
|
||||||
66
app/test/prefs_test.dart
Normal file
66
app/test/prefs_test.dart
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
// The dashboard's settings as they sync (prefs.dart = settingsync.py): values read with the dashboard's
|
||||||
|
// defaults until they've come, the food split from its preset or the custom fields, the fields' checks.
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dash_app/app/prefs.dart';
|
||||||
|
import 'package:dash_app/health/cycle_model.dart';
|
||||||
|
import 'package:dash_app/health/food_model.dart';
|
||||||
|
import 'package:dash_app/sync/store.dart';
|
||||||
|
import 'package:dash_app/work/work_model.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final store = SyncStore('${Directory.systemTemp.createTempSync('prefs').path}/d.db', 'test00000000');
|
||||||
|
void fromDashboard(String k, Object? v) => store.put(tSetting, k, {'k': k, 'v': jsonEncode(v)});
|
||||||
|
|
||||||
|
test('defaults until the dashboard\'s values come', () {
|
||||||
|
final f = FoodSettings.of(store);
|
||||||
|
expect(f.split, (20, 50, 30));
|
||||||
|
expect(f.goalRate, 0);
|
||||||
|
expect(CycleSettings.of(store).cycleLength, 28);
|
||||||
|
expect(WorkSettings.of(store).dayStart, 7);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the dashboard\'s values: presets, the custom split, numbers as stored', () {
|
||||||
|
fromDashboard('food.macro_preset', 'high_protein');
|
||||||
|
fromDashboard('food.goal_rate', 0.25);
|
||||||
|
fromDashboard('cycle.cycle_length', 30.0);
|
||||||
|
fromDashboard('workload.currency', 'RON');
|
||||||
|
expect(FoodSettings.of(store).split, (30, 40, 30));
|
||||||
|
expect(FoodSettings.of(store).goalRate, 0.25);
|
||||||
|
expect(CycleSettings.of(store).cycleLength, 30);
|
||||||
|
expect(WorkSettings.of(store).currency, 'RON');
|
||||||
|
fromDashboard('food.macro_preset', 'custom');
|
||||||
|
fromDashboard('food.custom_protein', 35);
|
||||||
|
fromDashboard('food.custom_carbs', 35);
|
||||||
|
fromDashboard('food.custom_fat', 30);
|
||||||
|
expect(FoodSettings.of(store).split, (35, 35, 30));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('set writes only a change', () {
|
||||||
|
final p = Prefs(store);
|
||||||
|
p.set('food.sugar_max', 40);
|
||||||
|
final h = store.rows(tSetting).firstWhere((r) => r['_u'] == 'food.sugar_max')['_h'];
|
||||||
|
p.set('food.sugar_max', 40);
|
||||||
|
expect(store.rows(tSetting).firstWhere((r) => r['_u'] == 'food.sugar_max')['_h'], h);
|
||||||
|
expect(FoodSettings.of(store).sugarMax, 40);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fields: sections in order, checks as the dashboard', () {
|
||||||
|
void field(String k, int pos, Map<String, Object?> spec) =>
|
||||||
|
store.put(tField, k, {'k': k, 'plugin': k.split('.').first, 'title': k.split('.').first, 'pos': pos, 'spec': jsonEncode(spec)});
|
||||||
|
field('cycle.cycle_length', 0, {'key': 'cycle_length', 'type': 'number', 'min': 15, 'max': 60, 'integer': true});
|
||||||
|
field('food.goal_rate', 1, {'key': 'goal_rate', 'type': 'select', 'options': [[0.0, 'Keep'], [0.25, 'Lose 0.25 %']]});
|
||||||
|
field('workload.currency', 2, {'key': 'currency', 'type': 'text', 'max': 3, 'pattern': '[A-Za-z]{3}'});
|
||||||
|
final secs = Prefs(store).sections();
|
||||||
|
expect([for (final s in secs) s.$1], ['cycle', 'food', 'workload']);
|
||||||
|
final cl = secs[0].$3.single, gr = secs[1].$3.single, cur = secs[2].$3.single;
|
||||||
|
expect(cl.check('29.6'), (29, null));
|
||||||
|
expect(cl.check('80').$2, 'Must be between 15 and 60.');
|
||||||
|
expect(gr.check(0.25), (0.25, null));
|
||||||
|
expect(gr.check('1').$2, 'Pick one of the options.');
|
||||||
|
expect(cur.check('eu1').$2, isNotNull);
|
||||||
|
expect(cur.check('EUR'), ('EUR', null));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -403,6 +403,11 @@ def load(store):
|
||||||
for fn in p.workers:
|
for fn in p.workers:
|
||||||
threading.Thread(target=fn, args=(p.ctx,), daemon=True, name=f"plugin-{name}").start()
|
threading.Thread(target=fn, args=(p.ctx,), daemon=True, name=f"plugin-{name}").start()
|
||||||
print(f"plugin {name}: loaded{' (on)' if enabled(store, name) else ''}", flush=True)
|
print(f"plugin {name}: loaded{' (on)' if enabled(store, name) else ''}", flush=True)
|
||||||
|
try: # the settings the app shares (settingsync.py)
|
||||||
|
import settingsync
|
||||||
|
settingsync.publish(store)
|
||||||
|
except Exception:
|
||||||
|
print(f"settings: {traceback.format_exc()}", flush=True)
|
||||||
try: # META["sync"]: stamp those tables, start the sync worker
|
try: # META["sync"]: stamp those tables, start the sync worker
|
||||||
import sync
|
import sync
|
||||||
sync.boot(store)
|
sync.boot(store)
|
||||||
|
|
|
||||||
|
|
@ -37,13 +37,13 @@ META = {
|
||||||
"the other dashboards through the sync, sorted into your categories here.",
|
"the other dashboards through the sync, sorted into your categories here.",
|
||||||
"links": [{"label": "Open", "href": "/activity"}, {"label": "Categories & rules", "href": "/activity/rules"}],
|
"links": [{"label": "Open", "href": "/activity"}, {"label": "Categories & rules", "href": "/activity/rules"}],
|
||||||
"settings": [
|
"settings": [
|
||||||
{"key": "sources", "label": "Computers (name=address, comma separated)", "type": "text", "max": 500,
|
{"key": "sources", "local": True, "label": "Computers (name=address, comma separated)", "type": "text", "max": 500,
|
||||||
"default": "",
|
"default": "",
|
||||||
"help": "Each one's ActivityWatch, listening on the home network (aw-server.toml: host = \"0.0.0.0\"). "
|
"help": "Each one's ActivityWatch, listening on the home network (aw-server.toml: host = \"0.0.0.0\"). "
|
||||||
"A dashboard running on one of them reaches its own at http://127.0.0.1:5600 — that works away from home; "
|
"A dashboard running on one of them reaches its own at http://127.0.0.1:5600 — that works away from home; "
|
||||||
"what the others pull arrives through the sync."},
|
"what the others pull arrives through the sync."},
|
||||||
{"key": "every", "label": "Ask every (minutes)", "type": "number", "default": 5, "min": 1, "max": 60, "integer": True},
|
{"key": "every", "local": True, "label": "Ask every (minutes)", "type": "number", "default": 5, "min": 1, "max": 60, "integer": True},
|
||||||
{"key": "smooth", "label": "Smooth out switches shorter than (seconds; 0 = off)", "type": "number", "default": sorter.SMOOTH,
|
{"key": "smooth", "local": True, "label": "Smooth out switches shorter than (seconds; 0 = off)", "type": "number", "default": sorter.SMOOTH,
|
||||||
"min": 0, "max": 900, "integer": True,
|
"min": 0, "max": 900, "integer": True,
|
||||||
"help": "A short switch between two stretches of the same category takes theirs; unsorted short ones take the longer neighbour. "
|
"help": "A short switch between two stretches of the same category takes theirs; unsorted short ones take the longer neighbour. "
|
||||||
"Distractions are never smoothed away. The day page can show it raw too."},
|
"Distractions are never smoothed away. The day page can show it raw too."},
|
||||||
|
|
|
||||||
|
|
@ -59,11 +59,11 @@ META = {
|
||||||
"min": 0, "max": 300, "integer": True},
|
"min": 0, "max": 300, "integer": True},
|
||||||
{"key": "sodium_max", "label": "Sodium, at most (mg)", "type": "number", "default": 2000,
|
{"key": "sodium_max", "label": "Sodium, at most (mg)", "type": "number", "default": 2000,
|
||||||
"min": 0, "max": 10000, "integer": True, "help": "WHO: under 2000 mg (= 5 g salt)."},
|
"min": 0, "max": 10000, "integer": True, "help": "WHO: under 2000 mg (= 5 g salt)."},
|
||||||
{"key": "use_model", "label": "Describe box (language model) on", "type": "bool", "default": True,
|
{"key": "use_model", "local": True, "label": "Describe box (language model) on", "type": "bool", "default": True,
|
||||||
"help": "Off: the diary has only the form; nothing is sent to the model."},
|
"help": "Off: the diary has only the form; nothing is sent to the model."},
|
||||||
{"key": "model_url", "label": "Language model address (Ollama)", "type": "text", "default": "",
|
{"key": "model_url", "local": True, "label": "Language model address (Ollama)", "type": "text", "default": "",
|
||||||
"max": 200, "help": "e.g. http://localhost:11434 — empty = the describe box is off."},
|
"max": 200, "help": "e.g. http://localhost:11434 — empty = the describe box is off."},
|
||||||
{"key": "model", "label": "Model", "type": "text", "default": "qwen3:1.7b", "max": 80},
|
{"key": "model", "local": True, "label": "Model", "type": "text", "default": "qwen3:1.7b", "max": 80},
|
||||||
],
|
],
|
||||||
# what syncs between devices (sync.py / syncdb.py): My foods, then the diary pointing at them;
|
# what syncs between devices (sync.py / syncdb.py): My foods, then the diary pointing at them;
|
||||||
# imported entries keep their import id, a meal's ingredients ("my:ID" in recipe) travel as ids
|
# imported entries keep their import id, a meal's ingredients ("my:ID" in recipe) travel as ids
|
||||||
|
|
|
||||||
|
|
@ -64,7 +64,7 @@ META = {
|
||||||
"pattern": "[A-Za-z]+(/[A-Za-z0-9_+-]+){0,2}|UTC", "pattern_help": "A zone name like Europe/Berlin.",
|
"pattern": "[A-Za-z]+(/[A-Za-z0-9_+-]+){0,2}|UTC", "pattern_help": "A zone name like Europe/Berlin.",
|
||||||
"help": "Empty = the phone's (the app sends it with the band's data), else this computer's (timedatectl). "
|
"help": "Empty = the phone's (the app sends it with the band's data), else this computer's (timedatectl). "
|
||||||
"Otherwise a name like Europe/Berlin or America/New_York."},
|
"Otherwise a name like Europe/Berlin or America/New_York."},
|
||||||
{"key": "gb_export", "label": "Gadgetbridge export (folder or file on the Pi)", "type": "text", "default": "",
|
{"key": "gb_export", "local": True, "label": "Gadgetbridge export (folder or file on the Pi)", "type": "text", "default": "",
|
||||||
"max": 300, "help": "Where Syncthing puts Gadgetbridge's database export, e.g. /home/pi/Sync/gadgetbridge. "
|
"max": 300, "help": "Where Syncthing puts Gadgetbridge's database export, e.g. /home/pi/Sync/gadgetbridge. "
|
||||||
"A newer export is imported by itself within ~5 minutes. Empty = off."},
|
"A newer export is imported by itself within ~5 minutes. Empty = off."},
|
||||||
],
|
],
|
||||||
|
|
|
||||||
|
|
@ -293,6 +293,11 @@ def apply(store, d):
|
||||||
old.clear()
|
old.clear()
|
||||||
old.update(new)
|
old.update(new)
|
||||||
store.units = new["units"]
|
store.units = new["units"]
|
||||||
|
try: # what changed goes to the phone (settingsync.py)
|
||||||
|
import settingsync
|
||||||
|
settingsync.publish(store, changed=True)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"settings: publish: {e}", flush=True)
|
||||||
store.om_wake.set() # Open-Meteo: the main place
|
store.om_wake.set() # Open-Meteo: the main place
|
||||||
from plugins.weather.weather import forget_places
|
from plugins.weather.weather import forget_places
|
||||||
forget_places() # extra places: re-fetched on next view
|
forget_places() # extra places: re-fetched on next view
|
||||||
|
|
|
||||||
147
dashboard/settingsync.py
Normal file
147
dashboard/settingsync.py
Normal file
|
|
@ -0,0 +1,147 @@
|
||||||
|
"""The plugins' settings, synced with the phone app (and any other dashboard of the same account).
|
||||||
|
|
||||||
|
dash_data/settings/settings.db (synced like a plugin's data — sync.specs adds it):
|
||||||
|
setting (k "food.goal_rate", v = the value as JSON) both ways; the row id is k, so every device edits
|
||||||
|
the same row and the later change wins per setting
|
||||||
|
field (k, plugin, title, pos, spec = the field as META["settings"] declares it, JSON)
|
||||||
|
written here, read by the app: its Settings page is
|
||||||
|
built from them (labels, types, options, limits, help)
|
||||||
|
Fields with "local": True (a computer's address, a model URL, a path on this machine) stay out, and so does
|
||||||
|
each plugin's on / off.
|
||||||
|
|
||||||
|
dash_config.json stays what the dashboard runs on:
|
||||||
|
publish(store) start-up and after Settings is saved here: the fields, and the values — a value the rows
|
||||||
|
don't have yet is added; after a save (changed=True) the ones that differ are written over
|
||||||
|
adopt(store) after a sync pulled something: a value another device set → checked as Settings would
|
||||||
|
(pluginhost._value + the plugin's validate_settings) and saved into dash_config.json;
|
||||||
|
one that fails the check is written back with this dashboard's value (the phone follows)
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
PATH = os.path.join(HERE, "dash_data", "settings", "settings.db")
|
||||||
|
SPEC = {"settings.db": {"setting": {"key": "NEW.k"}, "field": {"key": "NEW.k"}}} # sync.specs: plugin name "settings"
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS setting (k TEXT PRIMARY KEY, v TEXT);
|
||||||
|
CREATE TABLE IF NOT EXISTS field (k TEXT PRIMARY KEY, plugin TEXT NOT NULL, title TEXT, pos INTEGER, spec TEXT);
|
||||||
|
"""
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_store = None
|
||||||
|
|
||||||
|
|
||||||
|
def _con():
|
||||||
|
os.makedirs(os.path.dirname(PATH), exist_ok=True)
|
||||||
|
con = sqlite3.connect(PATH, timeout=30)
|
||||||
|
con.row_factory = sqlite3.Row
|
||||||
|
con.executescript(SCHEMA)
|
||||||
|
return con
|
||||||
|
|
||||||
|
|
||||||
|
def _fields():
|
||||||
|
"""[(plugin name, plugin, field)] — the synced fields of the plugins that loaded."""
|
||||||
|
import pluginhost
|
||||||
|
return [(n, p, f) for n, p in pluginhost._plugins.items() if not p.error
|
||||||
|
for f in p.meta.get("settings", []) if not f.get("local")]
|
||||||
|
|
||||||
|
|
||||||
|
def _current(store, name, f):
|
||||||
|
return (((store.cfg.get("plugins") or {}).get(name) or {})).get(f["key"], f.get("default"))
|
||||||
|
|
||||||
|
|
||||||
|
def publish(store, changed=False):
|
||||||
|
"""The fields + this dashboard's values → settings.db (only rows that change are written)."""
|
||||||
|
global _store
|
||||||
|
_store = store
|
||||||
|
with _lock:
|
||||||
|
con = _con()
|
||||||
|
try:
|
||||||
|
for pos, (name, p, f) in enumerate(_fields()):
|
||||||
|
k = f"{name}.{f['key']}"
|
||||||
|
spec = json.dumps({x: y for x, y in f.items() if x != "local"}, ensure_ascii=False, sort_keys=True)
|
||||||
|
old = con.execute("SELECT plugin, title, pos, spec FROM field WHERE k = ?", (k,)).fetchone()
|
||||||
|
new = (name, p.meta.get("title", name), pos, spec)
|
||||||
|
if not old:
|
||||||
|
con.execute("INSERT INTO field (k, plugin, title, pos, spec) VALUES (?, ?, ?, ?, ?)", (k, *new))
|
||||||
|
elif tuple(old) != new:
|
||||||
|
con.execute("UPDATE field SET plugin = ?, title = ?, pos = ?, spec = ? WHERE k = ?", (*new, k))
|
||||||
|
v = json.dumps(_current(store, name, f))
|
||||||
|
row = con.execute("SELECT v FROM setting WHERE k = ?", (k,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
con.execute("INSERT INTO setting (k, v) VALUES (?, ?)", (k, v))
|
||||||
|
elif changed and row["v"] != v:
|
||||||
|
con.execute("UPDATE setting SET v = ? WHERE k = ?", (v, k))
|
||||||
|
con.commit()
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
|
||||||
|
|
||||||
|
def adopt(store=None):
|
||||||
|
"""Values set on another device → dash_config.json (checked first). Returns how many were taken."""
|
||||||
|
import pluginhost
|
||||||
|
from config import save_config
|
||||||
|
store = store or _store
|
||||||
|
if store is None or not os.path.exists(PATH):
|
||||||
|
return 0
|
||||||
|
with _lock:
|
||||||
|
con = _con()
|
||||||
|
try:
|
||||||
|
dev = (con.execute("SELECT v FROM _sync_meta WHERE k = 'dev'").fetchone() or [None])[0] \
|
||||||
|
if con.execute("SELECT 1 FROM sqlite_master WHERE name = '_sync_meta'").fetchone() else None
|
||||||
|
rows = {r["k"]: r for r in con.execute("SELECT * FROM setting")}
|
||||||
|
plugins = {k: dict(v) for k, v in (store.cfg.get("plugins") or {}).items() if isinstance(v, dict)}
|
||||||
|
took, back = [], []
|
||||||
|
for name, p, f in _fields():
|
||||||
|
k = f"{name}.{f['key']}"
|
||||||
|
r = rows.get(k)
|
||||||
|
if not r or ("_dev" in r.keys() and r["_dev"] == dev):
|
||||||
|
continue # not set yet / this dashboard's own
|
||||||
|
mine = _current(store, name, f)
|
||||||
|
try:
|
||||||
|
v = json.loads(r["v"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
back.append((k, mine))
|
||||||
|
continue
|
||||||
|
if v == mine:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
v = pluginhost._value(f, v, k)
|
||||||
|
except pluginhost.Invalid as e:
|
||||||
|
print(f"settings: {k} = {v!r} from another device: {e} — kept {mine!r}", flush=True)
|
||||||
|
back.append((k, mine))
|
||||||
|
continue
|
||||||
|
plugins.setdefault(name, {})[f["key"]] = v
|
||||||
|
took.append((name, k, v))
|
||||||
|
for name in {n for n, _, _ in took}: # the plugin's cross-field check (food: a split of 100 %)
|
||||||
|
check = getattr(pluginhost._plugins[name].module, "validate_settings", None)
|
||||||
|
bad = check(plugins[name]) if check else None
|
||||||
|
if bad:
|
||||||
|
print(f"settings: {name} from another device: {bad[1]} — kept this dashboard's", flush=True)
|
||||||
|
for n, k, _ in [t for t in took if t[0] == name]:
|
||||||
|
f = next(f for nn, _, f in _fields() if nn == n and f"{nn}.{f['key']}" == k)
|
||||||
|
back.append((k, _current(store, n, f)))
|
||||||
|
plugins[name] = dict((store.cfg.get("plugins") or {}).get(name) or {})
|
||||||
|
took = [t for t in took if t[0] != name]
|
||||||
|
for k, mine in back: # written over: this value goes out to the others
|
||||||
|
con.execute("UPDATE setting SET v = ? WHERE k = ?", (json.dumps(mine), k))
|
||||||
|
con.commit()
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
if took:
|
||||||
|
new = dict(store.cfg, plugins=plugins)
|
||||||
|
save_config(new)
|
||||||
|
with store.lock: # the same dict the workers and pages hold
|
||||||
|
store.cfg.clear()
|
||||||
|
store.cfg.update(new)
|
||||||
|
print(f"settings: from another device: {', '.join(f'{k} = {v!r}' for _, k, v in took)}", flush=True)
|
||||||
|
return len(took)
|
||||||
|
|
||||||
|
|
||||||
|
def after_pull():
|
||||||
|
try:
|
||||||
|
adopt()
|
||||||
|
except Exception:
|
||||||
|
print(f"settings: {traceback.format_exc()}", flush=True)
|
||||||
|
|
@ -98,6 +98,9 @@ def specs():
|
||||||
for name, meta in metas.items():
|
for name, meta in metas.items():
|
||||||
for fname, tables in (meta.get("sync") or {}).items():
|
for fname, tables in (meta.get("sync") or {}).items():
|
||||||
out.append((name, os.path.join(DATA, name, fname), tables))
|
out.append((name, os.path.join(DATA, name, fname), tables))
|
||||||
|
import settingsync # the plugins' settings (settingsync.py)
|
||||||
|
for fname, tables in settingsync.SPEC.items():
|
||||||
|
out.append(("settings", os.path.join(DATA, "settings", fname), tables))
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -295,7 +298,11 @@ def sync_now():
|
||||||
raise RuntimeError("sync isn't set up (python3 sync.py setup …)")
|
raise RuntimeError("sync isn't set up (python3 sync.py setup …)")
|
||||||
st["key_bytes"] = base64.b64decode(st["key"])
|
st["key_bytes"] = base64.b64decode(st["key"])
|
||||||
prepare_new(st)
|
prepare_new(st)
|
||||||
res = {"pulled": pull(st), "pushed": push(st)}
|
pulled = pull(st)
|
||||||
|
if pulled.get("applied"): # settings changed on another device → dash_config.json
|
||||||
|
import settingsync
|
||||||
|
settingsync.after_pull()
|
||||||
|
res = {"pulled": pulled, "pushed": push(st)}
|
||||||
status.update(last=time.time(), error=None, result=res)
|
status.update(last=time.time(), error=None, result=res)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue