screen-locker/stronglift_replacement/workout_app/lib/main.dart
Krzysztof kuhy Rudnicki 186bfcabc4 Run the workout app on Linux, and let it hold the screen lock
The phone is lost, so no workout can be recorded and enforcement has been
disarmed since 2026-08-21. This gives the PC a first-class way to do the
workout, reusing the existing app rather than reimplementing the progression
rules a second time -- two implementations would guarantee the divergence the
"same weights everywhere" requirement forbids.

Storage: sqflite has no Linux plugin, so main() installs sqflite_common_ffi's
factory, which runs the same schema and migrations against the same SQL. It
was already a dev dependency driving the test suite; this only promotes it.

Auth: the account password in ~/.config/crdt-sync no longer authenticates
(verified: HTTP 400 INVALID_LOGIN_CREDENTIALS). The PC fleet has been running
on the cached refresh token all along, so the desktop credential store reads
that same 0600 file -- the Dart and Python credential JSON keys are already
identical -- and passes null instead of the stale password. This also avoids
google_sign_in, which ships no Linux implementation.

Lock mode: --lock-mode makes the window the lock surface. There is no Dart API
for this, so the runner sets override-redirect and takes an exclusive
gdk_seat_grab. Two details cost a debugging cycle each and are commented in
place: override-redirect must be set BEFORE the first map, or the window stays
mapped and never repaints; and gtk_window_fullscreen() only ASKS the window
manager, which cannot see an override-redirect window -- so the geometry is
set from the monitor directly, otherwise a strip of live desktop is left
uncovered at the edge of a larger screen.

The grab is acquired by retry rather than by asking the supervisor to release
first: the Python locker keeps its grab while this window maps on top, so the
screen is covered continuously instead of exposing the desktop for the whole
of Flutter's cold start.

Verified against the live data: pulls all 7 exercises from Firebase (Bench
17.5x12, RDL 27.5x8, Row 25x6, Situp 10x31 -- the real weights, not factory
defaults), leaves the remote progression byte-identical, and mints its own
device id rather than reusing the phone's. A Tk client is refused the grab
while the lock holds it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfJC1Wu1SEgJ6X49k5Jqtg
2026-08-22 11:18:48 +02:00

141 lines
5.6 KiB
Dart

import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/ui/theme.dart';
// coverage:ignore-start
// App bootstrap: permission request, DB init, and a real listening socket —
// platform-channel work that can't run on the CI test host. The pieces it wires
// up are unit-tested individually; the entry point itself is not.
void main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
// Must precede runApp: the UI reads this to decide whether to offer
// any way out of the workout.
lockModeEnabled = parseLockMode(args);
// Linux desktop has no sqflite plugin. The FFI factory runs the same
// schema and migrations against the same SQL, so this is a transport
// swap, not a second storage implementation. Must precede any DB open.
if (Platform.isLinux) {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
}
// Before anything that stamps an Hlc or syncs: until this resolves, the
// device id falls back to the pre-migration constant.
await initSyncDeviceId();
// Storage permission is settled before the DB is opened: opening it seeds
// factory defaults for any missing exercise, and restoring afterwards is a
// no-op once rows exist. Losing that race is what wiped months of
// progression on 2026-08-05.
//
// CHECKED, never requested. `request()` throws the user into a system
// Settings page on every launch where the permission is absent, and since
// Firebase now carries progression the `/sdcard` backup is a second copy
// rather than the only one. The grant prompt lives in Settings, where the
// user asks for it.
final storageGranted = await BackupService.instance.hasStoragePermission();
if (!storageGranted) {
debugPrint(
'WorkoutApp: no storage permission — the backup at $kBackupPath can '
'neither be read nor written, so progression rides on Firebase alone. '
'Grant it in Settings to keep a second, offline copy.',
);
}
await StorageService.init();
await StorageService.instance.restoreFromBackupIfNeeded();
// The permission-free restore path, and the reason storage is now optional.
// `backup.json` is unreadable without the grant, so on a denied reinstall the
// line above is a no-op and this is the ONLY thing between the user and
// factory defaults. Safe to run unconditionally: it applies remote records
// only to a freshly-installed DB, so it restores a wiped install but never
// overwrites progression — or a deliberate reset — made on this phone.
//
// Bounded: this is N sequential network reads on the launch path, so a slow
// or half-open connection would otherwise hold the UI on a blank screen.
// Timing out is safe — it leaves `progression_synced_at` unset, so the next
// launch retries and, until it succeeds, pushProgression refuses to
// overwrite the remote copy.
final restored = await ProgressionSyncService()
.pullProgression()
.timeout(
const Duration(seconds: 20),
onTimeout: () => const ProgressionSyncResult(
changed: false,
reason:
'progression pull timed out after 20s — starting on local state; '
'the next launch will retry',
),
);
debugPrint('WorkoutApp: ${restored.reason}');
// Android-only transport: it exists so the PC can pull today's workout off
// the phone over LAN. On the PC itself it would bind the very port the PC
// scans, so it is skipped rather than serving the machine to itself.
if (!Platform.isLinux) {
await HttpServerService.instance.start();
}
runApp(const WorkoutApp());
}
// coverage:ignore-end
/// Root widget that bootstraps the app with Material 3 dark theming.
///
/// Also owns the app-lifecycle observer that stops [HttpServerService]'s
/// listening socket while the app is backgrounded, so the process (and its
/// open socket) doesn't sit alive indefinitely and block Doze/App-Standby.
class WorkoutApp extends StatefulWidget {
/// Creates the root app widget.
const WorkoutApp({super.key});
@override
State<WorkoutApp> createState() => _WorkoutAppState();
}
class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The socket is never started on Linux (see main()), so there is nothing
// to stop or restart here either.
if (Platform.isLinux) return;
switch (state) {
case AppLifecycleState.paused:
case AppLifecycleState.detached:
unawaited(HttpServerService.instance.stop());
case AppLifecycleState.resumed:
unawaited(HttpServerService.instance.start());
case AppLifecycleState.inactive:
case AppLifecycleState.hidden:
break;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Workout Tracker',
debugShowCheckedModeBanner: false,
theme: buildAppTheme(),
home: const HomeScreen(),
);
}
}