diff --git a/stronglift_replacement/workout_app/android/app/src/main/AndroidManifest.xml b/stronglift_replacement/workout_app/android/app/src/main/AndroidManifest.xml
index 99a0f19..413a16a 100644
--- a/stronglift_replacement/workout_app/android/app/src/main/AndroidManifest.xml
+++ b/stronglift_replacement/workout_app/android/app/src/main/AndroidManifest.xml
@@ -32,6 +32,12 @@
+
+
diff --git a/stronglift_replacement/workout_app/lib/main.dart b/stronglift_replacement/workout_app/lib/main.dart
index a0d75b1..5ceab8b 100644
--- a/stronglift_replacement/workout_app/lib/main.dart
+++ b/stronglift_replacement/workout_app/lib/main.dart
@@ -17,18 +17,23 @@ import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
+import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/pc_pairing.dart';
import 'package:workout_app/services/progression_sync_service.dart';
+import 'package:workout_app/services/run_checkpoint_location.dart';
+import 'package:workout_app/services/run_launch.dart';
import 'package:workout_app/services/run_upload_credentials.dart';
import 'package:workout_app/services/run_uploader.dart';
+import 'package:workout_app/services/run_wiring.dart';
import 'package:workout_app/services/runnerup_importer.dart';
import 'package:workout_app/services/shared_storage.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_device_id.dart';
import 'package:workout_app/services/sync_service.dart';
import 'package:workout_app/ui/theme.dart';
+import 'package:workout_app/widgets/run_landing.dart';
// coverage:ignore-start
// App bootstrap: permission request, DB init, and a real listening socket —
@@ -101,12 +106,14 @@ void main(List args) async {
// still pending from an earlier launch.
if (!Sandbox.enabled) await RunCredentialStore().importProvisionFile();
unawaited(RunUploader.instance.uploadPending());
+ installRunWiring();
// Before the UI exists: a service left over from a crashed or force-stopped
// workout must not sit in the status bar counting down nothing.
await stopStaleBreakService(
FlutterForegroundBreakClient(),
hasActiveWorkout: () async =>
await StorageService.instance.loadActiveSession() != null,
+ runIsOwed: runIsOwed, // the service may be hosting a run
);
await StorageService.instance.restoreFromBackupIfNeeded();
// The permission-free restore path, and the reason storage is now optional.
@@ -147,7 +154,13 @@ void main(List args) async {
localDir: sharedPathFor(Sandbox.packageName, kRunnerUpLocalDir),
).runGuarded(),
);
- runApp(const WorkoutApp());
+ final resumeRun =
+ Platform.isAndroid &&
+ await resumeRunOnLaunch(
+ owed: runIsOwed,
+ client: FlutterForegroundRunClient(),
+ );
+ runApp(WorkoutApp(resumeRun: resumeRun));
}
// coverage:ignore-end
@@ -157,8 +170,11 @@ void main(List args) async {
/// 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});
+ /// Creates the root app widget; [resumeRun] opens the live run screen.
+ const WorkoutApp({super.key, this.resumeRun = false});
+
+ /// A run is in progress: land on it, whatever launched the app.
+ final bool resumeRun;
@override
State createState() => _WorkoutAppState();
@@ -214,7 +230,10 @@ class _WorkoutAppState extends State with WidgetsBindingObserver {
fw.DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
- home: const HomeScreen(),
+ home: RunLanding(
+ owed: Platform.isAndroid ? runIsOwed : null,
+ child: HomeScreen(openRunOnLaunch: widget.resumeRun),
+ ),
// The one thing that must never be mistaken for the daily build: a
// ribbon on every screen, in the error colour, on the sandbox only.
builder: (context, child) => Sandbox.enabled
diff --git a/stronglift_replacement/workout_app/lib/screens/home_screen.dart b/stronglift_replacement/workout_app/lib/screens/home_screen.dart
index 4312e03..befe631 100644
--- a/stronglift_replacement/workout_app/lib/screens/home_screen.dart
+++ b/stronglift_replacement/workout_app/lib/screens/home_screen.dart
@@ -37,8 +37,12 @@ class HomeScreen extends StatefulWidget {
this.clock,
this.configuredProbe,
this.openWorkoutOnLaunch = true,
+ this.openRunOnLaunch = false,
});
+ /// A run is in progress: the first load opens the run, not the workout.
+ final bool openRunOnLaunch;
+
/// Sync service to use; defaults to a real [WorkoutSyncService].
final WorkoutSyncService? syncService;
@@ -97,6 +101,7 @@ class _HomeScreenState extends State {
lastDate.day == today.day;
final firstLoad = !_hasAutoOpened;
_hasAutoOpened = true;
+ final resumeRun = firstLoad && widget.openRunOnLaunch;
final launch = await _decideLaunch(
firstLoad: firstLoad,
hasSaved: saved != null,
@@ -122,7 +127,11 @@ class _HomeScreenState extends State {
// changes what the card says when it lands.
unawaited(_refreshSyncStatus());
- if (launch.open) {
+ if (resumeRun) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) unawaited(_openRun(resuming: true));
+ });
+ } else if (launch.open) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
unawaited(
diff --git a/stronglift_replacement/workout_app/lib/screens/home_screen_launch.dart b/stronglift_replacement/workout_app/lib/screens/home_screen_launch.dart
index 636f1fa..c7ae6ab 100644
--- a/stronglift_replacement/workout_app/lib/screens/home_screen_launch.dart
+++ b/stronglift_replacement/workout_app/lib/screens/home_screen_launch.dart
@@ -40,7 +40,9 @@ extension _HomeScreenLaunch on _HomeScreenState {
required DateTime today,
}) async {
const stay = (open: false, syncedToday: false, syncNotSetUp: false);
+ // A run in progress opens its own screen (see `_load`).
if (!firstLoad || !widget.openWorkoutOnLaunch) return stay;
+ if (widget.openRunOnLaunch) return stay;
final wantsFresh = !hasSaved && !doneLocally && !lockModeEnabled;
if (!hasSaved && !wantsFresh) return stay;
diff --git a/stronglift_replacement/workout_app/lib/screens/home_screen_navigation.dart b/stronglift_replacement/workout_app/lib/screens/home_screen_navigation.dart
index 6bfe4c6..2ef3120 100644
--- a/stronglift_replacement/workout_app/lib/screens/home_screen_navigation.dart
+++ b/stronglift_replacement/workout_app/lib/screens/home_screen_navigation.dart
@@ -16,11 +16,11 @@ extension _HomeScreenNavigation on _HomeScreenState {
/// Pushes the GPS run screen, then reloads (a finished run can change
/// today's credit once the PC has it).
- Future _openRun() async {
- SandboxLog.event('open run screen');
- await Navigator.of(
- context,
- ).push(MaterialPageRoute(builder: (_) => const RunScreen()));
+ Future _openRun({bool resuming = false}) async {
+ SandboxLog.event('open run screen', {'resuming': resuming});
+ await Navigator.of(context).push(
+ MaterialPageRoute(builder: (_) => RunScreen(resuming: resuming)),
+ );
unawaited(_load());
}
diff --git a/stronglift_replacement/workout_app/lib/screens/run_screen.dart b/stronglift_replacement/workout_app/lib/screens/run_screen.dart
index 441fb25..f1d1dfd 100644
--- a/stronglift_replacement/workout_app/lib/screens/run_screen.dart
+++ b/stronglift_replacement/workout_app/lib/screens/run_screen.dart
@@ -8,46 +8,30 @@ library;
import 'dart:async';
-import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';
import 'package:material_ui/material_ui.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox_log.dart';
-import 'package:workout_app/sandbox/sandbox_run_replay.dart';
-import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
-import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_format.dart';
-import 'package:workout_app/services/run_recorder.dart';
-import 'package:workout_app/services/run_saver.dart';
+import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_uploader.dart';
-import 'package:workout_app/services/storage_service.dart';
+import 'package:workout_app/services/run_view.dart';
import 'package:workout_app/ui/theme.dart';
+import 'package:workout_app/widgets/run_finish_dialog.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import 'package:workout_app/widgets/run_pace_picker.dart';
import 'package:workout_app/widgets/run_upload_badge.dart';
part 'run_screen_numbers.dart';
part 'run_screen_parts.dart';
-
-/// The controller the app uses: real GPS (or the sandbox replay), the real
-/// foreground service, the real database and the app-wide upload queue.
-RunController buildRunController() => RunController(
- sourceFor: positionSourceFor,
- idleSourceFor: idlePositionSourceFor,
- service: FlutterForegroundRunClient(),
- cues: FeedbackCues(AudioPlayer()),
- save: (track) => saveRecordedRun(
- track,
- storage: StorageService.instance,
- enqueue: RunUploader.instance.uploadPending,
- ),
-);
+part 'run_screen_pulse.dart';
+part 'run_screen_state.dart';
/// Builds the live map from the run's accepted points and the user's current
/// position (shown until the run has points).
@@ -59,19 +43,29 @@ typedef RunMapBuilder =
);
/// Records one GPS activity (always a run).
+///
+/// The run itself lives in a host that outlasts this screen: leaving, closing
+/// the app or replacing this screen never ends it. Only the finish button
+/// followed by its confirm modal does.
class RunScreen extends StatefulWidget {
/// Creates the screen; every argument is a test or map seam.
const RunScreen({
super.key,
- this.controllerFactory = buildRunController,
+ this.controllerFactory,
this.uploader,
this.paceStore,
this.mapBuilder,
this.openSettings = openAppSettings,
+ this.resuming = false,
});
+ /// The factory `main` installs: real GPS, the real service and database.
+ /// Set once at startup; tests pass [controllerFactory] instead.
+ static RunController Function()? defaultControllerFactory;
+
/// Builds the controller for a recording (called again for "new run").
- final RunController Function() controllerFactory;
+ /// Defaults to [defaultControllerFactory].
+ final RunController Function()? controllerFactory;
/// The upload queue shown in the badge; defaults to the app-wide one.
final RunUploader? uploader;
@@ -85,147 +79,14 @@ class RunScreen extends StatefulWidget {
/// Opens the system settings page for this app.
final Future Function() openSettings;
+ /// The app opened because a run is in progress: back does nothing until
+ /// the host has answered and the run is on screen.
+ final bool resuming;
+
@override
State createState() => _RunScreenState();
}
-class _RunScreenState extends State with WidgetsBindingObserver {
- late RunController _controller = widget.controllerFactory();
- late final RunUploader _uploader = widget.uploader ?? RunUploader.instance;
- late final PaceTargetStore _paceStore =
- widget.paceStore ?? PrefsPaceTargetStore();
- bool _starting = false;
- bool _paceOn = false;
- int _paceTarget = kDefaultPaceTarget;
-
- @override
- void initState() {
- super.initState();
- SandboxLog.event('open run');
- WidgetsBinding.instance.addObserver(this);
- unawaited(_controller.watchIdle());
- unawaited(_loadPaceTarget());
- // So the badge shows the real queue, not the pre-first-pass default.
- unawaited(_uploader.uploadPending());
- }
-
- @override
- void dispose() {
- WidgetsBinding.instance.removeObserver(this);
- _controller.dispose();
- super.dispose();
- }
-
- @override
- void didChangeAppLifecycleState(AppLifecycleState state) {
- // A silent re-check: the permission prompt itself backgrounds the app, so
- // asking again here would loop.
- if (state == AppLifecycleState.resumed) {
- unawaited(_controller.recheckAccess());
- }
- }
-
- Future _loadPaceTarget() async {
- final stored = await _paceStore.load();
- if (mounted) setState(() => _paceTarget = stored);
- }
-
- void _setPaceTarget(int seconds) {
- setState(() => _paceTarget = seconds);
- unawaited(_paceStore.save(seconds));
- }
-
- Future _start() async {
- setState(() => _starting = true);
- _controller.recorder.setPaceTarget(_paceOn ? _paceTarget : null);
- try {
- await _controller.start();
- } finally {
- if (mounted) setState(() => _starting = false);
- }
- }
-
- void _again() {
- final old = _controller;
- setState(() => _controller = widget.controllerFactory());
- unawaited(_controller.watchIdle());
- old.dispose();
- }
-
- /// Fixable refusals open the system settings; a plain denial asks again.
- VoidCallback? _issueTap(RunIssue issue) => switch (issue) {
- RunIssue.deniedForever ||
- RunIssue.serviceOff => () => unawaited(widget.openSettings()),
- RunIssue.denied => () => unawaited(_controller.watchIdle()),
- _ => null,
- };
-
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: _controller,
- builder: (context, _) {
- final c = _controller;
- final r = c.recorder;
- final blocked = c.blocked;
- final issue = _IssueButton(
- issue: r.issue,
- onTap: _issueTap(r.issue),
- size: blocked ? 96 : 24,
- );
- return PopScope(
- // A recording lives in this screen's controller: leaving would lose it.
- canPop: !c.active,
- child: Scaffold(
- body: SafeArea(
- child: Padding(
- padding: const EdgeInsets.all(AppSpacing.md),
- child: Column(
- children: [
- _StatusRow(
- controller: c,
- uploader: _uploader,
- issue: blocked ? null : issue,
- ),
- const SizedBox(height: AppSpacing.sm),
- if (blocked)
- Expanded(child: Center(child: issue))
- else ...[
- Expanded(
- flex: 4,
- child: KeyedSubtree(
- key: ObjectKey(c),
- child: (widget.mapBuilder ?? _defaultMap)(
- context,
- r.livePoints,
- c.position,
- ),
- ),
- ),
- const SizedBox(height: AppSpacing.md),
- Expanded(flex: 3, child: _Numbers(recorder: r)),
- const SizedBox(height: AppSpacing.md),
- _Controls(
- controller: c,
- starting: _starting,
- paceOn: _paceOn,
- paceTarget: _paceTarget,
- onPaceToggle: () => setState(() => _paceOn = !_paceOn),
- onPaceChanged: _setPaceTarget,
- onStart: () => unawaited(_start()),
- onAgain: _again,
- onClose: () => Navigator.of(context).maybePop(),
- ),
- ],
- ],
- ),
- ),
- ),
- ),
- );
- },
- );
-}
-
Widget _defaultMap(
BuildContext context,
ValueListenable> points,
diff --git a/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart b/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart
index 27cb0eb..395dca6 100644
--- a/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart
+++ b/stronglift_replacement/workout_app/lib/screens/run_screen_numbers.dart
@@ -3,15 +3,15 @@
part of 'run_screen.dart';
class _Numbers extends StatelessWidget {
- const _Numbers({required this.recorder});
+ const _Numbers({required this.view});
- final RunRecorder recorder;
+ final RunView view;
/// Green on pace, red off it, plain while there is no verdict yet.
Color _paceColour(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final colors = Theme.of(context).extension()!;
- final band = recorder.coach.band;
+ final band = view.band;
if (band == null) return scheme.onSurface;
return band == PaceBand.onPace ? colors.success : scheme.error;
}
@@ -44,14 +44,14 @@ class _Numbers extends StatelessWidget {
],
),
);
- final current = recorder.coach.pace;
+ final current = view.pace;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: big(
const Key('run_time'),
- formatDuration(recorder.seconds),
+ formatDuration(view.seconds),
96,
scheme.onSurface,
),
@@ -62,17 +62,17 @@ class _Numbers extends StatelessWidget {
small(
Icons.straighten,
const Key('run_distance'),
- formatDistanceKm(recorder.distanceM),
+ formatDistanceKm(view.distanceM),
),
small(
Icons.speed,
const Key('run_pace'),
formatPace(
- seconds: recorder.seconds,
- distanceM: recorder.distanceM,
+ seconds: view.seconds,
+ distanceM: view.distanceM,
),
),
- if (recorder.coach.target != null)
+ if (view.paceTarget != null)
small(
Icons.bolt,
const Key('run_pace_now'),
diff --git a/stronglift_replacement/workout_app/lib/screens/run_screen_parts.dart b/stronglift_replacement/workout_app/lib/screens/run_screen_parts.dart
index fc52f98..6ee552a 100644
--- a/stronglift_replacement/workout_app/lib/screens/run_screen_parts.dart
+++ b/stronglift_replacement/workout_app/lib/screens/run_screen_parts.dart
@@ -115,6 +115,7 @@ class _Controls extends StatelessWidget {
required this.onPaceToggle,
required this.onPaceChanged,
required this.onStart,
+ required this.onFinish,
required this.onAgain,
required this.onClose,
});
@@ -126,12 +127,13 @@ class _Controls extends StatelessWidget {
final VoidCallback onPaceToggle;
final ValueChanged onPaceChanged;
final VoidCallback onStart;
+ final VoidCallback onFinish;
final VoidCallback onAgain;
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
- final recorder = controller.recorder;
+ final view = controller.view;
final scheme = Theme.of(context).colorScheme;
Widget button(
String id,
@@ -152,7 +154,13 @@ class _Controls extends StatelessWidget {
);
}
- final buttons = switch (recorder.phase) {
+ // Advice to finish (stationary, vehicle speed, GPS lost, restored) only
+ // makes this button pulse: the run ends on the modal's check, nowhere else.
+ final finish = _PulsingFinish(
+ pulsing: view.suggestion != null,
+ child: button('finish', Icons.stop, onFinish, tint: scheme.error),
+ );
+ final buttons = switch (view.phase) {
RunPhase.idle => [
Flexible(
child: RunPacePicker(
@@ -170,21 +178,11 @@ class _Controls extends StatelessWidget {
],
RunPhase.recording => [
button('pause', Icons.pause, controller.pause),
- button(
- 'finish',
- Icons.stop,
- () => unawaited(controller.finish()),
- tint: scheme.error,
- ),
+ finish,
],
RunPhase.paused => [
button('resume', Icons.play_arrow, controller.resume),
- button(
- 'finish',
- Icons.stop,
- () => unawaited(controller.finish()),
- tint: scheme.error,
- ),
+ finish,
],
RunPhase.finished => [
button('again', Icons.refresh, controller.saving ? null : onAgain),
diff --git a/stronglift_replacement/workout_app/lib/screens/run_screen_pulse.dart b/stronglift_replacement/workout_app/lib/screens/run_screen_pulse.dart
new file mode 100644
index 0000000..3037dd9
--- /dev/null
+++ b/stronglift_replacement/workout_app/lib/screens/run_screen_pulse.dart
@@ -0,0 +1,57 @@
+// The finish button's pulse: the one cue that finishing is suggested.
+part of 'run_screen.dart';
+
+/// Pulses [child] while [pulsing]: the one cue the screen gives that finishing
+/// is suggested. A symbol of motion, no words.
+class _PulsingFinish extends StatefulWidget {
+ const _PulsingFinish({required this.pulsing, required this.child});
+
+ final bool pulsing;
+ final Widget child;
+
+ @override
+ State<_PulsingFinish> createState() => _PulsingFinishState();
+}
+
+class _PulsingFinishState extends State<_PulsingFinish>
+ with SingleTickerProviderStateMixin {
+ late final AnimationController _pulse = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 700),
+ lowerBound: 0.88,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ _sync();
+ }
+
+ @override
+ void didUpdateWidget(_PulsingFinish old) {
+ super.didUpdateWidget(old);
+ _sync();
+ }
+
+ void _sync() {
+ if (widget.pulsing && !_pulse.isAnimating) {
+ _pulse.repeat(reverse: true);
+ } else if (!widget.pulsing && _pulse.isAnimating) {
+ _pulse.value = 1;
+ _pulse.stop();
+ }
+ }
+
+ @override
+ void dispose() {
+ _pulse.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => ScaleTransition(
+ key: Key(widget.pulsing ? 'run_finish_pulse' : 'run_finish_still'),
+ scale: widget.pulsing ? _pulse : const AlwaysStoppedAnimation(1),
+ child: widget.child,
+ );
+}
diff --git a/stronglift_replacement/workout_app/lib/screens/run_screen_state.dart b/stronglift_replacement/workout_app/lib/screens/run_screen_state.dart
new file mode 100644
index 0000000..44ebb31
--- /dev/null
+++ b/stronglift_replacement/workout_app/lib/screens/run_screen_state.dart
@@ -0,0 +1,177 @@
+// The run screen's state: the controller's life, the finish modal, "new run".
+part of 'run_screen.dart';
+
+class _RunScreenState extends State with WidgetsBindingObserver {
+ late RunController _controller = _build();
+ late final RunUploader _uploader = widget.uploader ?? RunUploader.instance;
+ late final PaceTargetStore _paceStore =
+ widget.paceStore ?? PrefsPaceTargetStore();
+ bool _starting = false;
+ bool _paceOn = false;
+ bool _asking = false;
+ int _paceTarget = kDefaultPaceTarget;
+
+ RunController _build() =>
+ (widget.controllerFactory ?? RunScreen.defaultControllerFactory!)();
+
+ @override
+ void initState() {
+ super.initState();
+ SandboxLog.event('open run');
+ WidgetsBinding.instance.addObserver(this);
+ _wire(_controller);
+ unawaited(_controller.watchIdle());
+ unawaited(_loadPaceTarget());
+ // So the badge shows the real queue, not the pre-first-pass default.
+ unawaited(_uploader.uploadPending());
+ }
+
+ /// Hears the host, so a notification tap or a started run reaches the
+ /// screen; asks it where the run stands.
+ void _wire(RunController c) {
+ c.addListener(_onControllerChanged);
+ unawaited(c.attach());
+ }
+
+ /// The notification asked for the finish modal: show it once.
+ void _onControllerChanged() {
+ if (_controller.view.promptFinish && !_asking && mounted) {
+ unawaited(_askFinish());
+ }
+ }
+
+ @override
+ void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ _controller
+ ..removeListener(_onControllerChanged)
+ // Hangs up only: the run is in the host and goes on.
+ ..dispose();
+ super.dispose();
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ // A silent re-check: the permission prompt itself backgrounds the app, so
+ // asking again here would loop.
+ if (state == AppLifecycleState.resumed) {
+ unawaited(_controller.recheckAccess());
+ }
+ }
+
+ Future _loadPaceTarget() async {
+ final stored = await _paceStore.load();
+ if (mounted) setState(() => _paceTarget = stored);
+ }
+
+ void _setPaceTarget(int seconds) {
+ setState(() => _paceTarget = seconds);
+ unawaited(_paceStore.save(seconds));
+ }
+
+ Future _start() async {
+ setState(() => _starting = true);
+ try {
+ await _controller.start(paceTarget: _paceOn ? _paceTarget : null);
+ } finally {
+ if (mounted) setState(() => _starting = false);
+ }
+ }
+
+ /// The one way a run ends: the confirm modal's red check.
+ Future _askFinish() async {
+ if (_asking) return;
+ _asking = true;
+ try {
+ if (_controller.view.promptFinish) _controller.ackPrompt();
+ final end = await showRunFinishDialog(context);
+ if (end && mounted) await _controller.finish();
+ } finally {
+ _asking = false;
+ }
+ }
+
+ void _again() {
+ final old = _controller..removeListener(_onControllerChanged);
+ setState(() => _controller = _build());
+ _wire(_controller);
+ unawaited(_controller.watchIdle());
+ // Hangs up the old link; a run still going in the host is untouched.
+ old.dispose();
+ }
+
+ /// Fixable refusals open the system settings; a plain denial asks again.
+ VoidCallback? _issueTap(RunIssue issue) => switch (issue) {
+ RunIssue.deniedForever ||
+ RunIssue.serviceOff => () => unawaited(widget.openSettings()),
+ RunIssue.denied => () => unawaited(_controller.watchIdle()),
+ _ => null,
+ };
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: _controller,
+ builder: (context, _) {
+ final c = _controller;
+ final v = c.view;
+ final blocked = c.blocked;
+ final issue = _IssueButton(
+ issue: v.issue,
+ onTap: _issueTap(v.issue),
+ size: blocked ? 96 : 24,
+ );
+ return PopScope(
+ // The run lives in the host, but the screen still refuses to be left
+ // while one is going (or while a resumed one has not shown up yet).
+ canPop: !c.active && !(widget.resuming && !c.attachGaveUp && !v.synced),
+ child: Scaffold(
+ body: SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.all(AppSpacing.md),
+ child: Column(
+ children: [
+ _StatusRow(
+ controller: c,
+ uploader: _uploader,
+ issue: blocked ? null : issue,
+ ),
+ const SizedBox(height: AppSpacing.sm),
+ if (blocked)
+ Expanded(child: Center(child: issue))
+ else ...[
+ Expanded(
+ flex: 4,
+ child: KeyedSubtree(
+ key: ObjectKey(c),
+ child: (widget.mapBuilder ?? _defaultMap)(
+ context,
+ v.livePoints,
+ c.position,
+ ),
+ ),
+ ),
+ const SizedBox(height: AppSpacing.md),
+ Expanded(flex: 3, child: _Numbers(view: v)),
+ const SizedBox(height: AppSpacing.md),
+ _Controls(
+ controller: c,
+ starting: _starting,
+ paceOn: _paceOn,
+ paceTarget: _paceTarget,
+ onPaceToggle: () => setState(() => _paceOn = !_paceOn),
+ onPaceChanged: _setPaceTarget,
+ onStart: () => unawaited(_start()),
+ onFinish: () => unawaited(_askFinish()),
+ onAgain: _again,
+ onClose: () => Navigator.of(context).maybePop(),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/stronglift_replacement/workout_app/lib/services/break_service_controller.dart b/stronglift_replacement/workout_app/lib/services/break_service_controller.dart
index 86789b2..e5b6cd9 100644
--- a/stronglift_replacement/workout_app/lib/services/break_service_controller.dart
+++ b/stronglift_replacement/workout_app/lib/services/break_service_controller.dart
@@ -20,8 +20,12 @@ import 'package:workout_app/services/foreground_break_client.dart';
Future stopStaleBreakService(
ForegroundBreakClient client, {
required Future Function() hasActiveWorkout,
+ required Future Function() runIsOwed,
}) async {
if (!client.isSupported) return false;
+ // The one foreground service may be hosting a run (it comes back after a
+ // kill, with no workout session): stopping it would end the run.
+ if (await runIsOwed()) return false;
if (!await client.isRunning()) return false;
if (await hasActiveWorkout()) return false;
log(
diff --git a/stronglift_replacement/workout_app/lib/services/feedback_cues.dart b/stronglift_replacement/workout_app/lib/services/feedback_cues.dart
index a2db859..d4136b0 100644
--- a/stronglift_replacement/workout_app/lib/services/feedback_cues.dart
+++ b/stronglift_replacement/workout_app/lib/services/feedback_cues.dart
@@ -109,4 +109,29 @@ class FeedbackCues {
debugPrint('WorkoutApp: pace tone failed to play ($error).');
});
}
+
+ /// The recorder suggests finishing the run (stationary, vehicle speed, GPS
+ /// lost, restored): three buzzes and, if allowed, the chime. Advice only,
+ /// the run keeps going.
+ Future finishSuggested() => _longCue('cue finish suggested');
+
+ /// The 5 h limit ended the run: the same buzz and chime as a suggestion, so
+ /// a phone in a pocket says something happened.
+ Future autoEnded() => _longCue('cue run auto-ended');
+
+ Future _longCue(String event) async {
+ SandboxLog.event(event, {'sound': soundOn});
+ if (await Vibration.hasVibrator()) {
+ // Android/iOS-only: hasVibrator() is false on the Linux test host.
+ // coverage:ignore-start
+ unawaited(Vibration.vibrate(pattern: [0, 300, 150, 300, 150, 300]));
+ // coverage:ignore-end
+ }
+ if (!soundOn) return;
+ await _player.play(AssetSource('sounds/workout_done.wav')).catchError((
+ Object error,
+ ) {
+ debugPrint('WorkoutApp: $event chime failed to play ($error).');
+ });
+ }
}
diff --git a/stronglift_replacement/workout_app/lib/services/foreground_break_client_flutter.dart b/stronglift_replacement/workout_app/lib/services/foreground_break_client_flutter.dart
index 079e95f..6b81022 100644
--- a/stronglift_replacement/workout_app/lib/services/foreground_break_client_flutter.dart
+++ b/stronglift_replacement/workout_app/lib/services/foreground_break_client_flutter.dart
@@ -1,6 +1,7 @@
/// The real foreground-service client, and the service's entry point.
library;
+import 'dart:developer';
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
@@ -12,6 +13,8 @@ import 'package:workout_app/services/break_service_port.dart';
import 'package:workout_app/services/break_service_port_flutter.dart';
import 'package:workout_app/services/break_task_handler.dart';
import 'package:workout_app/services/foreground_break_client.dart';
+import 'package:workout_app/services/run_checkpoint_location.dart';
+import 'package:workout_app/services/run_wire.dart';
/// Channel the ongoing workout notification lives on.
///
@@ -113,8 +116,12 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
);
}
+ /// The shared service hosts a RUN while its checkpoint exists; this client
+ /// must neither see, replace nor stop it (stopping clears the options the
+ /// plugin keeps for a boot restart, and ends the run).
@override
- Future isRunning() => FlutterForegroundTask.isRunningService;
+ Future isRunning() async =>
+ !await runIsOwed() && await FlutterForegroundTask.isRunningService;
@override
Future hasNotificationPermission() async =>
@@ -128,6 +135,14 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
@override
Future start(BreakSnapshot snapshot) async {
+ if (await runIsOwed()) {
+ log(
+ 'WorkoutApp: a GPS run owns the foreground service, so the break '
+ 'timer service was not started. The in-app countdown still works.',
+ level: 1000,
+ );
+ return false;
+ }
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
@@ -154,6 +169,7 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
@override
Future stop() async {
+ if (await runIsOwed()) return;
if (await FlutterForegroundTask.isRunningService) {
await FlutterForegroundTask.stopService();
}
@@ -174,7 +190,10 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
/// The service's nudge carries no payload -- see [BreakServicePort]. Any
/// message from the task isolate means "the queue has something in it".
- void _handleTaskData(Object data) => _onNudge?.call();
+ void _handleTaskData(Object data) {
+ // The run host shares this channel; its snapshots are not nudges.
+ if (!isRunMessage(data)) _onNudge?.call();
+ }
// coverage:ignore-end
}
diff --git a/stronglift_replacement/workout_app/lib/services/foreground_run_client_flutter.dart b/stronglift_replacement/workout_app/lib/services/foreground_run_client_flutter.dart
index 1f417c1..5e71030 100644
--- a/stronglift_replacement/workout_app/lib/services/foreground_run_client_flutter.dart
+++ b/stronglift_replacement/workout_app/lib/services/foreground_run_client_flutter.dart
@@ -1,11 +1,17 @@
-/// The real run foreground-service client, and the service's entry point.
+/// The real run foreground-service client and the UI's real link to its host.
library;
+import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
+import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/services/break_notification_text.dart';
import 'package:workout_app/services/foreground_run_client.dart';
+import 'package:workout_app/services/run_link.dart';
+import 'package:workout_app/services/run_service_isolate.dart';
+import 'package:workout_app/services/run_wire.dart';
+import 'package:workout_app/services/storage_service.dart';
/// Channel the ongoing run notification lives on.
///
@@ -15,32 +21,6 @@ import 'package:workout_app/services/foreground_run_client.dart';
/// shows it in system settings.
const kRunOngoingChannelId = 'run_ongoing_v1';
-// coverage:ignore-start
-/// Entry point the plugin calls in the background isolate.
-///
-/// The handler does nothing: the recorder lives in the UI isolate. The
-/// service exists to keep that isolate's process alive, to hold the wake lock
-/// and to own the notification.
-@pragma('vm:entry-point')
-void runServiceStartCallback() {
- FlutterForegroundTask.setTaskHandler(_RunServiceTaskHandler());
-}
-
-class _RunServiceTaskHandler extends TaskHandler {
- @override
- Future onStart(DateTime timestamp, TaskStarter starter) async {}
-
- @override
- void onRepeatEvent(DateTime timestamp) {}
-
- @override
- void onNotificationPressed() => FlutterForegroundTask.launchApp();
-
- @override
- Future onDestroy(DateTime timestamp, bool isTimeout) async {}
-}
-// coverage:ignore-end
-
/// The real [ForegroundRunClient], driving `flutter_foreground_task`.
class FlutterForegroundRunClient implements ForegroundRunClient {
/// Creates a client. Cheap: nothing happens until [start].
@@ -51,7 +31,8 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
// Platform-channel passthroughs. `flutter test` runs on Linux, where
// isSupported is false and none of this is reachable; the decisions that
- // lead here live in run_controller.dart, covered against a fake.
+ // lead here live in run_controller.dart and run_host.dart, covered against
+ // fakes.
// coverage:ignore-start
@override
@@ -64,12 +45,16 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
await FlutterForegroundTask.requestNotificationPermission() ==
NotificationPermission.granted;
+ /// Starts the service, or leaves a running one alone: a live service may be
+ /// hosting a run, and replacing it would end that run.
@override
Future start({
required bool withLocation,
required String title,
required String text,
}) async {
+ if (await FlutterForegroundTask.isRunningService) return true;
+ await _saveFlags();
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: kRunOngoingChannelId,
@@ -80,18 +65,17 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
iosNotificationOptions: const IOSNotificationOptions(),
foregroundTaskOptions: ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.nothing(),
+ // The run must come back by itself after a reboot, and the plugin
+ // restarts a killed service (allowAutoRestart defaults to true).
// allowWakeLock stays at its default (true): it is why GPS fixes keep
// arriving with the screen off.
+ autoRunOnBoot: true,
),
);
- if (await FlutterForegroundTask.isRunningService) {
- await FlutterForegroundTask.stopService();
- }
final result = await FlutterForegroundTask.startService(
- serviceTypes: [
- ForegroundServiceTypes.dataSync,
- if (withLocation) ForegroundServiceTypes.location,
- ],
+ // `location` alone: Android 15 refuses a dataSync service from the boot
+ // broadcast, and dataSync has a 6 h budget a long run can exhaust.
+ serviceTypes: [ForegroundServiceTypes.location],
notificationTitle: title,
notificationText: text,
callback: runServiceStartCallback,
@@ -99,6 +83,21 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
return result is ServiceRequestSuccess;
}
+ Future _saveFlags() async {
+ await FlutterForegroundTask.saveData(
+ key: kRunFlagSandbox,
+ value: Sandbox.enabled,
+ );
+ await FlutterForegroundTask.saveData(
+ key: kRunFlagReplayFactor,
+ value: Sandbox.runReplayFactor,
+ );
+ await FlutterForegroundTask.saveData(
+ key: kRunFlagSound,
+ value: await StorageService.instance.getSoundEnabled(),
+ );
+ }
+
@override
Future update({required String title, required String text}) async {
await FlutterForegroundTask.updateService(
@@ -116,3 +115,34 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
// coverage:ignore-end
}
+
+/// The UI's link to the host in the service isolate.
+// coverage:ignore-start
+class ServiceRunLink implements RunLink {
+ /// Listens for the host's messages until [close].
+ ServiceRunLink() {
+ FlutterForegroundTask.addTaskDataCallback(_onData);
+ }
+
+ final _out = StreamController