Compare commits

...

3 Commits

Author SHA1 Message Date
c12faa3920 app: package the desktop app as the web build, and delete the Linux embedder
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Completes the move: `linux/` is gone, replaced by the web build served by the
wrapper in a Chrome `--app` window. The icons and the .desktop installer move
out of `linux/` first -- they are not Flutter scaffolding and are still
needed; the entry now points at the packaged launcher and matches the
`--class=diet_guard_app` the wrapper passes, so the taskbar shows the app's
icon rather than a browser's.

install_arch.sh carries over the three traps each of which produced an
install that looked fine until launched: `dart build cli` rather than
`dart compile exe` (which refuses any package whose dependency graph has
native build hooks), `options=('!strip')` (makepkg would otherwise discard
the AOT snapshot, leaving a binary that runs as the bare Dart VM printing a
usage message), and no browser in `depends` (this machine's policy uninstalls
`chromium` seconds later, failing dependency resolution).

Also adds the frame-cadence instrument the performance claim is measured
with, armed by `--dart-define=DIET_GUARD_FRAME_STATS=1` and read with
`String.fromEnvironment` -- `bool.fromEnvironment` only accepts the literal
`true`, so `=1` would evaluate to false and a whole run would silently
produce no data. It reports frame-to-frame cadence rather than build/raster
durations, since work that fits the budget says nothing about the frame rate
actually achieved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 16:32:24 +02:00
aeb9376391 app: add the desktop wrapper that serves the web build and fronts GitHub
A browser cannot touch the filesystem, so the desktop app needs a second
half. This local process serves the built web assets, owns an on-disk copy of
every document and photo blob the app stores, and performs the GitHub I/O the
page cannot.

Both GitHub responsibilities are load-bearing, not convenience:

- the device-flow endpoints (github.com/login/device/*) send no CORS headers,
  so a page cannot call them at all;
- proxying api.github.com server-side is what keeps the token out of the
  browser -- the page is told `{"status":"ok"}`, never the token itself.

The wrapper falls back to the PC gate's existing
`~/.config/diet_guard/sync_token`, so this machine needs no second setup.

Details learned the hard way in the two apps migrated before this one, kept
here deliberately: loopback-only binding (the endpoints overwrite files in
$HOME with no auth), `application/wasm` for .wasm or CanvasKit renders
nothing at all, a fixed port and Chrome profile because IndexedDB is keyed by
origin, and treating a browser exit inside ~5s as a handoff to an existing
window rather than a reason to stop serving. Mirror names are rejected unless
they are plain filenames -- a `..` segment would turn a mirror write into an
arbitrary-file overwrite.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 16:31:47 +02:00
802ee0fe6d app: run the companion app's desktop target as a web build
Flutter's Linux embedder manages ~20fps at 3840x2160 -- measured on a stock
`flutter create` counter app, so it is the toolkit rather than this code --
where the same Dart rendered by Chrome sustains ~144fps (evidence in
~/todo/docs/desktop-performance-findings.md). The desktop target therefore
becomes a Flutter *web* build; Android is untouched.

`dart:io` does not fail a web *compile* -- it resolves to a stub that throws
at runtime -- so every platform edge moves behind a conditional export rather
than being discovered later as a blank white window:

- storage: `document_store*.dart`, files on Android and IndexedDB in the
  browser (mirrored to the desktop wrapper, which is what makes a wiped
  Chrome profile recoverable). Document names stay the exact pre-web
  filenames so an installed phone keeps reading its existing log.
- photos: `blob_store*.dart` plus `attached_image*.dart`, since `Image.file`
  cannot resolve an IndexedDB key. The picker itself has web support; what
  changed is the storage and display model. Camera *capture* is genuinely
  lost on desktop -- and photos never crossed devices anyway, `imagePath`
  being stripped before push.
- scheduling: `background_tasks*.dart`. A browser has no WorkManager
  equivalent -- a closed tab runs nothing -- so the desktop runs an in-page
  5-minute check while its window is open. That loses nothing on the PC,
  where `diet-guard-gate.timer` already locks the screen on an unlogged
  slot, which is strictly stronger than a notification.
- notifications: `notification_backend*.dart`, the browser Notifications API
  in place of flutter_local_notifications.
- the GitHub token: `token_vault*.dart`. On web it is *not* held by the
  browser at all -- flutter_secure_storage's web backend is WebCrypto-wrapped
  localStorage with the wrap key beside the ciphertext, which is obfuscation,
  not encryption at rest -- so the desktop wrapper owns it and proxies the
  API (`github_client_factory*.dart`).

`Platform.isAndroid` itself throws on web, so every platform branch now tests
`kIsWeb` first; the battery-optimization row (permission_handler, no web
implementation) is hidden off Android.

The desktop pushes under device id `desktop`, not `phone`: sharing an id
would have made the two devices overwrite each other's pushed log on every
tick. The Python side enumerates device directories generically, so it needs
no change.

Tests move onto the same seams -- the file-backed stores keep the atomicity
and unreadable-file guarantees where they belong.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 16:31:32 +02:00
98 changed files with 2823 additions and 1016 deletions

View File

@ -113,6 +113,40 @@ silently does **not** reach the running service.
private `kuhyx/syncs` GitHub repo (see "Cross-device sync" above)
and `~/.config/diet_guard/sync_token`.
## The companion app's desktop target is a web build
`app/` builds for two platforms, and only two: **Android** (the phone) and
**web** (the Linux desktop). There is no `app/linux/` — Flutter's GTK embedder
manages only ~20fps at 3840x2160 (measured on a stock `flutter create` app, so
it is the toolkit, not this code), where the same Dart in Chrome sustains
~144fps; see `~/todo/docs/desktop-performance-findings.md`. On the desktop the
app is the web build served by `bin/diet_guard_desktop.dart` and shown in a
Chrome `--app` window.
Consequences worth knowing before touching `app/`:
- **`dart:io` does not fail a web *compile*** — it becomes a stub that throws
at runtime, so the symptom is a blank white window, not a build error. Every
platform-specific edge goes behind a conditional export
(`document_store*.dart`, `blob_store*.dart`, `background_tasks*.dart`,
`notification_backend*.dart`, `token_vault*.dart`,
`github_client_factory*.dart`, `attached_image*.dart`). Branch on `kIsWeb`
*before* any `Platform.is…`, which itself throws on web.
- **The port and the Chrome `--user-data-dir` are fixed on purpose**
(`lib/services/desktop_wrapper.dart`). IndexedDB is keyed by origin and
lives in that profile: changing either hides the entire local food log.
- **The wrapper holds the GitHub token**, not the browser, and proxies
`api.github.com` plus the CORS-less device flow (`lib/desktop/github_proxy.dart`).
- **The desktop pushes as device id `desktop`**, the phone as `phone`, the
Python side as `pc`. Sharing an id means two devices overwrite each other's
pushed log every tick.
- **Desktop reminders only exist while the window is open.** A browser has no
WorkManager equivalent; the PC's real backstop is `diet-guard-gate.timer`,
which locks the screen. Don't "fix" this with a background service without
deciding you want a new daemon.
- `flutter create --platforms linux` would silently restore the slow path.
Don't run it in `app/`.
## Commands
- Run tests: `python -m pytest diet_guard/tests/ --cov=diet_guard --cov-branch --cov-fail-under=100`
@ -120,6 +154,11 @@ silently does **not** reach the running service.
- Test the lock manually (safe, closeable): `python -m diet_guard gate --demo`
- Run one sync tick manually: `python -m diet_guard sync`
- Install for production: `bash install.sh`
- App tests: `cd app && flutter test`
- Run the desktop app from the repo: `cd app && bash run.sh`
- Install the desktop app (Arch package + .desktop entry):
`cd app && bash install_arch.sh`
- Build the phone app: `cd app && flutter build apk --release`
## Do NOT
@ -131,6 +170,9 @@ silently does **not** reach the running service.
- Don't reintroduce a seal/lock/`chattr +i` on the budget file as a "fix" —
it was deliberately removed so the budget is freely editable and synced
between devices; see "Operational gotchas" above.
- Don't re-add a Linux embedder target to `app/`, and don't change the
wrapper's fixed port or Chrome profile path — see "The companion app's
desktop target is a web build" above.
## Flutter/Dart AI rules

View File

@ -4,7 +4,7 @@
# This file should be version controlled and should not be manually edited.
version:
revision: "c9a6c484230f8b5e408ec57be1ef71dee1e77020"
revision: "ee80f08bbf97172ec030b8751ceab557177a34a6"
channel: "stable"
project_type: app
@ -13,11 +13,11 @@ project_type: app
migration:
platforms:
- platform: root
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
- platform: linux
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
- platform: web
create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
# User provided section

View File

@ -0,0 +1,133 @@
// coverage:ignore-file
// Entry point for the desktop wrapper: resolves real paths, starts the
// server, and launches the browser. The serving logic it delegates to is
// covered by test/desktop/wrapper_server_test.dart.
import 'dart:io';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/desktop/wrapper_server.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:path/path.dart' as p;
Future<void> main(List<String> args) async {
final home = Platform.environment['HOME'];
if (home == null) {
stderr.writeln('HOME is not set; cannot resolve the data directory.');
exit(1);
}
// `dart build cli` emits bundle/bin/<exe> alongside bundle/lib/, so the
// installed layout is /opt/diet-guard/bin/diet_guard_desktop with the web
// assets one level up at /opt/diet-guard/web. --web-root overrides for
// development runs straight out of the repo.
final webRoot =
_argValue(args, '--web-root') ??
p.normalize(p.join(p.dirname(Platform.resolvedExecutable), '..', 'web'));
if (!Directory(webRoot).existsSync()) {
stderr.writeln('web assets not found at $webRoot');
exit(1);
}
// Overridable so a verification run cannot touch the real data or the real
// sync token.
final dataDir =
_argValue(args, '--data-dir') ??
p.join(home, '.local', 'share', 'diet-guard-desktop');
final proxy = GitHubProxy(
tokenPath:
_argValue(args, '--token-path') ??
p.join(home, '.config', 'diet_guard_app', 'sync_token'),
// The PC's Python gate already keeps a token for `diet-guard-sync.timer`;
// reusing it means the desktop app needs no second setup on this machine.
// Read-only: a token obtained here is written to our own path.
fallbackTokenPath:
_argValue(args, '--fallback-token-path') ??
p.join(home, '.config', 'diet_guard', 'sync_token'),
);
final server = WrapperServer(
webRoot: webRoot,
dataDir: dataDir,
gitHubProxy: proxy,
);
final port =
int.tryParse(_argValue(args, '--port') ?? '') ?? desktopWrapperPort;
await server.start(port);
stdout.writeln('diet_guard desktop serving on http://localhost:$port');
// A bare flag, not a valued option: requiring a dummy value meant passing a
// stray positional, which the AOT runtime tries to interpret as a snapshot.
if (!args.contains('--no-browser')) {
final ranLongEnough = await _launchBrowser(home, port);
if (!ranLongEnough) {
// Chrome exits immediately when it hands the URL to an instance that
// already owns the profile directory (or when a stale SingletonLock is
// left behind). Shutting down here would pull the server out from under
// a window that is still open, so keep serving instead.
stdout.writeln(
'Browser returned immediately (handed off to an existing window). '
'Still serving on http://localhost:$port -- Ctrl-C to stop.',
);
return;
}
// Otherwise the browser owned the session: its window closed, so we exit.
await server.stop();
}
}
/// Launches the app in a Chrome-family browser with a **stable** profile
/// directory, since the food log, photos and settings live in that profile.
/// Returns true when the browser ran long enough to have owned the session.
Future<bool> _launchBrowser(String home, int port) async {
// Ordered by preference, and deliberately broad: this machine runs Thorium
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
// package, so assuming any single browser is wrong. DIET_GUARD_BROWSER
// overrides.
final candidates = [
Platform.environment['DIET_GUARD_BROWSER'] ?? '',
'/opt/google/chrome/chrome',
'/opt/thorium-browser/thorium-browser',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/brave',
];
final browser = candidates.firstWhere(
(path) => path.isNotEmpty && File(path).existsSync(),
orElse: () => '',
);
if (browser.isEmpty) {
stderr.writeln(
'No Chrome-family browser found; open http://localhost:$port manually.',
);
return false;
}
// The profile directory must stay as stable as the port: IndexedDB is keyed
// by origin and lives inside this profile, so a changing path silently
// hides the entire food log.
final profile = p.join(
home,
'.local',
'share',
'diet-guard-desktop',
'profile',
);
final process = await Process.start(browser, [
'--app=http://localhost:$port',
'--user-data-dir=$profile',
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
// Without it the window inherits the browser's class and the taskbar shows
// a browser icon instead of diet_guard's.
'--class=diet_guard_app',
'--no-first-run',
]);
final started = DateTime.now();
await process.exitCode;
return DateTime.now().difference(started) > const Duration(seconds: 5);
}
String? _argValue(List<String> args, String name) {
final index = args.indexOf(name);
if (index == -1 || index + 1 >= args.length) return null;
return args[index + 1];
}

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

Before

Width:  |  Height:  |  Size: 380 B

After

Width:  |  Height:  |  Size: 380 B

View File

Before

Width:  |  Height:  |  Size: 542 B

After

Width:  |  Height:  |  Size: 542 B

View File

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

Before

Width:  |  Height:  |  Size: 726 B

After

Width:  |  Height:  |  Size: 726 B

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,34 +1,34 @@
#!/bin/bash
# ============================================================================
# Install the diet_guard_app launcher icon and .desktop entry for the Linux desktop.
# Install the diet_guard_app launcher icon and .desktop entry for the Linux
# desktop.
#
# Flutter's GTK runner has no icon of its own: my_application.cc calls
# gtk_window_set_icon_name("diet-guard-app"), which resolves through the hicolor icon
# theme. This script is what puts the icon into that theme, plus a .desktop
# entry so the app appears in application menus.
# The desktop app is a Flutter *web* build shown in a Chrome app window (the
# Linux embedder manages only ~20fps at 4K), so the launcher starts the
# wrapper, which serves the build and opens the browser.
#
# Icon PNGs are pre-rendered and committed under linux/icons/, so this script
# Icon PNGs are pre-rendered and committed under desktop/icons/, so this script
# needs no image tooling at run time. Regenerate them with:
# PYTHONPATH=~/testsAndMisc python3 -m python_pkg.app_icons \
# generate --app diet_guard_app --linux-out linux/icons
# generate --app diet_guard_app --linux-out desktop/icons
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
LINUX_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="$(dirname "$LINUX_DIR")"
readonly SCRIPT_NAME LINUX_DIR REPO_DIR
DESKTOP_SRC_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly SCRIPT_NAME DESKTOP_SRC_DIR
readonly ICON_NAME="diet-guard-app"
readonly BINARY_NAME="diet_guard_app"
# GTK derives WM_CLASS from the GApplication id in linux/CMakeLists.txt,
# not from the binary name; verified with xprop on the running window.
readonly WM_CLASS="com.kuhy.diet_guard_app"
readonly ICON_SRC_DIR="$LINUX_DIR/icons"
# Chrome sets WM_CLASS from --class, which the wrapper passes explicitly.
# Without it the window inherits the browser's own class and the taskbar shows
# a browser icon instead of this app's.
readonly WM_CLASS="diet_guard_app"
readonly ICON_SRC_DIR="$DESKTOP_SRC_DIR/icons"
readonly ICON_THEME_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor"
readonly DESKTOP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
readonly BUNDLE_BIN="$REPO_DIR/build/linux/x64/release/bundle/$BINARY_NAME"
# Installed by install_arch.sh; the repo copy is only used for development.
readonly LAUNCHER="/usr/bin/diet-guard-app"
usage() {
echo "Usage: $SCRIPT_NAME"
@ -79,7 +79,7 @@ install_desktop_entry() {
Type=Application
Name=diet guard
Comment=Diet logging and budget companion
Exec=$BUNDLE_BIN
Exec=$LAUNCHER
Icon=$ICON_NAME
Terminal=false
Categories=Utility;
@ -97,9 +97,9 @@ main() {
install_desktop_entry
echo "Installed $ICON_NAME icon into $ICON_THEME_DIR"
echo "Installed $DESKTOP_DIR/$ICON_NAME.desktop"
if [[ ! -x "$BUNDLE_BIN" ]]; then
echo "Note: $BUNDLE_BIN does not exist yet."
echo " Run 'flutter build linux --release' to make the entry launchable."
if [[ ! -x "$LAUNCHER" ]]; then
echo "Note: $LAUNCHER does not exist yet."
echo " Run 'bash install_arch.sh' to make the entry launchable."
fi
}

86
app/install_arch.sh Executable file
View File

@ -0,0 +1,86 @@
#!/bin/bash
# Builds the diet_guard companion app's desktop target and installs it as an
# Arch Linux package via pacman.
# Run from anywhere -- uses the directory of this script as the repo root.
# Requires: flutter, base-devel (provides makepkg), sudo for pacman.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# The desktop app is a Flutter *web* build served by a small local wrapper:
# Flutter's Linux embedder only reaches ~20fps at 4K, while the same Dart code
# in Chrome sustains ~144fps.
WEB_DIR="$SCRIPT_DIR/build/web"
WRAPPER_BUNDLE="$SCRIPT_DIR/build/cli/bundle"
WORK_DIR="$(mktemp -d)"
cleanup() { rm -rf "$WORK_DIR"; }
trap cleanup EXIT
# Parse version from pubspec.yaml (strip build number: 1.0.0+1 -> 1.0.0)
PKGVER="$(grep '^version:' "$SCRIPT_DIR/pubspec.yaml" \
| sed 's/^version:[[:space:]]*//' | sed 's/+.*//')"
echo "==> Building diet_guard_app $PKGVER (Flutter web release)..."
cd "$SCRIPT_DIR"
flutter build web --release
echo "==> Compiling the desktop wrapper..."
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
# with native build hooks, which `dart compile` refuses to handle even though
# the wrapper itself uses none of them.
rm -rf "$SCRIPT_DIR/build/cli"
dart build cli -o "$SCRIPT_DIR/build/cli"
echo "==> Generating PKGBUILD..."
cat > "$WORK_DIR/PKGBUILD" <<EOF
pkgname=diet-guard-app
pkgver=$PKGVER
pkgrel=1
pkgdesc='Diet logging and budget companion for diet_guard'
arch=('x86_64')
url='https://github.com/kuhyx/diet-guard'
license=('custom')
# No hard browser dependency: naming one means makepkg installs it, and this
# system has a policy that immediately removes 'chromium' again, which then
# fails dependency resolution. The wrapper discovers whatever is present.
depends=()
optdepends=('google-chrome: renders the app window'
'chromium: renders the app window')
# !strip is load-bearing: the wrapper is a Dart AOT executable with its
# snapshot embedded in the ELF, and stripping discards it. The stripped binary
# still runs, but is just the bare Dart VM printing a usage message.
options=('!strip' '!debug')
package() {
# Preserve the bundle's bin/ + lib/ layout: the executable loads its native
# libraries from ../lib and resolves the web assets from ../web.
install -dm755 "\$pkgdir/opt/diet-guard-app"
cp -r "$WRAPPER_BUNDLE/bin" "\$pkgdir/opt/diet-guard-app/bin"
# lib/ only exists when a dependency ships native code; copying it
# unconditionally would fail on a bundle that has none.
if [[ -d "$WRAPPER_BUNDLE/lib" ]]; then
cp -r "$WRAPPER_BUNDLE/lib" "\$pkgdir/opt/diet-guard-app/lib"
fi
chmod 755 "\$pkgdir/opt/diet-guard-app/bin/diet_guard_desktop"
install -dm755 "\$pkgdir/opt/diet-guard-app/web"
cp -r "$WEB_DIR/." "\$pkgdir/opt/diet-guard-app/web/"
install -dm755 "\$pkgdir/usr/bin"
cat > "\$pkgdir/usr/bin/diet-guard-app" <<'WRAPPER'
#!/bin/bash
exec /opt/diet-guard-app/bin/diet_guard_desktop "\$@"
WRAPPER
chmod 755 "\$pkgdir/usr/bin/diet-guard-app"
}
EOF
echo "==> Installing package via makepkg..."
cd "$WORK_DIR"
makepkg -sif --noconfirm
echo "==> Installing the desktop entry..."
"$SCRIPT_DIR/desktop/install_desktop_entry.sh"
echo "==> Done. 'diet-guard-app' now runs version $PKGVER installed via pacman."

View File

@ -0,0 +1,194 @@
/// The desktop wrapper's GitHub half: token storage, device flow, API proxy.
///
/// The desktop app runs in a browser, and a browser cannot do either half of
/// GitHub sync safely on its own:
///
/// * GitHub's **device-flow** endpoints (`github.com/login/device/code` and
/// the token poll) send no CORS headers, so a page cannot call them at all.
/// * A token held by the page would live in `localStorage` inside the Chrome
/// profile -- `flutter_secure_storage` on web is WebCrypto-wrapped
/// `localStorage` with the wrap key sitting beside the ciphertext, which is
/// obfuscation rather than encryption at rest.
///
/// This wrapper is a local process with neither limitation, so it owns the
/// token file and performs every authenticated call itself. The page never
/// sees the token: it asks for *status*, and its API requests are proxied
/// with the `Authorization` header attached here.
library;
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
/// GitHub's REST API base, which [GitHubProxy] fronts.
const githubApiBase = 'https://api.github.com';
/// GitHub's device-flow base (a different host, and CORS-less on purpose).
const githubDeviceBase = 'https://github.com';
/// Serves `/github/*` for the wrapper.
class GitHubProxy {
/// Creates a proxy storing its token at [tokenPath], optionally seeding
/// from [fallbackTokenPath] (the PC's own `diet_guard` sync token) when it
/// has none of its own.
GitHubProxy({
required this.tokenPath,
this.fallbackTokenPath,
http.Client? httpClient,
}) : _http = httpClient ?? http.Client();
/// File this wrapper writes tokens to (mode 600).
final String tokenPath;
/// Optional pre-existing token to fall back to, so a PC that already
/// configured `python -m diet_guard sync` needs no second setup.
final String? fallbackTokenPath;
final http.Client _http;
/// Reads the stored token, or the empty string when there is none.
Future<String> readToken() async {
for (final path in [tokenPath, ?fallbackTokenPath]) {
final file = File(path);
if (!file.existsSync()) continue;
try {
final token = (await file.readAsString()).trim();
if (token.isNotEmpty) return token;
} on FileSystemException {
continue;
}
}
return '';
}
/// Writes [token] (mode 600), or deletes the file when it is empty.
Future<void> writeToken(String token) async {
final file = File(tokenPath);
if (token.isEmpty) {
if (file.existsSync()) await file.delete();
return;
}
await file.parent.create(recursive: true);
await file.writeAsString(token);
// The token is a repo-scoped credential; keep it off other users' eyes
// the same way the Python side's sync_token is stored.
await Process.run('chmod', ['600', tokenPath]);
}
/// Handles a `/github/...` [request], with [rest] the path after `/github/`.
///
/// Returns false when [rest] matches nothing, so the caller can 404.
Future<bool> handle(HttpRequest request, String rest) async {
switch (rest) {
case 'auth/status':
final token = await readToken();
_json(request, {'configured': token.isNotEmpty});
return true;
case 'auth/token':
await writeToken((await utf8.decoder.bind(request).join()).trim());
request.response.statusCode = HttpStatus.noContent;
return true;
case 'auth/device/start':
await _deviceStart(request);
return true;
case 'auth/device/poll':
await _devicePoll(request);
return true;
}
if (rest.startsWith('api/')) {
await _proxyApi(request, rest.substring('api/'.length));
return true;
}
return false;
}
Future<void> _deviceStart(HttpRequest request) async {
final body = await _jsonBody(request);
final response = await _http.post(
Uri.parse('$githubDeviceBase/login/device/code'),
headers: const {'Accept': 'application/json'},
body: {'client_id': '${body['client_id']}', 'scope': 'repo'},
);
_passThrough(request, response);
}
Future<void> _devicePoll(HttpRequest request) async {
final body = await _jsonBody(request);
final response = await _http.post(
Uri.parse('$githubDeviceBase/login/oauth/access_token'),
headers: const {'Accept': 'application/json'},
body: {
'client_id': '${body['client_id']}',
'device_code': '${body['device_code']}',
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
},
);
Map<String, dynamic> decoded;
try {
decoded = jsonDecode(response.body) as Map<String, dynamic>;
} on FormatException {
_passThrough(request, response);
return;
}
final token = decoded['access_token'];
if (token is String && token.isNotEmpty) {
await writeToken(token);
// Deliberately does not echo the token back: the whole point of the
// proxy is that the browser never holds it.
_json(request, {'status': 'ok'});
return;
}
// Still pending / denied / expired: the page drives the poll loop, so it
// needs GitHub's own `error` value verbatim.
_json(request, decoded..remove('access_token'));
}
Future<void> _proxyApi(HttpRequest request, String path) async {
final token = await readToken();
final uri = Uri.parse(
'$githubApiBase/$path',
).replace(query: request.uri.query.isEmpty ? null : request.uri.query);
final proxied = http.Request(request.method, uri)
..headers.addAll({
'Authorization': 'Bearer $token',
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
})
..bodyBytes = await _bodyBytes(request);
final response = await http.Response.fromStream(await _http.send(proxied));
_passThrough(request, response);
}
Future<Map<String, dynamic>> _jsonBody(HttpRequest request) async {
final raw = await utf8.decoder.bind(request).join();
if (raw.isEmpty) return {};
try {
final decoded = jsonDecode(raw);
return decoded is Map<String, dynamic> ? decoded : {};
} on FormatException {
return {};
}
}
Future<List<int>> _bodyBytes(HttpRequest request) async {
final chunks = await request.toList();
return [for (final chunk in chunks) ...chunk];
}
void _passThrough(HttpRequest request, http.Response response) {
request.response
..statusCode = response.statusCode
..headers.contentType = ContentType.json
..add(response.bodyBytes);
}
void _json(HttpRequest request, Map<String, dynamic> body) {
request.response
..headers.contentType = ContentType.json
..write(jsonEncode(body));
}
/// Releases the outbound HTTP client.
void close() => _http.close();
}

View File

@ -0,0 +1,200 @@
/// Local HTTP server backing the desktop app.
///
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder
/// manages only ~20fps at 4K, where the same Dart code in Chrome sustains
/// ~144fps -- see `~/todo/docs/desktop-performance-findings.md`), so it runs
/// in a browser and cannot touch the filesystem. This process is the other
/// half of the desktop app:
///
/// * it serves the built web assets;
/// * it owns an on-disk copy of every document and photo the app stores, so a
/// wiped Chrome profile is not a total-loss event (photos in particular
/// never sync, so nothing else could restore them);
/// * it fronts GitHub, holding the sync token and running the CORS-less
/// device flow the page cannot (see `github_proxy.dart`).
///
/// Binds to loopback only. The endpoints overwrite files in the user's home
/// directory with no authentication, so exposing them on a routable address
/// would let anything on the network rewrite the food log.
library;
import 'dart:async';
import 'dart:io';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:path/path.dart' as p;
/// Serves the desktop app's web build plus its disk-backed endpoints.
class WrapperServer {
/// Creates a server serving [webRoot], mirroring the app's storage under
/// [dataDir], and proxying GitHub through [gitHubProxy].
WrapperServer({
required this.webRoot,
required this.dataDir,
required this.gitHubProxy,
});
/// Directory holding the built Flutter web assets.
final String webRoot;
/// Directory holding the on-disk copies of documents and photo blobs.
final String dataDir;
/// GitHub half of the wrapper.
final GitHubProxy gitHubProxy;
HttpServer? _server;
/// Port the server is listening on, once [start] has completed.
int get port => _server!.port;
/// Binds to loopback on [requestedPort] and begins serving.
///
/// Pass 0 to let the OS choose a port (tests do this); the desktop launcher
/// passes [desktopWrapperPort], because the browser keys IndexedDB by
/// origin -- a changing port would look like an app with no history.
Future<void> start(int requestedPort) async {
_server = await HttpServer.bind(
InternetAddress.loopbackIPv4,
requestedPort,
);
unawaited(_serve(_server!));
}
/// Stops serving and releases the port.
Future<void> stop() async {
await _server?.close(force: true);
gitHubProxy.close();
}
Future<void> _serve(HttpServer server) async {
await for (final request in server) {
try {
await _handle(request);
} on Exception {
request.response.statusCode = HttpStatus.internalServerError;
}
await request.response.close();
}
}
Future<void> _handle(HttpRequest request) async {
final path = request.uri.path;
if (path.startsWith(WrapperPaths.github)) {
final rest = path.substring(WrapperPaths.github.length);
if (await gitHubProxy.handle(request, rest)) return;
request.response.statusCode = HttpStatus.notFound;
return;
}
if (path.startsWith(WrapperPaths.documents)) {
return _storedFile(
request,
'documents',
path.substring(WrapperPaths.documents.length),
);
}
if (path.startsWith(WrapperPaths.blobs)) {
return _storedFile(
request,
'blobs',
path.substring(WrapperPaths.blobs.length),
);
}
return _static(request, path);
}
/// GET returns the stored bytes (404 when absent); POST overwrites them.
///
/// [name] is rejected unless it is a plain filename: these handlers write
/// into the user's home directory, so a `..` segment would turn a mirror
/// write into an arbitrary-file overwrite.
Future<void> _storedFile(
HttpRequest request,
String subdirectory,
String name,
) async {
if (name.isEmpty || name.contains('/') || name.contains('..')) {
request.response.statusCode = HttpStatus.badRequest;
return;
}
final file = File(p.join(dataDir, subdirectory, name));
if (request.method == 'POST') {
await file.parent.create(recursive: true);
final bytes = [for (final chunk in await request.toList()) ...chunk];
await file.writeAsBytes(bytes);
request.response.statusCode = HttpStatus.noContent;
return;
}
if (request.method != 'GET') {
request.response.statusCode = HttpStatus.methodNotAllowed;
return;
}
if (!file.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = subdirectory == 'documents'
? ContentType.json
: ContentType.binary;
await request.response.addStream(file.openRead());
}
Future<void> _static(HttpRequest request, String path) async {
final relative = path == '/' ? 'index.html' : path.substring(1);
// Reject traversal before touching the filesystem: the served root sits
// next to the user's files, so `../` must not escape it.
final resolved = p.normalize(p.join(webRoot, relative));
// coverage:ignore-start
// Defence in depth, and currently unreachable: Dart's HttpServer decodes
// and normalises the path before a handler runs, so even `%2e%2e` arrives
// already collapsed. Kept so the guarantee does not depend on that
// implementation detail holding.
if (!p.isWithin(webRoot, resolved) && resolved != p.normalize(webRoot)) {
request.response.statusCode = HttpStatus.forbidden;
return;
}
// coverage:ignore-end
final file = File(resolved);
if (!file.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = contentTypeFor(resolved);
await request.response.addStream(file.openRead());
}
/// Content type for [filePath].
///
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
/// served as anything but `application/wasm`, and the app then renders
/// nothing at all.
static ContentType contentTypeFor(String filePath) {
switch (p.extension(filePath).toLowerCase()) {
case '.html':
return ContentType.html;
case '.js' || '.mjs':
return ContentType('text', 'javascript', charset: 'utf-8');
case '.json':
return ContentType.json;
case '.wasm':
return ContentType('application', 'wasm');
case '.css':
return ContentType('text', 'css', charset: 'utf-8');
case '.png':
return ContentType('image', 'png');
case '.jpg' || '.jpeg':
return ContentType('image', 'jpeg');
case '.svg':
return ContentType('image', 'svg+xml');
case '.ttf':
return ContentType('font', 'ttf');
case '.otf':
return ContentType('font', 'otf');
case '.woff2':
return ContentType('font', 'woff2');
default:
return ContentType.binary;
}
}
}

View File

@ -2,16 +2,16 @@
/// background due-slot check, then shows the primary meal-logging screen.
library;
import 'dart:io';
import 'dart:async';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_check_service.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/frame_stats.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
@ -19,18 +19,23 @@ Future<void> main() async {
await AppSettingsService.init();
await FoodBankService.init();
final notifications = await NotificationService.init();
await notifications.requestPermission();
// WorkManager has no Linux/web/desktop implementation -- registering it
// there throws. Guard to the two platforms that ship it.
// Deliberately *not* awaited before the first frame: the browser's
// `Notification.requestPermission()` does not complete until the user
// answers the prompt, so awaiting it here left the desktop app as a blank
// white window behind the permission bubble. Scheduling is likewise
// platform-specific (WorkManager on Android, an in-page timer in the
// browser -- see background_tasks.dart) and equally not worth a delayed
// first frame.
// coverage:ignore-start
if (Platform.isAndroid || Platform.isIOS) {
await Workmanager().initialize(backgroundCheckCallbackDispatcher);
await Workmanager().registerPeriodicTask(
backgroundCheckTaskName,
backgroundCheckTaskName,
frequency: const Duration(minutes: 15),
);
}
unawaited(
notifications.requestPermission().then((_) {
return initBackgroundTasks();
}),
);
// coverage:ignore-end
// Off unless armed with --dart-define=DIET_GUARD_FRAME_STATS=1.
// coverage:ignore-start
if (frameStatsEnabled) startFrameStats();
// coverage:ignore-end
runApp(const DietGuardApp());
}

View File

@ -2,7 +2,6 @@
library;
import 'dart:async';
import 'dart:io';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
@ -10,6 +9,7 @@ import 'package:diet_guard_app/screens/photo_viewer_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/attached_image.dart';
import 'package:flutter/material.dart';
// ---------------------------------------------------------------------------
@ -636,16 +636,11 @@ class _Thumbnail extends StatelessWidget {
),
child: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.file(
File(path),
child: AttachedImage(
path: path,
width: 40,
height: 40,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) => const SizedBox(
width: 40,
height: 40,
child: Icon(Icons.broken_image),
),
),
),
);

View File

@ -3,7 +3,6 @@
library;
import 'dart:async';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
@ -16,8 +15,9 @@ import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/meal_builder_screen.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/background_tasks.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
@ -28,7 +28,6 @@ import 'package:diet_guard_app/widgets/slot_selector_row.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
import 'package:workmanager/workmanager.dart';
/// Lets the user log one food item, with food-bank autocomplete and
/// today's slot status, or hop into [MealBuilderScreen] for a composite
@ -122,10 +121,8 @@ class _LogMealScreenState extends State<LogMealScreen>
try {
final settings = await SyncSettings.load();
if (!settings.isConfigured) return;
final client = GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
final client = createGitHubClient(
settings,
httpClient: widget.httpClient,
);
try {
@ -143,24 +140,12 @@ class _LogMealScreenState extends State<LogMealScreen>
}
}
/// Queues a connectivity-gated WorkManager push so a meal logged while
/// offline still uploads on reconnect, without the app being reopened. The
/// in-process [_autoSync] covers the online case; this is the backstop.
/// [ExistingWorkPolicy.replace] coalesces a burst of logs into one pending
/// job, and backoff retries a push that fails once connectivity returns.
/// No-op off mobile (WorkManager ships only on Android/iOS).
/// Queues the platform's offline push backstop so a meal logged while
/// offline still uploads on reconnect. The in-process [_autoSync] covers
/// the online case; this is the backstop (a no-op on web, which has no
/// out-of-page scheduler -- see background_tasks.dart).
// coverage:ignore-start
Future<void> _enqueueSyncBackstop() async {
if (!Platform.isAndroid && !Platform.isIOS) return;
await Workmanager().registerOneOffTask(
syncPushTaskName,
syncPushTaskName,
constraints: Constraints(networkType: NetworkType.connected),
existingWorkPolicy: ExistingWorkPolicy.replace,
backoffPolicy: BackoffPolicy.linear,
backoffPolicyDelay: const Duration(minutes: 1),
);
}
Future<void> _enqueueSyncBackstop() => enqueueSyncBackstop();
// coverage:ignore-end

View File

@ -1,8 +1,7 @@
/// Full-screen, pinch-to-zoom view of a locally attached meal photo.
library;
import 'dart:io';
import 'package:diet_guard_app/widgets/attached_image.dart';
import 'package:flutter/material.dart';
/// Shows the image at [path] full-screen, with pinch-to-zoom and a back
@ -11,7 +10,8 @@ class PhotoViewerScreen extends StatelessWidget {
/// Creates a [PhotoViewerScreen] for the photo at [path].
const PhotoViewerScreen({required this.path, super.key});
/// Local filesystem path to the image to display.
/// Blob key of the image to display (a file path on Android, an IndexedDB
/// key in the desktop web build).
final String path;
@override
@ -24,13 +24,10 @@ class PhotoViewerScreen extends StatelessWidget {
),
body: Center(
child: InteractiveViewer(
child: Image.file(
File(path),
errorBuilder: (context, error, stackTrace) => const Icon(
Icons.broken_image,
color: Colors.white,
size: 64,
),
child: AttachedImage(
path: path,
errorIconSize: 64,
errorIconColor: Colors.white,
),
),
),

View File

@ -8,12 +8,13 @@ library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart' as crdt_sync;
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
@ -75,7 +76,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
_rewardUrlController.text = AppSettingsService.rewardUrl ?? '';
_ownerController.text = settings.owner;
_repoController.text = settings.repo;
_tokenController.text = settings.token;
// On web the stored "token" is only a stand-in for one the desktop
// wrapper holds (see TokenVault); showing it would invite the user to
// edit a literal. [_storedToken] keeps it for round-tripping.
_storedToken = settings.token;
_tokenController.text = SyncSettings.exposesTokenValue
? settings.token
: '';
_clientIdController.text = settings.clientId;
setState(() => _loading = false);
}
@ -92,12 +99,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
super.dispose();
}
SyncSettings _currentSettings() => SyncSettings(
owner: _ownerController.text.trim(),
repo: _repoController.text.trim(),
token: _tokenController.text.trim(),
clientId: _clientIdController.text.trim(),
);
/// The token as loaded, so a platform that cannot display it (web) still
/// round-trips it instead of blanking it on the next save.
String _storedToken = '';
SyncSettings _currentSettings() {
final typed = _tokenController.text.trim();
return SyncSettings(
owner: _ownerController.text.trim(),
repo: _repoController.text.trim(),
// The `_storedToken` side is web-only (the wrapper holds the real
// token), so it is unreachable from a VM test.
token: typed.isEmpty && !SyncSettings.exposesTokenValue
// coverage:ignore-line
? _storedToken
: typed,
clientId: _clientIdController.text.trim(),
);
}
/// Persists the temptation-bundling reward fields, blank -> null.
Future<void> _saveReward() async {
@ -128,10 +147,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
setState(() => _clientIdController.text = clientId);
await _currentSettings().save();
}
final auth = GitHubDeviceAuth(
clientId: clientId,
httpClient: widget.httpClient,
);
final auth = createDeviceAuth(clientId, httpClient: widget.httpClient);
try {
final device = await auth.requestDeviceCode();
if (!mounted) return;
@ -141,7 +157,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
builder: (_) => _DeviceCodeDialog(device: device, auth: auth),
);
if (token != null && token.isNotEmpty) {
setState(() => _tokenController.text = token);
setState(() {
_storedToken = token;
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
});
_showMessage('Connected — syncing…');
await _currentSettings().save();
await _syncAfterConnect();
@ -157,12 +176,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
/// to work immediately, with clear confirmation either way.
Future<void> _syncAfterConnect() async {
final settings = _currentSettings();
final client = crdt_sync.GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
await runSync(client);
_showMessage('Connected and synced.');
@ -184,12 +198,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Future<void> _testConnection() async {
setState(() => _busy = true);
final settings = _currentSettings();
final client = crdt_sync.GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
final ok = await client.canAccessRepo();
_showMessage(ok ? 'Connection OK.' : 'Connection failed.');
@ -205,12 +214,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
setState(() => _busy = true);
final settings = _currentSettings();
await settings.save();
final client = crdt_sync.GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: widget.httpClient,
);
final client = createGitHubClient(settings, httpClient: widget.httpClient);
try {
await runSync(client);
_showMessage('Synced.');
@ -241,6 +245,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
}
}
/// True on the one platform with OEM battery optimization to exempt from.
///
/// Uses [defaultTargetPlatform] rather than `Platform.isAndroid` because
/// `dart:io` is a throwing stub in the desktop web build.
bool get _isAndroid =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
@override
Widget build(BuildContext context) {
if (_loading) {
@ -335,8 +346,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
TextField(
controller: _tokenController,
obscureText: true,
decoration: const InputDecoration(
decoration: InputDecoration(
labelText: 'Personal access token (fallback)',
// Both wrapper hints are web-only; a VM test always takes
// the null branch.
// coverage:ignore-start
helperText: SyncSettings.exposesTokenValue
? null
: _storedToken.isEmpty
? 'Stored by the desktop wrapper, never by the browser'
: 'A token is stored by the desktop wrapper; type here '
'only to replace it',
// coverage:ignore-end
helperMaxLines: 2,
),
),
],
@ -365,18 +387,29 @@ class _SettingsScreenState extends State<SettingsScreen> {
Text('Notifications', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
Text(
'A background check nags you every ~15 min if a meal slot is '
'overdue. Aggressive OEM battery optimization (MIUI, some '
'Samsung configs) can delay this well past 15 min -- request an '
'exemption for reliable nagging.',
_isAndroid
? 'A background check nags you every ~15 min if a meal slot '
'is overdue. Aggressive OEM battery optimization (MIUI, '
'some Samsung configs) can delay this well past 15 min '
'-- request an exemption for reliable nagging.'
: 'A check runs every 5 min while this window is open and '
'notifies you about an overdue meal slot. A browser '
'cannot run anything once the window is closed -- on '
'the PC the real backstop is the diet_guard gate, '
'which locks the screen instead.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: _requestBatteryExemption,
icon: const Icon(Icons.battery_alert),
label: const Text('Disable battery optimization'),
),
// Battery-optimization exemption is an Android-only concept, and
// `permission_handler` has no web implementation at all; the row
// would throw rather than degrade if it were shown in the browser.
if (_isAndroid) ...[
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: _requestBatteryExemption,
icon: const Icon(Icons.battery_alert),
label: const Text('Disable battery optimization'),
),
],
if (_status != null) ...[
const SizedBox(height: 16),
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),

View File

@ -2,11 +2,10 @@
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// Singleton storing lightweight settings such as the daily kcal goal.
///
@ -18,14 +17,18 @@ import 'package:path_provider/path_provider.dart';
/// nothing of its own to contribute yet, rather than silently syncing the
/// unset default.
class AppSettingsService {
AppSettingsService._(this._file);
AppSettingsService._(this._store);
/// Document name this service owns, unchanged from the pre-web on-disk
/// filename so an installed phone keeps reading its existing settings.
static const documentName = 'app_settings.json';
static AppSettingsService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static AppSettingsService get instance => _instance!;
final File _file;
final DocumentStore _store;
int _dailyKcalGoal = 2200;
DateTime? _dailyKcalGoalUpdatedAt;
String? _rewardLabel;
@ -49,13 +52,15 @@ class AppSettingsService {
/// Returns the configured temptation-bundling reward URL, or null.
static String? get rewardUrl => _instance?._rewardUrl;
/// Initialises the singleton, pointing at the app's documents directory.
/// Initialises the singleton against the platform document store (files on
/// Android, IndexedDB in the browser-hosted desktop app).
static Future<AppSettingsService> init() async {
if (_instance != null) return _instance!;
final dir = await getApplicationDocumentsDirectory();
final svc = AppSettingsService._(
File(p.join(dir.path, 'app_settings.json')),
);
// Resolving the platform store is a plugin call (path_provider /
// IndexedDB), not reachable from `flutter test`.
// coverage:ignore-start
final svc = AppSettingsService._(await openDocumentStore());
// coverage:ignore-end
await svc._load();
_instance = svc;
return svc;
@ -63,35 +68,29 @@ class AppSettingsService {
/// Resets the singleton so [init] can be called again in tests.
///
/// When [testDir] is given, reads/writes go there instead of the real
/// documents directory.
/// When [store] is given, reads/writes go there instead of the real
/// platform store.
@visibleForTesting
static void resetForTesting({Directory? testDir}) {
_instance = testDir == null
? null
: AppSettingsService._(
File(p.join(testDir.path, 'app_settings.json')),
);
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : AppSettingsService._(store);
}
/// Initialises from [testDir], calling [_load], for use in unit tests.
/// Initialises from [store], calling [_load], for use in unit tests.
///
/// Bypasses [getApplicationDocumentsDirectory] so tests don't need platform
/// channels.
/// Bypasses [openDocumentStore] so tests need no platform channels.
@visibleForTesting
static Future<AppSettingsService> initForTesting(Directory testDir) async {
final svc = AppSettingsService._(
File(p.join(testDir.path, 'app_settings.json')),
);
static Future<AppSettingsService> initForTesting(DocumentStore store) async {
final svc = AppSettingsService._(store);
await svc._load();
_instance = svc;
return svc;
}
Future<void> _load() async {
if (!_file.existsSync()) return;
final raw = await _store.read(documentName);
if (raw == null) return;
try {
final data = jsonDecode(await _file.readAsString());
final data = jsonDecode(raw);
if (data is Map && data['daily_kcal_goal'] is int) {
_dailyKcalGoal = data['daily_kcal_goal'] as int;
}
@ -141,12 +140,12 @@ class AppSettingsService {
await _writeToDisk();
}
/// Writes the full current in-memory state to disk -- the single write
/// Writes the full current in-memory state to the store -- the single write
/// path every setter funnels through, so no two methods can race on
/// independently overwriting the same JSON file.
/// independently overwriting the same document.
Future<void> _writeToDisk() async {
await _file.parent.create(recursive: true);
await _file.writeAsString(
await _store.write(
documentName,
jsonEncode({
'daily_kcal_goal': _dailyKcalGoal,
'daily_kcal_goal_updated_at': _dailyKcalGoalUpdatedAt

View File

@ -1,38 +1,22 @@
/// WorkManager-driven periodic check: re-runs the same due/missing-slot
/// logic diet_guard's `_gate.py` uses to decide whether to lock the PC, and
/// syncs notifications to match. Registered as a 15-minute periodic task
/// (WorkManager's periodic floor) rather than four fixed exact alarms --
/// more robust against OEM background-kill behavior, at the cost of ±15 min
/// precision (accepted; see the project plan). Deliberately **not**
/// requesting `SCHEDULE_EXACT_ALARM` for this reason -- don't reach for it
/// to "fix" perceived lateness.
/// WorkManager wiring for the periodic due-slot check (Android/iOS only).
///
/// Registered as a 15-minute periodic task (WorkManager's periodic floor)
/// rather than four fixed exact alarms -- more robust against OEM
/// background-kill behavior, at the cost of ±15 min precision (accepted; see
/// the project plan). Deliberately **not** requesting `SCHEDULE_EXACT_ALARM`
/// for this reason -- don't reach for it to "fix" perceived lateness.
///
/// The check itself lives in `due_slot_check.dart` so it stays free of the
/// `workmanager` import, which has no web implementation.
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:workmanager/workmanager.dart';
/// Unique WorkManager task name for the periodic due-slot check.
const String backgroundCheckTaskName = 'diet_guard.background_check';
/// Reads the local log, computes today's due-but-unlogged slots as of
/// [now] (defaults to the real clock), and syncs notifications to match.
///
/// Extracted from [backgroundCheckCallbackDispatcher] so this logic is
/// unit-testable without the real WorkManager plugin, which only runs as a
/// true background isolate on-device. [now] is injectable for the same
/// reason `slot.dart`'s functions are clock-free: a test should not depend
/// on the wall-clock hour it happens to run at.
Future<void> checkAndNotify({DateTime? now}) async {
await LogStorageService.init();
await NotificationService.init();
final logged = await LogStorageService.instance.loggedSlotsToday();
final due = missingSlots(now ?? DateTime.now(), logged);
await NotificationService.instance.syncToSlots(due);
}
/// WorkManager entry point invoked by the OS on each periodic tick.
///
/// Deliberately thin: all logic lives in [checkAndNotify] so it stays unit

View File

@ -5,9 +5,9 @@
/// reconnect and uploads the log without the app being reopened.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
@ -41,12 +41,7 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
return false; // couldn't read config in-isolate; let WorkManager retry
}
if (!settings.isConfigured) return true; // nothing to push; don't retry
final client = GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: httpClient,
);
final client = createGitHubClient(settings, httpClient: httpClient);
try {
await runSync(client);
return true;

View File

@ -0,0 +1,10 @@
/// Platform entry point for scheduling the app's recurring work.
///
/// Conditional export because `workmanager` has no browser implementation at
/// all -- a closed tab runs nothing. Android schedules real OS-managed
/// background work; the browser-hosted desktop app runs an in-page timer that
/// lives only as long as its window (see `background_tasks_web.dart`).
library;
export 'background_tasks_io.dart'
if (dart.library.js_interop) 'background_tasks_web.dart';

View File

@ -0,0 +1,46 @@
/// WorkManager-backed scheduling, used on Android (and iOS).
library;
import 'dart:io';
import 'package:diet_guard_app/services/background_check_service.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:workmanager/workmanager.dart';
/// True on the two platforms that ship a WorkManager implementation.
///
/// Every entry point below is a no-op elsewhere: registering WorkManager on a
/// platform without it throws, which at app start would mean a blank window.
bool get _hasWorkManager => Platform.isAndroid || Platform.isIOS;
/// Registers the 15-minute periodic due-slot check with the OS.
// coverage:ignore-start
Future<void> initBackgroundTasks() async {
if (!_hasWorkManager) return;
await Workmanager().initialize(backgroundCheckCallbackDispatcher);
await Workmanager().registerPeriodicTask(
backgroundCheckTaskName,
backgroundCheckTaskName,
frequency: const Duration(minutes: 15),
);
}
/// Queues a connectivity-gated push so a meal logged while offline still
/// uploads on reconnect, without the app being reopened.
///
/// The in-process auto-sync covers the online case; this is the backstop.
/// [ExistingWorkPolicy.replace] coalesces a burst of logs into one pending
/// job, and backoff retries a push that fails once connectivity returns.
Future<void> enqueueSyncBackstop() async {
if (!_hasWorkManager) return;
await Workmanager().registerOneOffTask(
syncPushTaskName,
syncPushTaskName,
constraints: Constraints(networkType: NetworkType.connected),
existingWorkPolicy: ExistingWorkPolicy.replace,
backoffPolicy: BackoffPolicy.linear,
backoffPolicyDelay: const Duration(minutes: 1),
);
}
// coverage:ignore-end

View File

@ -0,0 +1,54 @@
/// In-page scheduling for the browser-hosted desktop app.
///
/// A browser has no equivalent of WorkManager: a closed tab runs nothing, so
/// the due-slot check can only run while the desktop window is open. That is
/// an accepted, deliberate reduction rather than an oversight -- on the PC the
/// real backstop is `diet-guard-gate.timer`, which *locks the screen* on an
/// unlogged slot and is strictly stronger than any notification this app could
/// raise.
library;
import 'dart:async';
import 'package:diet_guard_app/services/due_slot_check.dart';
/// How often the in-page check re-evaluates due slots.
///
/// Five minutes rather than WorkManager's 15: a foreground timer is cheap,
/// and the window is usually open for a short session, so a long period would
/// often mean the check never runs at all.
const inPageCheckInterval = Duration(minutes: 5);
Timer? _timer;
/// Starts the in-page periodic due-slot check (idempotent).
///
/// Runs one check immediately so opening the window is itself a check, then
/// repeats every [inPageCheckInterval] for as long as the page lives.
Future<void> initBackgroundTasks() async {
if (_timer != null) return;
_timer = Timer.periodic(inPageCheckInterval, (_) => _runCheck());
await _runCheck();
}
/// No-op on web: there is no out-of-page scheduler to hand a retry to.
///
/// A push that fails while the window is open is retried by the next
/// foreground sync; one that fails as the window closes is picked up on the
/// next launch.
Future<void> enqueueSyncBackstop() async {}
/// Cancels the in-page timer. Exposed so a test can stop the periodic work it
/// started rather than leaking it into the next test.
void stopBackgroundTasks() {
_timer?.cancel();
_timer = null;
}
Future<void> _runCheck() async {
try {
await checkAndNotify();
} on Exception {
// A failed check must never take the app down: the next tick retries.
}
}

View File

@ -0,0 +1,22 @@
/// Byte-blob persistence for attached meal photos.
library;
import 'dart:typed_data';
/// Stores and retrieves photo bytes under an opaque key.
///
/// The key is what ends up in [FoodEntry.imagePath]: an absolute file path on
/// Android (unchanged from before the web build existed, so installed phones
/// keep resolving their existing photos) and an IndexedDB key in the browser.
/// Callers must treat it as opaque and never join, split or stat it.
///
/// Deliberately free of `dart:io` -- see `document_store.dart` for why that
/// matters for the web build.
abstract class BlobStore {
/// Stores [bytes] as a new blob whose key ends with [extension] (`.jpg`),
/// returning the key.
Future<String> put(String extension, Uint8List bytes);
/// Returns the bytes stored under [key], or null when it is gone.
Future<Uint8List?> get(String key);
}

View File

@ -0,0 +1,4 @@
/// Platform entry point for opening the photo blob store.
library;
export 'blob_store_io.dart' if (dart.library.js_interop) 'blob_store_web.dart';

View File

@ -0,0 +1,49 @@
/// File-backed [BlobStore] used on Android.
library;
import 'dart:io';
import 'dart:typed_data';
import 'package:diet_guard_app/services/blob_store.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
/// [BlobStore] keeping one file per photo under `<documents>/images/`.
///
/// Keys are absolute paths, exactly as they were before photos went through
/// a store, so an already-installed phone keeps resolving the `imagePath` of
/// every photo it has ever attached.
class FileBlobStore implements BlobStore {
/// Creates a store keeping its blobs under `<[documentsDirectory]>/images`.
FileBlobStore(this.documentsDirectory);
/// Directory whose `images/` subdirectory holds the photos.
final Directory documentsDirectory;
@override
Future<String> put(String extension, Uint8List bytes) async {
final imagesDir = Directory(p.join(documentsDirectory.path, 'images'));
await imagesDir.create(recursive: true);
final dest = File(p.join(imagesDir.path, '${const Uuid().v4()}$extension'));
await dest.writeAsBytes(bytes);
return dest.path;
}
@override
Future<Uint8List?> get(String key) async {
final file = File(key);
if (!file.existsSync()) return null;
try {
return await file.readAsBytes();
} on FileSystemException {
return null;
}
}
}
/// Opens the platform blob store (the app's documents directory).
// coverage:ignore-start
Future<BlobStore> openBlobStore() async =>
FileBlobStore(await getApplicationDocumentsDirectory());
// coverage:ignore-end

View File

@ -0,0 +1,94 @@
/// IndexedDB-backed [BlobStore] for the browser-hosted desktop app.
library;
import 'dart:typed_data';
import 'package:diet_guard_app/services/blob_store.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:http/http.dart' as http;
import 'package:idb_shim/idb_browser.dart';
import 'package:uuid/uuid.dart';
/// [BlobStore] keeping photo bytes in IndexedDB, mirrored to the desktop
/// wrapper's on-disk copy.
///
/// Photos never sync (`imagePath` is stripped before push and ignored on
/// pull), so the wrapper mirror is the *only* thing standing between a wiped
/// Chrome profile and permanently losing them -- unlike the food log, which
/// GitHub would eventually restore.
class IndexedDbBlobStore implements BlobStore {
/// Creates a store over an already-open [database], mirroring to [baseUrl].
IndexedDbBlobStore(
this._database, {
this.baseUrl = desktopWrapperOrigin,
http.Client? httpClient,
}) : _client = httpClient ?? http.Client();
final Database _database;
final http.Client _client;
/// Origin of the desktop wrapper.
final String baseUrl;
/// Object store holding one entry per photo.
static const storeName = 'blobs';
/// IndexedDB database name.
static const databaseName = 'diet_guard_blobs';
@override
Future<String> put(String extension, Uint8List bytes) async {
final key = '${const Uuid().v4()}$extension';
final txn = _database.transaction(storeName, idbModeReadWrite);
await txn.objectStore(storeName).put(bytes, key);
await txn.completed;
await _writeMirror(key, bytes);
return key;
}
@override
Future<Uint8List?> get(String key) async {
final txn = _database.transaction(storeName, idbModeReadOnly);
final value = await txn.objectStore(storeName).getObject(key);
await txn.completed;
if (value is Uint8List) return value;
if (value is List<int>) return Uint8List.fromList(value);
// Missing locally: recover from the wrapper's disk copy (cleared profile).
return _readMirror(key);
}
Future<Uint8List?> _readMirror(String key) async {
try {
final response = await _client.get(_uriFor(key));
if (response.statusCode != 200 || response.bodyBytes.isEmpty) return null;
return response.bodyBytes;
} on Exception {
return null;
}
}
Future<void> _writeMirror(String key, Uint8List bytes) async {
try {
await _client.post(_uriFor(key), body: bytes);
} on Exception {
// Best-effort by design, like the document mirror.
}
}
Uri _uriFor(String key) => Uri.parse('$baseUrl${WrapperPaths.blobs}$key');
}
/// Opens (creating if needed) the IndexedDB-backed blob store.
Future<BlobStore> openBlobStore() async {
final database = await idbFactoryBrowser.open(
IndexedDbBlobStore.databaseName,
version: 1,
onUpgradeNeeded: (event) {
final db = event.database;
if (!db.objectStoreNames.contains(IndexedDbBlobStore.storeName)) {
db.createObjectStore(IndexedDbBlobStore.storeName);
}
},
);
return IndexedDbBlobStore(database);
}

View File

@ -0,0 +1,32 @@
/// Shared constants between the web app and the desktop wrapper that serves it.
library;
/// The fixed port the desktop wrapper serves on.
///
/// **Do not change this casually.** IndexedDB (the food log, the food bank,
/// the settings and the photo blobs) is keyed by origin, so a different port
/// looks like a different app with no history at all. The launcher, the
/// packaging and `bin/diet_guard_desktop.dart` must all use this value, and
/// the Chrome `--user-data-dir` must stay equally fixed for the same reason.
///
/// 8730 is `~/todo`'s wrapper and 8731 is `~/habit_stack`'s; this is the next
/// free one so all three can run at once.
const desktopWrapperPort = 8732;
/// Origin of the desktop wrapper, e.g. `http://localhost:8732`.
const desktopWrapperOrigin = 'http://localhost:$desktopWrapperPort';
/// URL paths the wrapper serves.
///
/// Kept beside the port so the client and the server cannot drift apart; the
/// server mirrors these constants rather than re-spelling the strings.
abstract final class WrapperPaths {
/// Prefix for document reads/writes: `/documents/<name>`.
static const documents = '/documents/';
/// Prefix for photo-blob reads/writes: `/blobs/<key>`.
static const blobs = '/blobs/';
/// Prefix for the GitHub proxy (see `wrapper_server.dart`).
static const github = '/github/';
}

View File

@ -0,0 +1,24 @@
/// Named-document persistence, independent of where the documents live.
library;
/// Reads and writes whole documents by name (`food_log.json`,
/// `food_bank.json`, `app_settings.json`).
///
/// Deliberately free of `dart:io` so the storage services compile for web:
/// the desktop app is a Flutter web build, and a single `dart:io` import
/// anywhere in the graph turns into a stub that throws at runtime (a blank
/// white window, not a build error). Implementations live in
/// `document_store_io.dart` (files) and `document_store_web.dart`
/// (IndexedDB), selected by the conditional export in
/// `document_store_factory.dart`.
///
/// Whole-document rather than key-value because every caller already
/// serialises a complete JSON structure, and a partial write of any of them
/// would be worse than none.
abstract class DocumentStore {
/// Returns the stored contents of [name], or null if nothing is stored.
Future<String?> read(String name);
/// Overwrites [name] with [contents].
Future<void> write(String name, String contents);
}

View File

@ -0,0 +1,9 @@
/// Platform entry point for opening the document store.
///
/// Conditional export because `dart:io` cannot even be *imported* in a web
/// compile: Android keeps the file-backed store, the browser-hosted desktop
/// app gets IndexedDB.
library;
export 'document_store_io.dart'
if (dart.library.js_interop) 'document_store_web.dart';

View File

@ -0,0 +1,64 @@
/// File-backed [DocumentStore] used on Android (and any `dart:io` platform).
library;
import 'dart:io';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// [DocumentStore] backed by one file per document.
///
/// Document names are the full on-disk filenames (`food_log.json`, …) rather
/// than bare keys, so the files an already-installed phone holds keep their
/// exact paths through this refactor -- renaming them would look to the app
/// like a device with no history.
class FileDocumentStore implements DocumentStore {
/// Creates a store keeping its documents under [directory].
FileDocumentStore(this.directory);
/// Directory holding the document files.
final Directory directory;
File _fileFor(String name) => File(p.join(directory.path, name));
@override
Future<String?> read(String name) async {
final file = _fileFor(name);
if (!file.existsSync()) return null;
try {
return await file.readAsString();
} on FileSystemException {
// An unreadable file is treated as absent; callers fall back to empty
// rather than failing to start.
return null;
}
}
/// Writes to a unique temp file then atomically renames it over the real
/// one, so a concurrent reader never observes a half-written document.
///
/// The temp name carries both the pid and a per-process counter: the pid
/// separates the foreground app from the connectivity-gated background
/// push, which can `runSync` -> write from a separate isolate, and the
/// counter separates two overlapping writes *within* one process (two
/// setters awaiting the same document would otherwise both create the same
/// temp file, and the second rename would fail with the first's file
/// already gone).
@override
Future<void> write(String name, String contents) async {
final file = _fileFor(name);
await file.parent.create(recursive: true);
final tmp = File('${file.path}.$pid.${_writeCounter++}.tmp');
await tmp.writeAsString(contents);
await tmp.rename(file.path);
}
static int _writeCounter = 0;
}
/// Opens the platform document store (the app's documents directory).
// coverage:ignore-start
Future<DocumentStore> openDocumentStore() async =>
FileDocumentStore(await getApplicationDocumentsDirectory());
// coverage:ignore-end

View File

@ -0,0 +1,96 @@
/// IndexedDB-backed [DocumentStore] used by the browser-hosted desktop app.
library;
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:http/http.dart' as http;
import 'package:idb_shim/idb_browser.dart';
/// [DocumentStore] backed by IndexedDB, mirrored to the desktop wrapper's
/// on-disk copy.
///
/// IndexedDB rather than `localStorage`: the latter caps at roughly 5-10MB per
/// origin and is evicted more eagerly, and these documents are the desktop
/// device's primary copy of the food log.
///
/// The wrapper mirror is the recovery path for a wiped Chrome profile. GitHub
/// sync would eventually restore the log too, but only what other devices have
/// already seen -- a meal logged on this desktop and never pushed exists
/// nowhere else. Reads fall back to the mirror when IndexedDB is empty; writes
/// to it are best-effort so the app still works opened in a plain browser tab
/// with no wrapper running.
class IndexedDbDocumentStore implements DocumentStore {
/// Creates a store over an already-open [database], mirroring to [baseUrl].
IndexedDbDocumentStore(
this._database, {
this.baseUrl = desktopWrapperOrigin,
http.Client? httpClient,
}) : _client = httpClient ?? http.Client();
final Database _database;
final http.Client _client;
/// Origin of the desktop wrapper.
final String baseUrl;
/// Object store holding one entry per document name.
static const storeName = 'documents';
/// IndexedDB database name.
static const databaseName = 'diet_guard';
@override
Future<String?> read(String name) async {
final txn = _database.transaction(storeName, idbModeReadOnly);
final value = await txn.objectStore(storeName).getObject(name);
await txn.completed;
if (value is String) return value;
// Empty IndexedDB: either a first run or a cleared profile. Recover from
// the wrapper's disk copy rather than silently starting from nothing.
return _readMirror(name);
}
@override
Future<void> write(String name, String contents) async {
final txn = _database.transaction(storeName, idbModeReadWrite);
await txn.objectStore(storeName).put(contents, name);
await txn.completed;
await _writeMirror(name, contents);
}
Future<String?> _readMirror(String name) async {
try {
final response = await _client.get(_uriFor(name));
if (response.statusCode != 200 || response.body.isEmpty) return null;
return response.body;
} on Exception {
return null;
}
}
Future<void> _writeMirror(String name, String contents) async {
try {
await _client.post(_uriFor(name), body: contents);
} on Exception {
// Best-effort by design; see the class docs.
}
}
Uri _uriFor(String name) =>
Uri.parse('$baseUrl${WrapperPaths.documents}$name');
}
/// Opens (creating if needed) the IndexedDB-backed document store.
Future<DocumentStore> openDocumentStore() async {
final database = await idbFactoryBrowser.open(
IndexedDbDocumentStore.databaseName,
version: 1,
onUpgradeNeeded: (event) {
final db = event.database;
if (!db.objectStoreNames.contains(IndexedDbDocumentStore.storeName)) {
db.createObjectStore(IndexedDbDocumentStore.storeName);
}
},
);
return IndexedDbDocumentStore(database);
}

View File

@ -0,0 +1,27 @@
/// The periodic due/missing-slot check, shared by every platform's scheduler.
///
/// Re-runs the same due/missing-slot logic diet_guard's `_gate.py` uses to
/// decide whether to lock the PC, and syncs notifications to match. Kept in
/// its own library, free of any scheduler plugin, because the two platforms
/// drive it very differently: Android hands it to WorkManager as a real
/// background isolate, while the browser-hosted desktop app can only run it
/// from an in-page timer while its window is open (see
/// `background_tasks_web.dart`).
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_service.dart';
/// Reads the local log, computes today's due-but-unlogged slots as of
/// [now] (defaults to the real clock), and syncs notifications to match.
///
/// [now] is injectable so a test does not depend on the wall-clock hour it
/// happens to run at, the same reason `slot.dart`'s functions are clock-free.
Future<void> checkAndNotify({DateTime? now}) async {
await LogStorageService.init();
await NotificationService.init();
final logged = await LogStorageService.instance.loggedSlotsToday();
final due = missingSlots(now ?? DateTime.now(), logged);
await NotificationService.instance.syncToSlots(due);
}

View File

@ -5,16 +5,15 @@
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:diet_guard_app/services/fuzzy.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// Below this similarity ratio a non-substring candidate is dropped.
/// Mirrors `_foodbank._FUZZY_THRESHOLD`.
@ -40,41 +39,46 @@ String _displayName(FoodBankRecord record, String key) =>
/// Singleton service for the locally-rebuilt food bank.
class FoodBankService {
FoodBankService._(this._file);
FoodBankService._(this._store);
/// Document holding the log-derived bank. Unchanged from the pre-web
/// on-disk filename so an installed phone keeps its existing bank.
static const documentName = 'food_bank.json';
/// Document holding the manually-curated bank.
static const manualDocumentName = 'food_bank_manual.json';
static FoodBankService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static FoodBankService get instance => _instance!;
final File _file;
final DocumentStore _store;
/// Initializes the singleton, pointing at the app's documents directory.
static Future<FoodBankService> init() async {
if (_instance != null) return _instance!;
final dir = await getApplicationDocumentsDirectory();
final svc = FoodBankService._(File(p.join(dir.path, 'food_bank.json')));
final svc = FoodBankService._(await openDocumentStore());
_instance = svc;
return svc;
}
/// Resets the singleton so [init] can be called again in tests.
@visibleForTesting
static void resetForTesting({Directory? testDir}) {
_instance = testDir == null
? null
: FoodBankService._(File(p.join(testDir.path, 'food_bank.json')));
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : FoodBankService._(store);
}
/// Reads the persisted bank (empty map on a missing/unparsable file).
Future<Map<String, FoodBankRecord>> readBank() async {
if (!_file.existsSync()) return {};
String raw;
try {
raw = await _file.readAsString();
} on FileSystemException {
return {};
}
/// Reads the persisted bank (empty map on a missing/unparsable document).
Future<Map<String, FoodBankRecord>> readBank() => _readBank(documentName);
/// Persists [bank].
Future<void> writeBank(Map<String, FoodBankRecord> bank) =>
_writeBank(documentName, bank);
Future<Map<String, FoodBankRecord>> _readBank(String name) async {
final raw = await _store.read(name);
if (raw == null) return {};
Object? data;
try {
data = jsonDecode(raw);
@ -93,14 +97,15 @@ class FoodBankService {
return result;
}
/// Persists [bank] to disk, creating the parent directory if needed.
Future<void> writeBank(Map<String, FoodBankRecord> bank) async {
await _file.parent.create(recursive: true);
Future<void> _writeBank(
String name,
Map<String, FoodBankRecord> bank,
) async {
final encoded = <String, Object?>{
for (final mapEntry in bank.entries)
mapEntry.key: mapEntry.value.toJson(),
};
await _file.writeAsString(jsonEncode(encoded));
await _store.write(name, jsonEncode(encoded));
}
/// Rebuilds the bank by replaying [log]'s entries in a fixed, device-
@ -204,44 +209,11 @@ class FoodBankService {
// Manual bank (food items added directly without logging them as eaten)
// ---------------------------------------------------------------------------
File get _manualFile =>
File(p.join(_file.parent.path, 'food_bank_manual.json'));
Future<Map<String, FoodBankRecord>> _readManualBank() =>
_readBank(manualDocumentName);
Future<Map<String, FoodBankRecord>> _readManualBank() async {
final file = _manualFile;
if (!file.existsSync()) return {};
String raw;
try {
raw = await file.readAsString();
} on FileSystemException {
return {};
}
Object? data;
try {
data = jsonDecode(raw);
} on FormatException {
return {};
}
if (data is! Map) return {};
final result = <String, FoodBankRecord>{};
for (final entry in data.entries) {
final key = entry.key;
final value = entry.value;
if (key is String && value is Map) {
result[key] = FoodBankRecord.fromJson(value.cast<String, dynamic>());
}
}
return result;
}
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) async {
final file = _manualFile;
await file.parent.create(recursive: true);
final encoded = <String, Object?>{
for (final entry in bank.entries) entry.key: entry.value.toJson(),
};
await file.writeAsString(jsonEncode(encoded));
}
Future<void> _writeManualBank(Map<String, FoodBankRecord> bank) =>
_writeBank(manualDocumentName, bank);
/// Adds or updates [record] in the manually-curated bank without logging it
/// as eaten. A repeated call with the same normalized name overwrites the

View File

@ -0,0 +1,75 @@
/// Optional frame-cadence instrument, armed with
/// `--dart-define=DIET_GUARD_FRAME_STATS=1`.
///
/// Reports **frame-to-frame cadence**, not build/raster durations: work that
/// fits the budget says nothing about the frame rate actually achieved, which
/// is the number the desktop migration exists to move.
///
/// Read with `String.fromEnvironment`, never `bool.fromEnvironment` -- the
/// latter only accepts the literal `true`, so `=1` would silently evaluate to
/// false and a whole measurement run would produce no data while looking like
/// a broken callback.
library;
import 'dart:async';
import 'dart:convert';
import 'dart:ui' show FramePhase;
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:flutter/scheduler.dart';
import 'package:http/http.dart' as http;
/// Whether the instrument is armed for this build.
const frameStatsEnabled =
String.fromEnvironment('DIET_GUARD_FRAME_STATS') == '1';
/// Starts collecting frame-to-frame intervals and periodically posts a
/// summary to the desktop wrapper, which writes it to disk.
///
/// The wrapper is used as the sink because a browser cannot write a file and
/// reading its console from outside needs a debugger attached; a POST lands
/// somewhere a measurement run can simply read.
// coverage:ignore-start
void startFrameStats({Duration reportEvery = const Duration(seconds: 2)}) {
final intervalsMs = <double>[];
int? previousMicros;
SchedulerBinding.instance.addTimingsCallback((timings) {
for (final timing in timings) {
final micros = timing.timestampInMicroseconds(FramePhase.rasterFinish);
if (previousMicros != null) {
intervalsMs.add((micros - previousMicros!) / 1000);
}
previousMicros = micros;
}
});
Timer.periodic(reportEvery, (_) {
if (intervalsMs.isEmpty) return;
final sample = [...intervalsMs]..sort();
intervalsMs.clear();
double percentile(double fraction) =>
sample[(sample.length * fraction).floor().clamp(
0,
sample.length - 1,
)];
unawaited(
http.post(
Uri.parse(
'$desktopWrapperOrigin${WrapperPaths.documents}'
'frame_stats.json',
),
body: jsonEncode({
'frames': sample.length,
'p50_ms': percentile(0.50),
'p95_ms': percentile(0.95),
'max_ms': sample.last,
'fps_at_p50': 1000 / percentile(0.50),
'fps_at_p95': 1000 / percentile(0.95),
}),
),
);
});
}
// coverage:ignore-end

View File

@ -0,0 +1,5 @@
/// Platform entry point for building the GitHub sync client.
library;
export 'github_client_factory_io.dart'
if (dart.library.js_interop) 'github_client_factory_web.dart';

View File

@ -0,0 +1,34 @@
/// Direct GitHub client, used on Android.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:http/http.dart' as http;
/// This device's id in the `diet-guard-sync/devices/<id>/food_log.json`
/// layout.
///
/// The PC's Python side pushes under `pc` (`SYNC_DEVICE_ID` in
/// `diet_guard/_constants.py`) and the desktop web build under `desktop`;
/// every device must have its own, or two of them overwrite each other's
/// pushed log on every tick.
const syncDeviceId = 'phone';
/// Builds a client that talks to `api.github.com` directly with [settings]'
/// token.
GitHubClient createGitHubClient(
SyncSettings settings, {
http.Client? httpClient,
}) => GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: settings.token,
httpClient: httpClient,
);
/// Builds the device-flow client, talking to GitHub directly.
GitHubDeviceAuth createDeviceAuth(
String clientId, {
http.Client? httpClient,
}) => GitHubDeviceAuth(clientId: clientId, httpClient: httpClient);

View File

@ -0,0 +1,82 @@
/// Wrapper-proxied GitHub client, used by the desktop web build.
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:diet_guard_app/services/github_device_auth.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:http/http.dart' as http;
/// This device's id under `diet-guard-sync/devices/`.
///
/// Distinct from the phone's `phone` and the Python side's `pc`: the desktop
/// app is a third device, and sharing an id would make two devices overwrite
/// each other's pushed log on every tick.
const syncDeviceId = 'desktop';
/// Builds a client whose requests go through the desktop wrapper.
///
/// The token is deliberately empty: the wrapper attaches the real one
/// server-side (see `desktop/github_proxy.dart`), so it never enters the
/// browser. `settings.token` on web is only ever the stand-in constant.
GitHubClient createGitHubClient(
SyncSettings settings, {
http.Client? httpClient,
}) => GitHubClient(
owner: settings.owner,
repo: settings.repo,
token: '',
httpClient: WrapperProxyClient(inner: httpClient),
);
/// Rewrites `https://api.github.com/...` to the wrapper's proxy endpoint.
///
/// A decorator rather than a `baseUrl` option on [GitHubClient] so the shared
/// `crdt_sync` library needs no web-specific knowledge; the rewrite is a
/// property of how this app is hosted, not of the transport.
class WrapperProxyClient extends http.BaseClient {
/// Creates a client delegating to [inner] after rewriting GitHub URLs.
WrapperProxyClient({http.Client? inner, this.baseUrl = desktopWrapperOrigin})
: _inner = inner ?? http.Client();
final http.Client _inner;
/// Origin of the desktop wrapper.
final String baseUrl;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
if (request.url.host != 'api.github.com' || request is! http.Request) {
return _inner.send(request);
}
final rewritten =
http.Request(
request.method,
Uri.parse(
'$baseUrl${WrapperPaths.github}api'
'${request.url.path}',
).replace(query: request.url.hasQuery ? request.url.query : null),
)
..headers.addAll(request.headers)
..bodyBytes = request.bodyBytes
..followRedirects = request.followRedirects;
return _inner.send(rewritten);
}
@override
void close() => _inner.close();
}
/// Builds the device-flow client, routed through the desktop wrapper.
///
/// GitHub's device-flow endpoints send no CORS headers, so the page cannot
/// call them; the wrapper does, and keeps the resulting token.
GitHubDeviceAuth createDeviceAuth(
String clientId, {
http.Client? httpClient,
}) => GitHubDeviceAuth(
clientId: clientId,
deviceCodeUrl: '$desktopWrapperOrigin${WrapperPaths.github}auth/device/start',
tokenUrl: '$desktopWrapperOrigin${WrapperPaths.github}auth/device/poll',
httpClient: httpClient,
);

View File

@ -1,8 +1,15 @@
import 'dart:async';
import 'dart:convert';
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:http/http.dart' as http;
/// GitHub's device-code endpoint.
const githubDeviceCodeUrl = 'https://github.com/login/device/code';
/// GitHub's device-flow token endpoint.
const githubTokenUrl = 'https://github.com/login/oauth/access_token';
/// First-stage response of the GitHub OAuth Device Flow: the code the user
/// types on github.com and the URL to type it into.
class DeviceCodeResponse {
@ -72,6 +79,8 @@ class GitHubDeviceAuth {
GitHubDeviceAuth({
required this.clientId,
this.scope = 'repo',
this.deviceCodeUrl = githubDeviceCodeUrl,
this.tokenUrl = githubTokenUrl,
http.Client? httpClient,
Future<void> Function(Duration)? delay,
}) : _http = httpClient ?? http.Client(),
@ -84,17 +93,26 @@ class GitHubDeviceAuth {
/// OAuth scope requested. `repo` is required for private-repo contents.
final String scope;
/// Endpoint asked for a device + user code.
///
/// GitHub's own URL on Android. The desktop web build points both this and
/// [tokenUrl] at the local wrapper instead, because GitHub's device-flow
/// endpoints send no CORS headers and a page cannot call them at all (see
/// `desktop/github_proxy.dart`).
final String deviceCodeUrl;
/// Endpoint polled for the access token. See [deviceCodeUrl].
final String tokenUrl;
final http.Client _http;
final Future<void> Function(Duration) _delay;
static const _deviceCodeUrl = 'https://github.com/login/device/code';
static const _tokenUrl = 'https://github.com/login/oauth/access_token';
static const _grantType = 'urn:ietf:params:oauth:grant-type:device_code';
/// Step 1: ask GitHub for a device + user code.
Future<DeviceCodeResponse> requestDeviceCode() async {
final res = await _http.post(
Uri.parse(_deviceCodeUrl),
Uri.parse(deviceCodeUrl),
headers: const {'Accept': 'application/json'},
body: {'client_id': clientId, 'scope': scope},
);
@ -118,7 +136,7 @@ class GitHubDeviceAuth {
while (DateTime.now().isBefore(deadline)) {
await _delay(Duration(seconds: intervalSeconds));
final res = await _http.post(
Uri.parse(_tokenUrl),
Uri.parse(tokenUrl),
headers: const {'Accept': 'application/json'},
body: {
'client_id': clientId,
@ -130,6 +148,9 @@ class GitHubDeviceAuth {
final token = json['access_token'] as String?;
if (token != null) return token;
// The wrapper-proxied flow deliberately keeps the token server-side and
// answers with a bare acknowledgement instead (see [deviceCodeUrl]).
if (json['status'] == 'ok') return wrapperManagedToken;
switch (json['error'] as String?) {
case 'authorization_pending':

View File

@ -2,15 +2,14 @@
library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_component.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/document_store_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
/// The on-disk log shape: date key (`YYYY-MM-DD`) to that day's entries.
@ -25,34 +24,37 @@ typedef DayLog = Map<String, List<FoodEntry>>;
/// autocomplete is small-corpus fuzzy string matching, not a relational
/// query.
class LogStorageService {
LogStorageService._(this._file);
LogStorageService._(this._store);
/// Document name this service owns, unchanged from the pre-web on-disk
/// filename so an installed phone keeps reading its existing log.
static const documentName = 'food_log.json';
static LogStorageService? _instance;
/// Returns the initialized singleton; throws if [init] was not called.
static LogStorageService get instance => _instance!;
final File _file;
final DocumentStore _store;
/// Initializes the singleton, pointing at the app's documents directory
/// (phone-sandboxed; no external-storage permission needed).
/// Initializes the singleton against the platform document store: files in
/// the app's documents directory on Android (phone-sandboxed; no
/// external-storage permission needed), IndexedDB in the browser-hosted
/// desktop app.
static Future<LogStorageService> init() async {
if (_instance != null) return _instance!;
final dir = await getApplicationDocumentsDirectory();
final svc = LogStorageService._(File(p.join(dir.path, 'food_log.json')));
final svc = LogStorageService._(await openDocumentStore());
_instance = svc;
return svc;
}
/// Resets the singleton so [init] can be called again in tests.
///
/// When [testDir] is given, subsequent reads/writes go there instead of
/// the real documents directory, so a test can never touch real data.
/// When [store] is given, subsequent reads/writes go there instead of the
/// real platform store, so a test can never touch real data.
@visibleForTesting
static void resetForTesting({Directory? testDir}) {
_instance = testDir == null
? null
: LogStorageService._(File(p.join(testDir.path, 'food_log.json')));
static void resetForTesting({DocumentStore? store}) {
_instance = store == null ? null : LogStorageService._(store);
}
/// Reads the full log, including tombstoned entries.
@ -60,13 +62,8 @@ class LogStorageService {
/// Returns an empty log on a missing or unparsable file, mirroring
/// `_state._read_raw_log`'s defensive read.
Future<DayLog> readLog() async {
if (!_file.existsSync()) return {};
String raw;
try {
raw = await _file.readAsString();
} on FileSystemException {
return {};
}
final raw = await _store.read(documentName);
if (raw == null) return {};
Object? data;
try {
data = jsonDecode(raw);
@ -87,22 +84,16 @@ class LogStorageService {
return result;
}
/// Persists the full log to disk, creating the parent directory if
/// needed, mirroring `_state._write_log`.
/// Persists the full log to the store, mirroring `_state._write_log`.
///
/// Atomicity against a concurrent reader is the store's job (see
/// `FileDocumentStore.write`'s temp-file-and-rename), not this method's.
Future<void> writeLog(DayLog log) async {
await _file.parent.create(recursive: true);
final encoded = <String, Object?>{
for (final mapEntry in log.entries)
mapEntry.key: mapEntry.value.map((e) => e.toLocalJson()).toList(),
};
// Write to a per-process temp file then atomically rename it over the
// real one, so a concurrent reader never sees a half-written file. The
// connectivity-gated background push (see background_sync_service.dart)
// can `runSync` -> writeLog in a separate isolate while the foreground
// app also writes; the pid in the temp name keeps the two from colliding.
final tmp = File('${_file.path}.$pid.tmp');
await tmp.writeAsString(jsonEncode(encoded));
await tmp.rename(_file.path);
await _store.write(documentName, jsonEncode(encoded));
}
/// Appends a signed-on-PC-eventually entry for [desc] to today's log.

View File

@ -0,0 +1,28 @@
/// The platform notification surface behind [NotificationService].
library;
/// Shows and cancels one notification per meal slot.
///
/// Free of any plugin import so [NotificationService]'s due-slot logic
/// compiles for web: the implementations are
/// `notification_backend_io.dart` (`flutter_local_notifications`) and
/// `notification_backend_web.dart` (the browser's Notifications API),
/// selected by the conditional export in
/// `notification_backend_factory.dart`.
abstract class NotificationBackend {
/// Prepares the platform surface. Called once, before any [show]/[cancel].
Future<void> initialize();
/// Asks the platform for permission to post notifications.
///
/// Returns null where the concept does not apply, which callers treat the
/// same as false: notifications degrade silently rather than blocking use
/// of the app.
Future<bool?> requestPermission();
/// Posts (or replaces) the notification for [slot].
Future<void> show(int slot, String title, String body);
/// Removes the notification for [slot], if one is showing.
Future<void> cancel(int slot);
}

View File

@ -0,0 +1,5 @@
/// Platform entry point for opening the notification backend.
library;
export 'notification_backend_io.dart'
if (dart.library.js_interop) 'notification_backend_web.dart';

View File

@ -0,0 +1,73 @@
/// `flutter_local_notifications`-backed [NotificationBackend] (Android).
library;
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// Wraps [FlutterLocalNotificationsPlugin] so the due-slot logic in
/// `notification_service.dart` is unit-testable against a fake platform
/// channel, independent of the real plugin's native implementation.
class LocalNotificationsBackend implements NotificationBackend {
/// Creates a backend over [plugin].
LocalNotificationsBackend(this.plugin);
/// The wrapped plugin. Injectable so a test can point it at a fake channel.
final FlutterLocalNotificationsPlugin plugin;
static const _channelId = 'diet_guard_due_slot';
static const _channelName = 'Meal reminders';
@override
Future<void> initialize() async {
const settings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
);
await plugin.initialize(settings: settings);
}
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.
///
/// Returns null on platforms where this Android-specific call doesn't
/// apply -- the caller treats null and false the same way (don't block on
/// it; notifications degrade silently if denied, matching the rest of this
/// service's silent-on-failure stance). Since the desktop target became a
/// web build, `android/` is this backend's only real platform, so in
/// production the non-null path always runs; the fallback is not reachable
/// from `flutter test` without polluting the process-global plugin
/// registration other tests in this file rely on, so it's excluded from
/// coverage rather than chased with a fragile test-ordering trick.
@override
Future<bool?> requestPermission() =>
plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.requestNotificationsPermission() ??
// coverage:ignore-line
Future.value();
@override
Future<void> show(int slot, String title, String body) async {
const details = NotificationDetails(
android: AndroidNotificationDetails(
_channelId,
_channelName,
importance: Importance.high,
priority: Priority.high,
),
);
await plugin.show(
id: slot,
title: title,
body: body,
notificationDetails: details,
);
}
@override
Future<void> cancel(int slot) => plugin.cancel(id: slot);
}
/// Opens the platform notification backend.
NotificationBackend openNotificationBackend() =>
LocalNotificationsBackend(FlutterLocalNotificationsPlugin());

View File

@ -0,0 +1,56 @@
/// Browser-Notifications-API [NotificationBackend] for the desktop app.
///
/// A browser notification only exists while the page that raised it is open,
/// so this is a genuinely weaker surface than Android's: closing the desktop
/// window drops every pending reminder. That is accepted -- the PC's real
/// backstop is `diet-guard-gate.timer`, which locks the screen rather than
/// asking politely.
library;
import 'dart:js_interop';
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:web/web.dart' as web;
/// [NotificationBackend] over the browser's `Notification` API.
class WebNotificationBackend implements NotificationBackend {
/// Live notifications by slot, so [cancel] can close the right one. The
/// `tag` also makes the browser replace rather than stack a re-shown slot;
/// the map is what makes an explicit close possible.
final _shown = <int, web.Notification>{};
bool _granted = false;
@override
Future<void> initialize() async {}
@override
Future<bool?> requestPermission() async {
if (web.Notification.permission == 'granted') {
_granted = true;
return true;
}
if (web.Notification.permission == 'denied') return false;
final result = await web.Notification.requestPermission().toDart;
return _granted = result.toDart == 'granted';
}
@override
Future<void> show(int slot, String title, String body) async {
// Posting without permission throws; a silent no-op matches this
// service's degrade-quietly stance everywhere else.
if (!_granted) return;
_shown[slot] = web.Notification(
title,
web.NotificationOptions(body: body, tag: 'diet_guard_slot_$slot'),
);
}
@override
Future<void> cancel(int slot) async {
_shown.remove(slot)?.close();
}
}
/// Opens the platform notification backend.
NotificationBackend openNotificationBackend() => WebNotificationBackend();

View File

@ -5,77 +5,51 @@
library;
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/services/notification_backend.dart';
import 'package:diet_guard_app/services/notification_backend_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// Wraps [FlutterLocalNotificationsPlugin] so the due-slot notification
/// logic ([syncToSlots]) is unit-testable against a fake platform channel,
/// independent of the real plugin's native implementation.
/// Owns the due-slot notification logic ([syncToSlots]) independently of the
/// platform surface that actually posts them: `flutter_local_notifications`
/// on Android, the browser's Notifications API in the desktop web build (see
/// `notification_backend.dart`).
class NotificationService {
NotificationService._(this._plugin);
NotificationService._(this._backend);
static NotificationService? _instance;
final FlutterLocalNotificationsPlugin _plugin;
final NotificationBackend _backend;
bool _initialized = false;
static const _channelId = 'diet_guard_due_slot';
static const _channelName = 'Meal reminders';
/// Returns the initialized singleton; throws if [init] was not called.
static NotificationService get instance => _instance!;
/// Initializes the singleton with the real plugin (idempotent -- a
/// Initializes the singleton with the platform backend (idempotent -- a
/// second call returns the already-initialized instance without
/// re-running platform setup).
static Future<NotificationService> init() async {
final svc = _instance ??= NotificationService._(
FlutterLocalNotificationsPlugin(),
);
final svc = _instance ??= NotificationService._(openNotificationBackend());
if (!svc._initialized) {
// `linux:` is required whenever the app runs on Linux (the desktop
// build used to visually verify screens); this app has no real
// Linux target otherwise.
const settings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
linux: LinuxInitializationSettings(defaultActionName: 'Open'),
);
await svc._plugin.initialize(settings: settings);
await svc._backend.initialize();
svc._initialized = true;
}
return svc;
}
/// Resets the singleton so tests can inject a plugin pointed at a fake
/// platform channel. A subsequent [init] call drives that fake's
/// `initialize` codepath, same as production.
/// Resets the singleton so tests can inject a backend -- typically one over
/// a plugin pointed at a fake platform channel. A subsequent [init] call
/// drives that backend's `initialize` codepath, same as production.
@visibleForTesting
static void resetForTesting({FlutterLocalNotificationsPlugin? plugin}) {
_instance = plugin == null ? null : NotificationService._(plugin);
static void resetForTesting({NotificationBackend? backend}) {
_instance = backend == null ? null : NotificationService._(backend);
}
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.
/// Requests the platform's notification permission.
///
/// Returns null on platforms where this Android-specific call doesn't
/// apply -- the caller treats null and false the same way (don't block on
/// it; notifications degrade silently if denied, matching the rest of
/// this service's silent-on-failure stance). This app only ships an
/// `android/` target, so in production the non-null path always runs;
/// the fallback exists for the Linux desktop build used to visually
/// verify this screen, where `resolvePlatformSpecificImplementation`
/// correctly resolves to null -- not reachable from `flutter test`
/// without polluting the process-global plugin registration other tests
/// in this file rely on, so it's excluded from coverage rather than
/// chased with a fragile test-ordering trick.
Future<bool?> requestPermission() =>
_plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.requestNotificationsPermission() ??
// coverage:ignore-line
Future.value();
/// Returns null where the concept doesn't apply; callers treat null and
/// false the same way.
Future<bool?> requestPermission() => _backend.requestPermission();
/// Shows a notification for every slot in [dueSlots] and cancels one for
/// every other known slot.
@ -88,27 +62,14 @@ class NotificationService {
final due = dueSlots.toSet();
for (final slot in daySlots()) {
if (due.contains(slot)) {
await _show(slot);
await _backend.show(
slot,
'Meal not logged',
"You haven't logged your ${slotLabel(slot)} meal yet.",
);
} else {
await _plugin.cancel(id: slot);
await _backend.cancel(slot);
}
}
}
Future<void> _show(int slot) async {
const details = NotificationDetails(
android: AndroidNotificationDetails(
_channelId,
_channelName,
importance: Importance.high,
priority: Priority.high,
),
);
await _plugin.show(
id: slot,
title: 'Meal not logged',
body: "You haven't logged your ${slotLabel(slot)} meal yet.",
notificationDetails: details,
);
}
}

View File

@ -1,52 +1,56 @@
/// Picks a photo and copies it into permanent phone-local storage.
/// Picks a photo and copies it into permanent app-local storage.
library;
import 'dart:io';
import 'package:diet_guard_app/services/blob_store.dart';
import 'package:diet_guard_app/services/blob_store_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
/// Wraps [ImagePicker] and persists the result under the app's documents
/// directory, so the returned path survives after the picker's own
/// (possibly cache-cleared) temp file is gone.
/// Wraps [ImagePicker] and persists the result in a [BlobStore], so the
/// returned key survives after the picker's own (possibly cache-cleared)
/// temp file is gone.
///
/// Photos are phone-local only: per the sync plan (Milestone 3), a logged
/// Photos are device-local only: per the sync plan (Milestone 3), a logged
/// entry's `imagePath` is stripped before push and never read from a pulled
/// remote copy, so no storage here needs to be sync-aware.
/// remote copy, so nothing here needs to be sync-aware. That also means a
/// photo attached on the desktop is never visible on the phone, and vice
/// versa -- by design, not by omission.
class PhotoAttachService {
PhotoAttachService._(this._testDir);
PhotoAttachService._(this._store);
static PhotoAttachService _instance = PhotoAttachService._(null);
/// The singleton instance.
static PhotoAttachService get instance => _instance;
final Directory? _testDir;
BlobStore? _store;
/// Redirects where picked photos are copied to, so a test never touches
/// the real documents directory. Pass null to restore default behavior.
/// Redirects where picked photos are stored, so a test never touches the
/// real store. Pass null to restore default behavior.
@visibleForTesting
static void resetForTesting({Directory? testDir}) {
_instance = PhotoAttachService._(testDir);
static void resetForTesting({BlobStore? store}) {
_instance = PhotoAttachService._(store);
}
/// Opens [source] (camera or gallery), and on a successful pick, copies
/// the image into `<app documents>/images/<uuid>.<ext>`.
Future<BlobStore> _resolveStore() async => _store ??= await openBlobStore();
/// Opens [source] (camera or gallery) and stores the picked image.
///
/// Returns the new permanent path, or null if the user cancelled the
/// picker.
/// Returns the new blob key -- an absolute path on Android, an IndexedDB
/// key in the browser -- or null if the user cancelled the picker.
Future<String?> pickAndStore(ImageSource source) async {
final picked = await ImagePicker().pickImage(source: source);
if (picked == null) return null;
final docsDir = _testDir ?? await getApplicationDocumentsDirectory();
final imagesDir = Directory(p.join(docsDir.path, 'images'));
await imagesDir.create(recursive: true);
final ext = p.extension(picked.path);
final dest = p.join(imagesDir.path, '${const Uuid().v4()}$ext');
await File(picked.path).copy(dest);
return dest;
final store = await _resolveStore();
// `readAsBytes` rather than a file copy: the browser's picker hands back
// a blob URL with no filesystem behind it.
return store.put(p.extension(picked.path), await picked.readAsBytes());
}
/// Returns the bytes stored under [key], or null when the photo is gone.
///
/// Backs the web image widget, which cannot render from a path.
Future<Uint8List?> readBytes(String key) async =>
(await _resolveStore()).get(key);
}

View File

@ -20,17 +20,12 @@ import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
const _devicesDir = 'diet-guard-sync/devices';
/// This device's id in the `diet-guard-sync/devices/<id>/food_log.json`
/// layout. The PC pushes under `pc` (`SYNC_DEVICE_ID` in
/// `diet_guard/_constants.py`); the phone is the only other device in this
/// design.
const phoneDeviceId = 'phone';
/// Runs one full sync tick: pull, merge, preserve photos, persist, push.
///
/// Returns the merged log as it now sits on disk locally. Propagates any
@ -43,7 +38,7 @@ Future<DayLog> runSync(GitHubClient client) async {
final mergedLog = await syncLog(
client: client,
deviceId: phoneDeviceId,
deviceId: syncDeviceId,
pathPrefix: _devicesDir,
localLog: dayLogToLog(local),
encode: encodeLogForPush,
@ -82,7 +77,7 @@ Future<void> _syncBudget(GitHubClient client) async {
final mergedBudgetLog = await syncLog(
client: client,
deviceId: phoneDeviceId,
deviceId: syncDeviceId,
pathPrefix: _devicesDir,
localLog: budgetToLog(localRecord),
encode: encodeBudgetForPush,

View File

@ -4,16 +4,17 @@
/// manual fallback.
library;
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:diet_guard_app/services/token_vault_factory.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// The GitHub token is kept in the OS keystore (Android Keystore / libsecret)
/// via [flutter_secure_storage]; only the non-secret owner/repo live in
/// `SharedPreferences`. Older builds stored the token in plaintext prefs;
/// [load]/[save] migrate it transparently and never drop the plaintext copy
/// until a secure write is confirmed (so we degrade to -- never below -- the
/// old behaviour when no secret service is available).
/// The GitHub token is kept out of `SharedPreferences`, which holds only the
/// non-secret owner/repo: on Android it lives in the OS keystore, and in the
/// desktop web build it lives in the wrapper process rather than the browser
/// at all (see [TokenVault]). Older builds stored the token in plaintext
/// prefs; [load]/[save] migrate it transparently and never drop the plaintext
/// copy until a vault write is confirmed (so we degrade to -- never below --
/// the old behaviour when no secure store is available).
class SyncSettings {
/// Creates a [SyncSettings] from its owner/repo/token.
const SyncSettings({
@ -59,12 +60,10 @@ class SyncSettings {
// the token has been migrated into secure storage.
static const _kToken = 'sync.token';
/// Key for the token inside the OS keystore.
static const _secureToken = 'sync.token';
static final TokenVault _vault = openTokenVault();
/// Default options keep us off the deprecated `encryptedSharedPreferences`
/// path on Android and use libsecret on Linux.
static const _secure = FlutterSecureStorage();
/// True when this platform can show the stored token back to the user.
static bool get exposesTokenValue => _vault.exposesTokenValue;
/// Loads settings, defaulting the owner/repo to `kuhyx/syncs`
/// (matching the PC's `SYNC_REPO_OWNER`/`SYNC_REPO_NAME` constants) and the
@ -90,57 +89,36 @@ class SyncSettings {
);
}
/// Reads the token, preferring the keystore and falling back to the legacy
/// plaintext value. A legacy value is migrated into the keystore on read,
/// but only dropped from prefs once that secure write succeeds.
/// Reads the token, preferring the vault and falling back to the legacy
/// plaintext value. A legacy value is migrated into the vault on read, but
/// only dropped from prefs once that write succeeds.
static Future<String> _loadToken(SharedPreferences prefs) async {
String? secure;
try {
secure = await _secure.read(key: _secureToken);
} on PlatformException {
// No secret service available -- fall back to the legacy plaintext copy.
secure = null;
}
if (secure != null && secure.isNotEmpty) return secure;
final stored = await _vault.read();
if (stored.isNotEmpty) return stored;
final legacy = prefs.getString(_kToken) ?? '';
if (legacy.isNotEmpty && await _writeSecureToken(legacy)) {
if (legacy.isNotEmpty && await _vault.write(legacy)) {
await prefs.remove(_kToken);
}
return legacy;
}
/// Persists [owner]/[repo] to prefs and [token] to the keystore (or
/// plaintext prefs as a fallback -- see [_loadToken]).
/// Persists [owner]/[repo] to prefs and [token] to the vault (or plaintext
/// prefs as a fallback -- see [_loadToken]).
Future<void> save() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_kOwner, owner);
await prefs.setString(_kRepo, repo);
await prefs.setString(_kClientId, clientId);
// Confirm-before-delete: only remove the plaintext copy once the keystore
// Confirm-before-delete: only remove the plaintext copy once the vault
// write succeeds; otherwise keep persisting it to prefs as before.
if (await _writeSecureToken(token)) {
if (await _vault.write(token)) {
await prefs.remove(_kToken);
} else {
await prefs.setString(_kToken, token);
}
}
/// Writes [token] to the keystore (deleting the entry when empty). Returns
/// false if the platform secret service is unavailable.
static Future<bool> _writeSecureToken(String token) async {
try {
if (token.isEmpty) {
await _secure.delete(key: _secureToken);
} else {
await _secure.write(key: _secureToken, value: token);
}
return true;
} on PlatformException {
return false;
}
}
/// Returns a copy of this with only the given fields replaced.
SyncSettings copyWith({
String? owner,

View File

@ -0,0 +1,34 @@
/// Where the GitHub sync token lives, per platform.
library;
/// Reads and writes the GitHub sync token.
///
/// Two very different implementations sit behind this:
///
/// * Android keeps the token in the OS keystore via `flutter_secure_storage`
/// (`token_vault_io.dart`), migrating any legacy plaintext copy.
/// * The desktop web build never holds the token at all: the wrapper owns it
/// on disk and attaches it to proxied requests, so the vault only reports
/// *whether* one exists (`token_vault_web.dart`).
abstract class TokenVault {
/// Returns the token, or the empty string when none is stored.
///
/// On web this returns [wrapperManagedToken] as a stand-in whenever the
/// wrapper holds a token: callers only ever test it for emptiness or hand
/// it to a client whose requests are proxied, and the real value stays out
/// of the browser.
Future<String> read();
/// Stores [token] (clearing it when empty). Returns false when the platform
/// has nowhere secure to put it, so the caller can fall back.
Future<bool> write(String token);
/// True when this platform can show the token back to the user.
///
/// False on web -- the settings screen hides the PAT field rather than
/// displaying a placeholder that cannot be edited meaningfully.
bool get exposesTokenValue;
}
/// Stand-in value used on web in place of the real, wrapper-held token.
const wrapperManagedToken = 'wrapper-managed';

View File

@ -0,0 +1,5 @@
/// Platform entry point for the GitHub sync token vault.
library;
export 'token_vault_io.dart'
if (dart.library.js_interop) 'token_vault_web.dart';

View File

@ -0,0 +1,53 @@
/// Keystore-backed [TokenVault] used on Android.
library;
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Keeps the token in the OS keystore (Android Keystore) via
/// [FlutterSecureStorage].
///
/// Default options keep us off the deprecated `encryptedSharedPreferences`
/// path on Android.
class SecureStorageTokenVault implements TokenVault {
/// Creates a vault over [storage].
const SecureStorageTokenVault({this.storage = const FlutterSecureStorage()});
/// The wrapped keystore. Injectable so a test can supply a fake.
final FlutterSecureStorage storage;
/// Key for the token inside the OS keystore.
static const _secureToken = 'sync.token';
@override
bool get exposesTokenValue => true;
@override
Future<String> read() async {
try {
return await storage.read(key: _secureToken) ?? '';
} on PlatformException {
// No secret service available -- the caller falls back to the legacy
// plaintext copy in SharedPreferences.
return '';
}
}
@override
Future<bool> write(String token) async {
try {
if (token.isEmpty) {
await storage.delete(key: _secureToken);
} else {
await storage.write(key: _secureToken, value: token);
}
return true;
} on PlatformException {
return false;
}
}
}
/// Opens the platform token vault.
TokenVault openTokenVault() => const SecureStorageTokenVault();

View File

@ -0,0 +1,65 @@
/// Wrapper-backed [TokenVault] for the desktop web build.
library;
import 'dart:convert';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:diet_guard_app/services/token_vault.dart';
import 'package:http/http.dart' as http;
/// Delegates token storage to the desktop wrapper.
///
/// The browser never holds the token: [read] reports only whether the wrapper
/// has one, and [write] hands a pasted PAT straight through to the wrapper's
/// 600-mode token file. This is deliberately *not* `flutter_secure_storage`'s
/// web backend, which is WebCrypto-wrapped `localStorage` with the wrap key
/// stored beside the ciphertext -- obfuscation, not encryption at rest.
class WrapperTokenVault implements TokenVault {
/// Creates a vault talking to the wrapper at [baseUrl].
WrapperTokenVault({this.baseUrl = desktopWrapperOrigin, http.Client? client})
: _client = client ?? http.Client();
/// Origin of the desktop wrapper.
final String baseUrl;
final http.Client _client;
@override
bool get exposesTokenValue => false;
@override
Future<String> read() async {
try {
final response = await _client.get(
Uri.parse('$baseUrl${WrapperPaths.github}auth/status'),
);
if (response.statusCode != 200) return '';
final body = jsonDecode(response.body);
final configured = body is Map && body['configured'] == true;
return configured ? wrapperManagedToken : '';
} on Exception {
// No wrapper running (a plain browser tab): behave as unconfigured
// rather than failing the whole settings screen.
return '';
}
}
@override
Future<bool> write(String token) async {
// The stand-in is what `read` handed out; writing it back would replace a
// real token with a literal.
if (token == wrapperManagedToken) return true;
try {
final response = await _client.post(
Uri.parse('$baseUrl${WrapperPaths.github}auth/token'),
body: token,
);
return response.statusCode == 204;
} on Exception {
return false;
}
}
}
/// Opens the platform token vault.
TokenVault openTokenVault() => WrapperTokenVault();

View File

@ -0,0 +1,10 @@
/// Platform entry point for rendering an attached meal photo.
///
/// Conditional export because the two platforms resolve a photo differently:
/// Android has a real file at the stored path, while the browser-hosted
/// desktop app has to read the bytes back out of IndexedDB before it can show
/// anything (`Image.file` is a `dart:io` stub there and would throw).
library;
export 'attached_image_io.dart'
if (dart.library.js_interop) 'attached_image_web.dart';

View File

@ -0,0 +1,58 @@
/// File-backed attached-photo widget (Android).
library;
import 'dart:io';
import 'package:flutter/material.dart';
/// Renders the photo stored under [path], falling back to a broken-image
/// icon when it cannot be read.
class AttachedImage extends StatelessWidget {
/// Creates an [AttachedImage] for the blob key [path].
const AttachedImage({
required this.path,
this.width,
this.height,
this.fit,
this.errorIconSize,
this.errorIconColor,
super.key,
});
/// Blob key of the photo -- an absolute file path on this platform.
final String path;
/// Optional fixed width; null renders at the image's own size.
final double? width;
/// Optional fixed height; null renders at the image's own size.
final double? height;
/// How to inscribe the image into its box.
final BoxFit? fit;
/// Size of the fallback broken-image icon.
final double? errorIconSize;
/// Colour of the fallback broken-image icon.
final Color? errorIconColor;
@override
Widget build(BuildContext context) {
return Image.file(
File(path),
width: width,
height: height,
fit: fit,
errorBuilder: (context, error, stackTrace) => SizedBox(
width: width,
height: height,
child: Icon(
Icons.broken_image,
size: errorIconSize,
color: errorIconColor,
),
),
);
}
}

View File

@ -0,0 +1,92 @@
/// IndexedDB-backed attached-photo widget (desktop web build).
library;
import 'dart:typed_data';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:flutter/material.dart';
/// Renders the photo stored under [path], falling back to a broken-image
/// icon when it cannot be read.
///
/// Unlike the Android build this is inherently asynchronous: the bytes come
/// from IndexedDB (or, for a cleared profile, the desktop wrapper's disk
/// mirror), not from a path the rasteriser can open itself.
class AttachedImage extends StatefulWidget {
/// Creates an [AttachedImage] for the blob key [path].
const AttachedImage({
required this.path,
this.width,
this.height,
this.fit,
this.errorIconSize,
this.errorIconColor,
super.key,
});
/// Blob key of the photo -- an IndexedDB key on this platform.
final String path;
/// Optional fixed width; null renders at the image's own size.
final double? width;
/// Optional fixed height; null renders at the image's own size.
final double? height;
/// How to inscribe the image into its box.
final BoxFit? fit;
/// Size of the fallback broken-image icon.
final double? errorIconSize;
/// Colour of the fallback broken-image icon.
final Color? errorIconColor;
@override
State<AttachedImage> createState() => _AttachedImageState();
}
class _AttachedImageState extends State<AttachedImage> {
late Future<Uint8List?> _bytes = _load();
Future<Uint8List?> _load() => PhotoAttachService.instance.readBytes(
widget.path,
);
@override
void didUpdateWidget(AttachedImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.path != widget.path) _bytes = _load();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Uint8List?>(
future: _bytes,
builder: (context, snapshot) {
final bytes = snapshot.data;
if (bytes == null) {
// Covers both "still loading" and "gone": a spinner that flashes
// for one frame per thumbnail would be worse than an empty box.
return SizedBox(
width: widget.width,
height: widget.height,
child: snapshot.connectionState == ConnectionState.done
? Icon(
Icons.broken_image,
size: widget.errorIconSize,
color: widget.errorIconColor,
)
: null,
);
}
return Image.memory(
bytes,
width: widget.width,
height: widget.height,
fit: widget.fit,
);
},
);
}
}

View File

@ -1,10 +1,10 @@
/// Shared attach/preview/remove control for a meal entry's optional photo.
library;
import 'dart:io';
import 'package:diet_guard_app/screens/photo_viewer_screen.dart';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:diet_guard_app/widgets/attached_image.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
@ -41,14 +41,21 @@ class PhotoAttachField extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text('Take a photo'),
onTap: () => Navigator.of(sheetContext).pop(ImageSource.camera),
),
// No camera row on web: the browser's picker is a file input,
// and `ImageSource.camera` silently falls back to the same file
// dialog -- an option that lies about what it does is worse than
// no option.
if (!kIsWeb)
ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text('Take a photo'),
onTap: () => Navigator.of(sheetContext).pop(ImageSource.camera),
),
ListTile(
leading: const Icon(Icons.photo_library),
title: const Text('Choose from gallery'),
title: const Text(
kIsWeb ? 'Choose a file' : 'Choose from gallery',
),
onTap: () => Navigator.of(sheetContext).pop(ImageSource.gallery),
),
],
@ -86,16 +93,11 @@ class PhotoAttachField extends StatelessWidget {
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(
File(path),
child: AttachedImage(
path: path,
width: thumbnailSize,
height: thumbnailSize,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) => SizedBox(
width: thumbnailSize,
height: thumbnailSize,
child: const Icon(Icons.broken_image),
),
),
),
);

View File

@ -1 +0,0 @@
flutter/ephemeral

View File

@ -1,128 +0,0 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "diet_guard_app")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "com.kuhy.diet_guard_app")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()

View File

@ -1,88 +0,0 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)

View File

@ -1,23 +0,0 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_linux/file_selector_plugin.h>
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
}

View File

@ -1,15 +0,0 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_

View File

@ -1,27 +0,0 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
file_selector_linux
flutter_secure_storage_linux
url_launcher_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)

View File

@ -1,26 +0,0 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")

View File

@ -1,6 +0,0 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}

View File

@ -1,153 +0,0 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "diet_guard_app");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "diet_guard_app");
}
gtk_window_set_default_size(window, 1280, 720);
// Resolved from the hicolor icon theme, which linux/install_desktop_entry.sh
// populates from linux/icons/. Without this the GTK runner shows a generic
// placeholder in the taskbar, since Flutter never sets a window icon itself.
gtk_window_set_icon_name(window, "diet-guard-app");
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#000000");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}

View File

@ -1,21 +0,0 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
G_DECLARE_FINAL_TYPE(MyApplication,
my_application,
MY,
APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_

View File

@ -94,10 +94,10 @@ packages:
dependency: transitive
description:
name: cross_file
sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
sha256: "92c9c43c383bfa1c32079d3bc492d55d6d4318044b7b47edaff8971cbb555c51"
url: "https://pub.dev"
source: hosted
version: "0.3.5+2"
version: "0.3.5+4"
crypto:
dependency: "direct main"
description:
@ -203,10 +203,10 @@ packages:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: a0d7141f14cabcee42967470a858dfc99dd6cfb70d3cab404bacfcafa9e84e70
sha256: "40c6a69189a622bda89ddcf50a139f4ba0f0eb9c0fef6718845b1f8b95452ed6"
url: "https://pub.dev"
source: hosted
version: "22.0.1"
version: "22.1.0"
flutter_local_notifications_linux:
dependency: transitive
description:
@ -219,10 +219,10 @@ packages:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: ff0013eae795e8dc8fad4a8992a209e64d3ba2fbd8bf5e43c36bf448f95bd814
sha256: "4dfbae10debab9ac975d8b01943fed94c0c19dad43f825964b29f3c3f9a8a852"
url: "https://pub.dev"
source: hosted
version: "12.0.0"
version: "12.0.1"
flutter_local_notifications_web:
dependency: transitive
description:
@ -329,6 +329,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.1.2"
idb_shim:
dependency: "direct main"
description:
name: idb_shim
sha256: "3448298f244bc76a14aca71461eeab6add2b8a877930521c42c2e8b71b644590"
url: "https://pub.dev"
source: hosted
version: "2.9.6+2"
image:
dependency: transitive
description:
@ -341,10 +349,10 @@ packages:
dependency: "direct main"
description:
name: image_picker
sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac"
sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667
url: "https://pub.dev"
source: hosted
version: "1.2.2"
version: "1.2.3"
image_picker_android:
dependency: transitive
description:
@ -541,10 +549,10 @@ packages:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
version: "2.2.2"
path_provider_platform_interface:
dependency: transitive
description:
@ -657,6 +665,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.6.0"
sembast:
dependency: transitive
description:
name: sembast
sha256: a58b26925e23071cf0f4754d8449aabe829e9a9930a872fb18e6ae4c2c88e025
url: "https://pub.dev"
source: hosted
version: "3.8.9+1"
shared_preferences:
dependency: "direct main"
description:
@ -669,10 +685,10 @@ packages:
dependency: transitive
description:
name: shared_preferences_android
sha256: "93ae5884a9df5d3bb696825bceb3a17590754548b5d740eba51500afc8d088f5"
sha256: "0634e64bd719f89c012f392938e173521f535d3ecaf66558fa94a056d22b5cc7"
url: "https://pub.dev"
source: hosted
version: "2.4.26"
version: "2.4.27"
shared_preferences_foundation:
dependency: transitive
description:
@ -750,6 +766,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
synchronized:
dependency: transitive
description:
name: synchronized
sha256: "93b153dcb6a26dcddee6ca087dd634b53e38c10b5aa163e8e49501a776456153"
url: "https://pub.dev"
source: hosted
version: "3.4.1"
term_glyph:
dependency: transitive
description:
@ -770,10 +794,10 @@ packages:
dependency: transitive
description:
name: timezone
sha256: "784a5e34d2eb62e1326f24d6f600aaaee452eb8ca8ef2f384a59244e292d158b"
sha256: "981d1020d6ef8fe1e7b3de5054e5b25579ae7c403d7734adc508ffc47668e9cb"
url: "https://pub.dev"
source: hosted
version: "0.11.0"
version: "0.11.1"
typed_data:
dependency: transitive
description:
@ -850,10 +874,10 @@ packages:
dependency: "direct main"
description:
name: uuid
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
url: "https://pub.dev"
source: hosted
version: "4.5.3"
version: "4.6.0"
vector_math:
dependency: transitive
description:
@ -879,7 +903,7 @@ packages:
source: hosted
version: "15.2.0"
web:
dependency: transitive
dependency: "direct main"
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"

View File

@ -19,6 +19,7 @@ dependencies:
flutter_local_notifications: ^22.0.1
flutter_secure_storage: ^10.3.1
http: ^1.6.0
idb_shim: ^2.9.6+2
image_picker: ^1.1.2
path: ^1.9.1
path_provider: ^2.1.5
@ -26,6 +27,7 @@ dependencies:
shared_preferences: ^2.5.5
url_launcher: ^6.3.2
uuid: ^4.5.3
web: ^1.1.1
workmanager: ^0.9.0+3
dev_dependencies:

31
app/run.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/bash
# Builds the web bundle and launches the diet_guard companion app through the
# desktop wrapper, straight out of the repo (no packaging step).
#
# The desktop app is a Flutter *web* build rather than a Linux embedder build:
# the embedder manages only ~20fps at 4K, while the same Dart code in Chrome
# sustains ~144fps.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
log() { echo "==> $*"; }
command -v flutter >/dev/null 2>&1 || {
echo "flutter is not on PATH" >&2
exit 1
}
cd "$SCRIPT_DIR"
flutter config --enable-web >/dev/null
log "fetching pub packages"
flutter pub get
log "building the web bundle"
flutter build web --release
log "launching the app"
exec dart run bin/diet_guard_desktop.dart --web-root "$SCRIPT_DIR/build/web"

View File

@ -0,0 +1,292 @@
// The desktop wrapper is the other half of the web-build desktop app: it
// serves the assets, owns the on-disk mirror of the app's storage, and fronts
// GitHub. These tests drive it over a real loopback socket, since its
// contract is HTTP.
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/desktop/wrapper_server.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:path/path.dart' as p;
void main() {
late Directory tempDir;
late String webRoot;
late String dataDir;
late WrapperServer server;
late List<http.Request> outbound;
late Map<String, http.Response> canned;
Future<void> startServer() async {
outbound = [];
canned = {};
final proxy = GitHubProxy(
tokenPath: p.join(tempDir.path, 'config', 'sync_token'),
fallbackTokenPath: p.join(tempDir.path, 'config', 'fallback_token'),
httpClient: MockClient((request) async {
outbound.add(request);
return canned[request.url.toString()] ??
http.Response('{"ok":true}', 200);
}),
);
server = WrapperServer(
webRoot: webRoot,
dataDir: dataDir,
gitHubProxy: proxy,
);
await server.start(0);
}
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_wrapper_');
webRoot = p.join(tempDir.path, 'web');
dataDir = p.join(tempDir.path, 'data');
await Directory(webRoot).create(recursive: true);
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html>app</html>');
File(p.join(webRoot, 'main.wasm')).writeAsBytesSync([0, 97, 115, 109]);
await startServer();
});
tearDown(() async {
await server.stop();
await tempDir.delete(recursive: true);
});
group('static assets', () {
test('serves index.html at the root', () async {
final response = await http.get(url('/'));
expect(response.statusCode, 200);
expect(response.body, '<html>app</html>');
expect(response.headers['content-type'], contains('text/html'));
});
test('serves .wasm as application/wasm', () async {
// CanvasKit refuses any other content type and the app then renders
// nothing at all -- the failure looks like a blank window, not an error.
final response = await http.get(url('/main.wasm'));
expect(response.statusCode, 200);
expect(response.headers['content-type'], 'application/wasm');
});
test('404s a missing asset', () async {
expect((await http.get(url('/nope.js'))).statusCode, 404);
});
});
group('document mirror', () {
test('round-trips a document', () async {
final posted = await http.post(
url('/documents/food_log.json'),
body: '{"2026-07-20":[]}',
);
final fetched = await http.get(url('/documents/food_log.json'));
expect(posted.statusCode, 204);
expect(fetched.body, '{"2026-07-20":[]}');
expect(
File(p.join(dataDir, 'documents', 'food_log.json')).readAsStringSync(),
'{"2026-07-20":[]}',
);
});
test('404s an unmirrored document', () async {
expect((await http.get(url('/documents/food_bank.json'))).statusCode, 404);
});
test('rejects a traversing name instead of writing outside dataDir', () {
// The mirror writes into the user's home directory, so a `..` segment
// would turn a document write into an arbitrary-file overwrite.
expect(
http
.post(url('/documents/..%2F..%2Fevil'), body: 'x')
.then((r) => r.statusCode),
completion(400),
);
});
test('rejects a method other than GET/POST', () async {
expect((await http.delete(url('/documents/x.json'))).statusCode, 405);
});
});
group('blob mirror', () {
test('round-trips photo bytes', () async {
final bytes = [1, 2, 3, 4];
final posted = await http.post(url('/blobs/photo.jpg'), body: bytes);
final fetched = await http.get(url('/blobs/photo.jpg'));
expect(posted.statusCode, 204);
expect(fetched.bodyBytes, bytes);
});
});
group('github proxy', () {
test('reports no token before one is stored', () async {
final response = await http.get(url('/github/auth/status'));
expect(jsonDecode(response.body), {'configured': false});
});
test('stores a pasted token and then reports configured', () async {
await http.post(url('/github/auth/token'), body: 'ghp_pasted');
final response = await http.get(url('/github/auth/status'));
expect(jsonDecode(response.body), {'configured': true});
expect(
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
'ghp_pasted',
);
});
test('falls back to the PC gate token when it has none of its own', () async {
// The Python side already keeps a token for diet-guard-sync.timer;
// reusing it is what makes the desktop app need no second setup.
final fallback = File(p.join(tempDir.path, 'config', 'fallback_token'))
..createSync(recursive: true)
..writeAsStringSync('ghp_from_gate\n');
addTearDown(fallback.deleteSync);
final response = await http.get(url('/github/auth/status'));
expect(jsonDecode(response.body), {'configured': true});
});
test('attaches the token to a proxied API call', () async {
await http.post(url('/github/auth/token'), body: 'ghp_stored');
canned['https://api.github.com/repos/kuhyx/syncs'] = http.Response(
'{"name":"syncs"}',
200,
);
final response = await http.get(url('/github/api/repos/kuhyx/syncs'));
expect(response.body, '{"name":"syncs"}');
expect(outbound.single.headers['Authorization'], 'Bearer ghp_stored');
});
test('keeps a device-flow token server-side', () async {
canned['https://github.com/login/oauth/access_token'] = http.Response(
'{"access_token":"ghp_device"}',
200,
);
final response = await http.post(
url('/github/auth/device/poll'),
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
);
// The point of the proxy: the browser is told "ok", never the token.
expect(jsonDecode(response.body), {'status': 'ok'});
expect(response.body, isNot(contains('ghp_device')));
expect(
File(p.join(tempDir.path, 'config', 'sync_token')).readAsStringSync(),
'ghp_device',
);
});
test('passes a still-pending device-flow poll straight back', () async {
canned['https://github.com/login/oauth/access_token'] = http.Response(
'{"error":"authorization_pending"}',
200,
);
final response = await http.post(
url('/github/auth/device/poll'),
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
);
expect(jsonDecode(response.body), {'error': 'authorization_pending'});
});
test('forwards the device-code request with the client id', () async {
canned['https://github.com/login/device/code'] = http.Response(
'{"device_code":"dc","user_code":"ABCD-1234"}',
200,
);
final response = await http.post(
url('/github/auth/device/start'),
body: jsonEncode({'client_id': 'cid'}),
);
expect(jsonDecode(response.body), containsPair('user_code', 'ABCD-1234'));
expect(outbound.single.bodyFields['client_id'], 'cid');
});
test('404s an unknown /github path', () async {
expect((await http.get(url('/github/nope'))).statusCode, 404);
});
test('clears the stored token when handed an empty one', () async {
await http.post(url('/github/auth/token'), body: 'ghp_stored');
await http.post(url('/github/auth/token'), body: '');
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
'configured': false,
});
});
test('ignores an unreadable token file rather than failing', () async {
// A directory where the token file should be: readToken must fall
// through to "no token" instead of throwing out of every request.
Directory(p.join(tempDir.path, 'config', 'sync_token'))
.createSync(recursive: true);
expect(jsonDecode((await http.get(url('/github/auth/status'))).body), {
'configured': false,
});
});
test('passes a non-JSON device-flow response straight back', () async {
canned['https://github.com/login/oauth/access_token'] = http.Response(
'<html>rate limited</html>',
200,
);
final response = await http.post(
url('/github/auth/device/poll'),
body: jsonEncode({'client_id': 'cid', 'device_code': 'dc'}),
);
expect(response.body, contains('rate limited'));
});
test('treats a malformed request body as empty fields', () async {
final response = await http.post(
url('/github/auth/device/start'),
body: 'not json',
);
expect(response.statusCode, 200);
expect(outbound.single.bodyFields['client_id'], 'null');
});
});
group('content types', () {
test('labels each asset kind the browser is strict about', () {
ContentType typeOf(String name) =>
WrapperServer.contentTypeFor('/web/$name');
expect(typeOf('main.dart.js').toString(), contains('text/javascript'));
expect(typeOf('m.mjs').toString(), contains('text/javascript'));
expect(typeOf('manifest.json').mimeType, 'application/json');
expect(typeOf('style.css').toString(), contains('text/css'));
expect(typeOf('icon.png').mimeType, 'image/png');
expect(typeOf('photo.jpg').mimeType, 'image/jpeg');
expect(typeOf('logo.svg').mimeType, 'image/svg+xml');
expect(typeOf('f.ttf').mimeType, 'font/ttf');
expect(typeOf('f.otf').mimeType, 'font/otf');
expect(typeOf('f.woff2').mimeType, 'font/woff2');
expect(typeOf('data.bin').mimeType, 'application/octet-stream');
});
});
}

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/screens/calendar_screen.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -29,8 +30,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_calendar_');
LogStorageService.resetForTesting(testDir: tempDir);
await AppSettingsService.initForTesting(tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
@ -26,8 +27,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_edit_test_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/food_bank_screen.dart';
@ -13,8 +14,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_screen_');
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/screens/photo_viewer_screen.dart';
@ -12,7 +13,7 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_history_');
LogStorageService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -3,6 +3,7 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
@ -20,8 +21,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_autosync_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,5 +1,7 @@
import 'dart:io';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/models/slot.dart';
@ -133,10 +135,10 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_screen_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
PhotoAttachService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
PhotoAttachService.resetForTesting(store: FileBlobStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
originalImagePickerPlatform = ImagePickerPlatform.instance;
});

View File

@ -1,5 +1,7 @@
import 'dart:io';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/screens/meal_builder_screen.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -28,9 +30,9 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_builder_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
PhotoAttachService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
PhotoAttachService.resetForTesting(store: FileBlobStore(tempDir));
originalImagePickerPlatform = ImagePickerPlatform.instance;
});

View File

@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
@ -43,9 +44,9 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_settings_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
});

View File

@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:flutter_test/flutter_test.dart';
@ -28,12 +29,12 @@ void main() {
group('resetForTesting', () {
test('with testDir creates a working instance', () {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
expect(AppSettingsService.instance, isNotNull);
});
test('without testDir nulls the singleton', () {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting();
// instance getter throws when null — verify via dailyKcalGoal fallback.
expect(AppSettingsService.dailyKcalGoal, 2200);
@ -42,7 +43,7 @@ void main() {
group('init early-return', () {
test('returns existing instance without re-initialising', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
final first = AppSettingsService.instance;
// init() sees _instance != null and returns early (no platform channel).
final second = await AppSettingsService.init();
@ -52,7 +53,7 @@ void main() {
group('saveDailyKcalGoal', () {
test('updates in-memory value and persists to file', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.instance.saveDailyKcalGoal(1800);
expect(AppSettingsService.dailyKcalGoal, 1800);
@ -65,7 +66,7 @@ void main() {
});
test('stamps a fresh dailyKcalGoalUpdatedAt', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
final before = DateTime.now();
await AppSettingsService.instance.saveDailyKcalGoal(1800);
final after = DateTime.now();
@ -81,7 +82,7 @@ void main() {
test(
'persists the given value and updatedAt verbatim, not "now"',
() async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
final winningEdit = DateTime.utc(2020);
await AppSettingsService.instance.applySyncedBudget(
@ -105,7 +106,7 @@ void main() {
);
test('a null updatedAt is accepted and persisted as null', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.instance.applySyncedBudget(1700);
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
});
@ -117,13 +118,13 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoal, 1600);
});
test('keeps default 2200 when file does not exist', () async {
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -133,7 +134,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString('not json at all');
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -143,7 +144,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode([1, 2, 3]));
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -153,7 +154,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 'two thousand'}));
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoal, 2200);
});
@ -166,7 +167,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(
AppSettingsService.dailyKcalGoalUpdatedAt,
@ -181,7 +182,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
},
@ -197,7 +198,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.dailyKcalGoalUpdatedAt, isNull);
},
@ -212,7 +213,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.rewardLabel, 'Podcast');
expect(AppSettingsService.rewardUrl, 'https://example.com/podcast');
@ -223,7 +224,7 @@ void main() {
'${tempDir.path}/app_settings.json',
).writeAsString(jsonEncode({'daily_kcal_goal': 1600}));
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.rewardLabel, isNull);
expect(AppSettingsService.rewardUrl, isNull);
@ -238,7 +239,7 @@ void main() {
}),
);
await AppSettingsService.initForTesting(tempDir);
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
expect(AppSettingsService.rewardLabel, isNull);
expect(AppSettingsService.rewardUrl, isNull);
@ -254,7 +255,7 @@ void main() {
group('saveReward', () {
test('persists label and url, readable back via static getters', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.instance.saveReward(
label: 'Podcast',
url: 'https://example.com/podcast',
@ -272,7 +273,7 @@ void main() {
});
test('clears fields back to null when saved as null', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.instance.saveReward(
label: 'Podcast',
url: 'https://example.com/podcast',
@ -284,7 +285,7 @@ void main() {
});
test('does not disturb the existing kcal goal fields', () async {
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.instance.saveDailyKcalGoal(1800);
await AppSettingsService.instance.saveReward(
label: 'Podcast',

View File

@ -5,6 +5,7 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/background_sync_service.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
@ -22,12 +23,12 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_bg_sync_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
// Pre-seeds the singleton so backgroundSyncPush's own AppSettingsService
// .init() call short-circuits instead of hitting the real (unmocked in
// this test) path_provider channel.
AppSettingsService.resetForTesting(testDir: tempDir);
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -0,0 +1,65 @@
// Photo bytes went behind a BlobStore when the desktop target became a web
// build: Android keeps files, the browser keeps IndexedDB entries. These
// tests pin the file backend, which is what the phone actually runs.
import 'dart:io';
import 'dart:typed_data';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
void main() {
late Directory tempDir;
late FileBlobStore store;
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_blob_');
store = FileBlobStore(tempDir);
});
tearDown(() async => tempDir.delete(recursive: true));
test('put writes under images/ with the given extension', () async {
final key = await store.put('.jpg', Uint8List.fromList([1, 2, 3]));
expect(key, startsWith(p.join(tempDir.path, 'images')));
expect(key, endsWith('.jpg'));
expect(File(key).readAsBytesSync(), [1, 2, 3]);
});
test('put gives each blob its own key', () async {
final first = await store.put('.jpg', Uint8List.fromList([1]));
final second = await store.put('.jpg', Uint8List.fromList([2]));
expect(first, isNot(second));
});
test('get returns the stored bytes', () async {
final key = await store.put('.png', Uint8List.fromList([9, 8]));
expect(await store.get(key), [9, 8]);
});
test('get returns null for a photo that is gone', () async {
// The entry outlives its file when the user clears app storage; the UI
// shows a broken-image icon rather than failing to build.
expect(await store.get(p.join(tempDir.path, 'images', 'missing.jpg')), null);
});
test('get returns null when the path is not a readable file', () async {
final directoryPath = p.join(tempDir.path, 'a_directory')..toString();
Directory(directoryPath).createSync();
expect(await store.get(directoryPath), null);
});
test('PhotoAttachService.readBytes reads through its store', () async {
// Backs the web image widget, which cannot render from a path.
PhotoAttachService.resetForTesting(store: store);
addTearDown(PhotoAttachService.resetForTesting);
final key = await store.put('.jpg', Uint8List.fromList([4, 5]));
expect(await PhotoAttachService.instance.readBytes(key), [4, 5]);
});
}

View File

@ -1,13 +1,15 @@
// `checkAndNotify` is the unit-testable half of the WorkManager periodic
// `checkAndNotify` is the scheduler-independent half of the periodic
// check; `backgroundCheckCallbackDispatcher` itself is integration-only
// (real WorkManager isolate, manual on-device smoke test) per the project
// plan, and is excluded from coverage.
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/background_check_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
@ -31,10 +33,10 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_bg_check_');
LogStorageService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
notificationLog = installFakeAndroidNotifications();
NotificationService.resetForTesting(
plugin: FlutterLocalNotificationsPlugin(),
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
});

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/meal_component.dart';
@ -129,8 +130,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_bank_');
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {
@ -189,8 +190,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_manual_');
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {
@ -338,8 +339,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_fb_err_');
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/models/meal_component.dart';
@ -21,7 +22,7 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_test_');
LogStorageService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,3 +1,4 @@
import 'package:diet_guard_app/services/notification_backend_io.dart';
import 'package:diet_guard_app/services/notification_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
@ -21,7 +22,7 @@ void main() {
test('init calls the platform initialize method, idempotently', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
plugin: FlutterLocalNotificationsPlugin(),
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
@ -33,7 +34,7 @@ void main() {
test('requestPermission delegates to the Android implementation', () async {
installFakeAndroidNotifications();
NotificationService.resetForTesting(
plugin: FlutterLocalNotificationsPlugin(),
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
@ -43,7 +44,7 @@ void main() {
test('syncToSlots shows due slots and cancels the rest', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
plugin: FlutterLocalNotificationsPlugin(),
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
log.clear();
@ -65,7 +66,7 @@ void main() {
test('syncToSlots with no due slots cancels every known slot', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
plugin: FlutterLocalNotificationsPlugin(),
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
log.clear();
@ -81,7 +82,9 @@ void main() {
() async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
plugin: FlutterLocalNotificationsPlugin(),
backend: LocalNotificationsBackend(
FlutterLocalNotificationsPlugin(),
),
);
await NotificationService.init();

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/blob_store_io.dart';
import 'package:diet_guard_app/services/photo_attach_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
@ -26,7 +27,7 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_photo_');
originalPlatform = ImagePickerPlatform.instance;
PhotoAttachService.resetForTesting(testDir: tempDir);
PhotoAttachService.resetForTesting(store: FileBlobStore(tempDir));
});
tearDown(() async {

View File

@ -7,6 +7,7 @@
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/models/nutrition.dart';
@ -121,9 +122,9 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_sync_test_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
await AppSettingsService.initForTesting(tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
});
tearDown(() async {

View File

@ -1,5 +1,6 @@
import 'dart:io';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/main.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
@ -10,8 +11,8 @@ void main() {
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_app_');
LogStorageService.resetForTesting(testDir: tempDir);
FoodBankService.resetForTesting(testDir: tempDir);
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {

BIN
app/web/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 917 B

BIN
app/web/icons/Icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
app/web/icons/Icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

46
app/web/index.html Normal file
View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="diet_guard_app">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>diet_guard_app</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!--
You can customize the "flutter_bootstrap.js" script.
This is useful to provide a custom configuration to the Flutter loader
or to give the user feedback during the initialization process.
For more details:
* https://docs.flutter.dev/platform-integration/web/initialization
-->
<script src="flutter_bootstrap.js" async></script>
</body>
</html>

35
app/web/manifest.json Normal file
View File

@ -0,0 +1,35 @@
{
"name": "diet_guard_app",
"short_name": "diet_guard_app",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}