mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-24 09:06:29 +01:00
Host the run in the foreground service
WIP: host, link, view, finish modal, launch routing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
This commit is contained in:
parent
bdf79ca6be
commit
c1dbfa0352
@ -32,6 +32,12 @@
|
|||||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||||
<uses-permission
|
<uses-permission
|
||||||
android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
||||||
|
<!-- A location foreground service that is (re)started from the
|
||||||
|
background (sticky restart after a kill, boot) may only read the
|
||||||
|
location if this is held; without it the run would restart silently
|
||||||
|
and receive no fixes. -->
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||||
<!-- Required by ForegroundTaskOptions(allowWakeLock: true), which takes a
|
<!-- Required by ForegroundTaskOptions(allowWakeLock: true), which takes a
|
||||||
PARTIAL_WAKE_LOCK so the deadline fires with the screen off. -->
|
PARTIAL_WAKE_LOCK so the deadline fires with the screen off. -->
|
||||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
|||||||
@ -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/backup_service.dart';
|
||||||
import 'package:workout_app/services/break_service_controller.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_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/http_server_service.dart';
|
||||||
import 'package:workout_app/services/lock_mode.dart';
|
import 'package:workout_app/services/lock_mode.dart';
|
||||||
import 'package:workout_app/services/pc_pairing.dart';
|
import 'package:workout_app/services/pc_pairing.dart';
|
||||||
import 'package:workout_app/services/progression_sync_service.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_upload_credentials.dart';
|
||||||
import 'package:workout_app/services/run_uploader.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/runnerup_importer.dart';
|
||||||
import 'package:workout_app/services/shared_storage.dart';
|
import 'package:workout_app/services/shared_storage.dart';
|
||||||
import 'package:workout_app/services/storage_service.dart';
|
import 'package:workout_app/services/storage_service.dart';
|
||||||
import 'package:workout_app/services/sync_device_id.dart';
|
import 'package:workout_app/services/sync_device_id.dart';
|
||||||
import 'package:workout_app/services/sync_service.dart';
|
import 'package:workout_app/services/sync_service.dart';
|
||||||
import 'package:workout_app/ui/theme.dart';
|
import 'package:workout_app/ui/theme.dart';
|
||||||
|
import 'package:workout_app/widgets/run_landing.dart';
|
||||||
|
|
||||||
// coverage:ignore-start
|
// coverage:ignore-start
|
||||||
// App bootstrap: permission request, DB init, and a real listening socket —
|
// App bootstrap: permission request, DB init, and a real listening socket —
|
||||||
@ -101,12 +106,14 @@ void main(List<String> args) async {
|
|||||||
// still pending from an earlier launch.
|
// still pending from an earlier launch.
|
||||||
if (!Sandbox.enabled) await RunCredentialStore().importProvisionFile();
|
if (!Sandbox.enabled) await RunCredentialStore().importProvisionFile();
|
||||||
unawaited(RunUploader.instance.uploadPending());
|
unawaited(RunUploader.instance.uploadPending());
|
||||||
|
installRunWiring();
|
||||||
// Before the UI exists: a service left over from a crashed or force-stopped
|
// 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.
|
// workout must not sit in the status bar counting down nothing.
|
||||||
await stopStaleBreakService(
|
await stopStaleBreakService(
|
||||||
FlutterForegroundBreakClient(),
|
FlutterForegroundBreakClient(),
|
||||||
hasActiveWorkout: () async =>
|
hasActiveWorkout: () async =>
|
||||||
await StorageService.instance.loadActiveSession() != null,
|
await StorageService.instance.loadActiveSession() != null,
|
||||||
|
runIsOwed: runIsOwed, // the service may be hosting a run
|
||||||
);
|
);
|
||||||
await StorageService.instance.restoreFromBackupIfNeeded();
|
await StorageService.instance.restoreFromBackupIfNeeded();
|
||||||
// The permission-free restore path, and the reason storage is now optional.
|
// The permission-free restore path, and the reason storage is now optional.
|
||||||
@ -147,7 +154,13 @@ void main(List<String> args) async {
|
|||||||
localDir: sharedPathFor(Sandbox.packageName, kRunnerUpLocalDir),
|
localDir: sharedPathFor(Sandbox.packageName, kRunnerUpLocalDir),
|
||||||
).runGuarded(),
|
).runGuarded(),
|
||||||
);
|
);
|
||||||
runApp(const WorkoutApp());
|
final resumeRun =
|
||||||
|
Platform.isAndroid &&
|
||||||
|
await resumeRunOnLaunch(
|
||||||
|
owed: runIsOwed,
|
||||||
|
client: FlutterForegroundRunClient(),
|
||||||
|
);
|
||||||
|
runApp(WorkoutApp(resumeRun: resumeRun));
|
||||||
}
|
}
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
|
|
||||||
@ -157,8 +170,11 @@ void main(List<String> args) async {
|
|||||||
/// listening socket while the app is backgrounded, so the process (and its
|
/// listening socket while the app is backgrounded, so the process (and its
|
||||||
/// open socket) doesn't sit alive indefinitely and block Doze/App-Standby.
|
/// open socket) doesn't sit alive indefinitely and block Doze/App-Standby.
|
||||||
class WorkoutApp extends StatefulWidget {
|
class WorkoutApp extends StatefulWidget {
|
||||||
/// Creates the root app widget.
|
/// Creates the root app widget; [resumeRun] opens the live run screen.
|
||||||
const WorkoutApp({super.key});
|
const WorkoutApp({super.key, this.resumeRun = false});
|
||||||
|
|
||||||
|
/// A run is in progress: land on it, whatever launched the app.
|
||||||
|
final bool resumeRun;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<WorkoutApp> createState() => _WorkoutAppState();
|
State<WorkoutApp> createState() => _WorkoutAppState();
|
||||||
@ -214,7 +230,10 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
|
|||||||
fw.DefaultMaterialLocalizations.delegate,
|
fw.DefaultMaterialLocalizations.delegate,
|
||||||
DefaultWidgetsLocalizations.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
|
// 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.
|
// ribbon on every screen, in the error colour, on the sandbox only.
|
||||||
builder: (context, child) => Sandbox.enabled
|
builder: (context, child) => Sandbox.enabled
|
||||||
|
|||||||
@ -37,8 +37,12 @@ class HomeScreen extends StatefulWidget {
|
|||||||
this.clock,
|
this.clock,
|
||||||
this.configuredProbe,
|
this.configuredProbe,
|
||||||
this.openWorkoutOnLaunch = true,
|
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].
|
/// Sync service to use; defaults to a real [WorkoutSyncService].
|
||||||
final WorkoutSyncService? syncService;
|
final WorkoutSyncService? syncService;
|
||||||
|
|
||||||
@ -97,6 +101,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
lastDate.day == today.day;
|
lastDate.day == today.day;
|
||||||
final firstLoad = !_hasAutoOpened;
|
final firstLoad = !_hasAutoOpened;
|
||||||
_hasAutoOpened = true;
|
_hasAutoOpened = true;
|
||||||
|
final resumeRun = firstLoad && widget.openRunOnLaunch;
|
||||||
final launch = await _decideLaunch(
|
final launch = await _decideLaunch(
|
||||||
firstLoad: firstLoad,
|
firstLoad: firstLoad,
|
||||||
hasSaved: saved != null,
|
hasSaved: saved != null,
|
||||||
@ -122,7 +127,11 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
// changes what the card says when it lands.
|
// changes what the card says when it lands.
|
||||||
unawaited(_refreshSyncStatus());
|
unawaited(_refreshSyncStatus());
|
||||||
|
|
||||||
if (launch.open) {
|
if (resumeRun) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (mounted) unawaited(_openRun(resuming: true));
|
||||||
|
});
|
||||||
|
} else if (launch.open) {
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
unawaited(
|
unawaited(
|
||||||
|
|||||||
@ -40,7 +40,9 @@ extension _HomeScreenLaunch on _HomeScreenState {
|
|||||||
required DateTime today,
|
required DateTime today,
|
||||||
}) async {
|
}) async {
|
||||||
const stay = (open: false, syncedToday: false, syncNotSetUp: false);
|
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 (!firstLoad || !widget.openWorkoutOnLaunch) return stay;
|
||||||
|
if (widget.openRunOnLaunch) return stay;
|
||||||
final wantsFresh = !hasSaved && !doneLocally && !lockModeEnabled;
|
final wantsFresh = !hasSaved && !doneLocally && !lockModeEnabled;
|
||||||
if (!hasSaved && !wantsFresh) return stay;
|
if (!hasSaved && !wantsFresh) return stay;
|
||||||
|
|
||||||
|
|||||||
@ -16,11 +16,11 @@ extension _HomeScreenNavigation on _HomeScreenState {
|
|||||||
|
|
||||||
/// Pushes the GPS run screen, then reloads (a finished run can change
|
/// Pushes the GPS run screen, then reloads (a finished run can change
|
||||||
/// today's credit once the PC has it).
|
/// today's credit once the PC has it).
|
||||||
Future<void> _openRun() async {
|
Future<void> _openRun({bool resuming = false}) async {
|
||||||
SandboxLog.event('open run screen');
|
SandboxLog.event('open run screen', {'resuming': resuming});
|
||||||
await Navigator.of(
|
await Navigator.of(context).push(
|
||||||
context,
|
MaterialPageRoute<void>(builder: (_) => RunScreen(resuming: resuming)),
|
||||||
).push(MaterialPageRoute<void>(builder: (_) => const RunScreen()));
|
);
|
||||||
unawaited(_load());
|
unawaited(_load());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -8,46 +8,30 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:audioplayers/audioplayers.dart';
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:latlong2/latlong.dart';
|
import 'package:latlong2/latlong.dart';
|
||||||
import 'package:material_ui/material_ui.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:permission_handler/permission_handler.dart';
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
import 'package:workout_app/models/run_track.dart';
|
import 'package:workout_app/models/run_track.dart';
|
||||||
import 'package:workout_app/sandbox/sandbox_log.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.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_band.dart';
|
||||||
import 'package:workout_app/services/pace_target_store.dart';
|
import 'package:workout_app/services/pace_target_store.dart';
|
||||||
import 'package:workout_app/services/run_controller.dart';
|
import 'package:workout_app/services/run_controller.dart';
|
||||||
import 'package:workout_app/services/run_format.dart';
|
import 'package:workout_app/services/run_format.dart';
|
||||||
import 'package:workout_app/services/run_recorder.dart';
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
import 'package:workout_app/services/run_saver.dart';
|
|
||||||
import 'package:workout_app/services/run_uploader.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/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_map_slot.dart';
|
||||||
import 'package:workout_app/widgets/run_pace_picker.dart';
|
import 'package:workout_app/widgets/run_pace_picker.dart';
|
||||||
import 'package:workout_app/widgets/run_upload_badge.dart';
|
import 'package:workout_app/widgets/run_upload_badge.dart';
|
||||||
|
|
||||||
part 'run_screen_numbers.dart';
|
part 'run_screen_numbers.dart';
|
||||||
part 'run_screen_parts.dart';
|
part 'run_screen_parts.dart';
|
||||||
|
part 'run_screen_pulse.dart';
|
||||||
/// The controller the app uses: real GPS (or the sandbox replay), the real
|
part 'run_screen_state.dart';
|
||||||
/// 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,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Builds the live map from the run's accepted points and the user's current
|
/// Builds the live map from the run's accepted points and the user's current
|
||||||
/// position (shown until the run has points).
|
/// position (shown until the run has points).
|
||||||
@ -59,19 +43,29 @@ typedef RunMapBuilder =
|
|||||||
);
|
);
|
||||||
|
|
||||||
/// Records one GPS activity (always a run).
|
/// 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 {
|
class RunScreen extends StatefulWidget {
|
||||||
/// Creates the screen; every argument is a test or map seam.
|
/// Creates the screen; every argument is a test or map seam.
|
||||||
const RunScreen({
|
const RunScreen({
|
||||||
super.key,
|
super.key,
|
||||||
this.controllerFactory = buildRunController,
|
this.controllerFactory,
|
||||||
this.uploader,
|
this.uploader,
|
||||||
this.paceStore,
|
this.paceStore,
|
||||||
this.mapBuilder,
|
this.mapBuilder,
|
||||||
this.openSettings = openAppSettings,
|
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").
|
/// 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.
|
/// The upload queue shown in the badge; defaults to the app-wide one.
|
||||||
final RunUploader? uploader;
|
final RunUploader? uploader;
|
||||||
@ -85,147 +79,14 @@ class RunScreen extends StatefulWidget {
|
|||||||
/// Opens the system settings page for this app.
|
/// Opens the system settings page for this app.
|
||||||
final Future<bool> Function() openSettings;
|
final Future<bool> 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
|
@override
|
||||||
State<RunScreen> createState() => _RunScreenState();
|
State<RunScreen> createState() => _RunScreenState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _RunScreenState extends State<RunScreen> 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<void> _loadPaceTarget() async {
|
|
||||||
final stored = await _paceStore.load();
|
|
||||||
if (mounted) setState(() => _paceTarget = stored);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _setPaceTarget(int seconds) {
|
|
||||||
setState(() => _paceTarget = seconds);
|
|
||||||
unawaited(_paceStore.save(seconds));
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _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(
|
Widget _defaultMap(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
ValueListenable<List<RunPoint>> points,
|
ValueListenable<List<RunPoint>> points,
|
||||||
|
|||||||
@ -3,15 +3,15 @@
|
|||||||
part of 'run_screen.dart';
|
part of 'run_screen.dart';
|
||||||
|
|
||||||
class _Numbers extends StatelessWidget {
|
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.
|
/// Green on pace, red off it, plain while there is no verdict yet.
|
||||||
Color _paceColour(BuildContext context) {
|
Color _paceColour(BuildContext context) {
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
final colors = Theme.of(context).extension<AppStatusColors>()!;
|
final colors = Theme.of(context).extension<AppStatusColors>()!;
|
||||||
final band = recorder.coach.band;
|
final band = view.band;
|
||||||
if (band == null) return scheme.onSurface;
|
if (band == null) return scheme.onSurface;
|
||||||
return band == PaceBand.onPace ? colors.success : scheme.error;
|
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(
|
return Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
Flexible(
|
Flexible(
|
||||||
child: big(
|
child: big(
|
||||||
const Key('run_time'),
|
const Key('run_time'),
|
||||||
formatDuration(recorder.seconds),
|
formatDuration(view.seconds),
|
||||||
96,
|
96,
|
||||||
scheme.onSurface,
|
scheme.onSurface,
|
||||||
),
|
),
|
||||||
@ -62,17 +62,17 @@ class _Numbers extends StatelessWidget {
|
|||||||
small(
|
small(
|
||||||
Icons.straighten,
|
Icons.straighten,
|
||||||
const Key('run_distance'),
|
const Key('run_distance'),
|
||||||
formatDistanceKm(recorder.distanceM),
|
formatDistanceKm(view.distanceM),
|
||||||
),
|
),
|
||||||
small(
|
small(
|
||||||
Icons.speed,
|
Icons.speed,
|
||||||
const Key('run_pace'),
|
const Key('run_pace'),
|
||||||
formatPace(
|
formatPace(
|
||||||
seconds: recorder.seconds,
|
seconds: view.seconds,
|
||||||
distanceM: recorder.distanceM,
|
distanceM: view.distanceM,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (recorder.coach.target != null)
|
if (view.paceTarget != null)
|
||||||
small(
|
small(
|
||||||
Icons.bolt,
|
Icons.bolt,
|
||||||
const Key('run_pace_now'),
|
const Key('run_pace_now'),
|
||||||
|
|||||||
@ -115,6 +115,7 @@ class _Controls extends StatelessWidget {
|
|||||||
required this.onPaceToggle,
|
required this.onPaceToggle,
|
||||||
required this.onPaceChanged,
|
required this.onPaceChanged,
|
||||||
required this.onStart,
|
required this.onStart,
|
||||||
|
required this.onFinish,
|
||||||
required this.onAgain,
|
required this.onAgain,
|
||||||
required this.onClose,
|
required this.onClose,
|
||||||
});
|
});
|
||||||
@ -126,12 +127,13 @@ class _Controls extends StatelessWidget {
|
|||||||
final VoidCallback onPaceToggle;
|
final VoidCallback onPaceToggle;
|
||||||
final ValueChanged<int> onPaceChanged;
|
final ValueChanged<int> onPaceChanged;
|
||||||
final VoidCallback onStart;
|
final VoidCallback onStart;
|
||||||
|
final VoidCallback onFinish;
|
||||||
final VoidCallback onAgain;
|
final VoidCallback onAgain;
|
||||||
final VoidCallback onClose;
|
final VoidCallback onClose;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final recorder = controller.recorder;
|
final view = controller.view;
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
Widget button(
|
Widget button(
|
||||||
String id,
|
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 => [
|
RunPhase.idle => [
|
||||||
Flexible(
|
Flexible(
|
||||||
child: RunPacePicker(
|
child: RunPacePicker(
|
||||||
@ -170,21 +178,11 @@ class _Controls extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
RunPhase.recording => [
|
RunPhase.recording => [
|
||||||
button('pause', Icons.pause, controller.pause),
|
button('pause', Icons.pause, controller.pause),
|
||||||
button(
|
finish,
|
||||||
'finish',
|
|
||||||
Icons.stop,
|
|
||||||
() => unawaited(controller.finish()),
|
|
||||||
tint: scheme.error,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
RunPhase.paused => [
|
RunPhase.paused => [
|
||||||
button('resume', Icons.play_arrow, controller.resume),
|
button('resume', Icons.play_arrow, controller.resume),
|
||||||
button(
|
finish,
|
||||||
'finish',
|
|
||||||
Icons.stop,
|
|
||||||
() => unawaited(controller.finish()),
|
|
||||||
tint: scheme.error,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
RunPhase.finished => [
|
RunPhase.finished => [
|
||||||
button('again', Icons.refresh, controller.saving ? null : onAgain),
|
button('again', Icons.refresh, controller.saving ? null : onAgain),
|
||||||
|
|||||||
@ -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,
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -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<RunScreen> 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<void> _loadPaceTarget() async {
|
||||||
|
final stored = await _paceStore.load();
|
||||||
|
if (mounted) setState(() => _paceTarget = stored);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _setPaceTarget(int seconds) {
|
||||||
|
setState(() => _paceTarget = seconds);
|
||||||
|
unawaited(_paceStore.save(seconds));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _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<void> _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(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -20,8 +20,12 @@ import 'package:workout_app/services/foreground_break_client.dart';
|
|||||||
Future<bool> stopStaleBreakService(
|
Future<bool> stopStaleBreakService(
|
||||||
ForegroundBreakClient client, {
|
ForegroundBreakClient client, {
|
||||||
required Future<bool> Function() hasActiveWorkout,
|
required Future<bool> Function() hasActiveWorkout,
|
||||||
|
required Future<bool> Function() runIsOwed,
|
||||||
}) async {
|
}) async {
|
||||||
if (!client.isSupported) return false;
|
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 client.isRunning()) return false;
|
||||||
if (await hasActiveWorkout()) return false;
|
if (await hasActiveWorkout()) return false;
|
||||||
log(
|
log(
|
||||||
|
|||||||
@ -109,4 +109,29 @@ class FeedbackCues {
|
|||||||
debugPrint('WorkoutApp: pace tone failed to play ($error).');
|
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<void> 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<void> autoEnded() => _longCue('cue run auto-ended');
|
||||||
|
|
||||||
|
Future<void> _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).');
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
/// The real foreground-service client, and the service's entry point.
|
/// The real foreground-service client, and the service's entry point.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'dart:developer';
|
||||||
import 'dart:io' show Platform;
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
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_service_port_flutter.dart';
|
||||||
import 'package:workout_app/services/break_task_handler.dart';
|
import 'package:workout_app/services/break_task_handler.dart';
|
||||||
import 'package:workout_app/services/foreground_break_client.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.
|
/// 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
|
@override
|
||||||
Future<bool> isRunning() => FlutterForegroundTask.isRunningService;
|
Future<bool> isRunning() async =>
|
||||||
|
!await runIsOwed() && await FlutterForegroundTask.isRunningService;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<bool> hasNotificationPermission() async =>
|
Future<bool> hasNotificationPermission() async =>
|
||||||
@ -128,6 +135,14 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Future<bool> start(BreakSnapshot snapshot) async {
|
Future<bool> 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) {
|
if (await FlutterForegroundTask.isRunningService) {
|
||||||
await FlutterForegroundTask.stopService();
|
await FlutterForegroundTask.stopService();
|
||||||
}
|
}
|
||||||
@ -154,6 +169,7 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> stop() async {
|
Future<void> stop() async {
|
||||||
|
if (await runIsOwed()) return;
|
||||||
if (await FlutterForegroundTask.isRunningService) {
|
if (await FlutterForegroundTask.isRunningService) {
|
||||||
await FlutterForegroundTask.stopService();
|
await FlutterForegroundTask.stopService();
|
||||||
}
|
}
|
||||||
@ -174,7 +190,10 @@ class FlutterForegroundBreakClient implements ForegroundBreakClient {
|
|||||||
|
|
||||||
/// The service's nudge carries no payload -- see [BreakServicePort]. Any
|
/// The service's nudge carries no payload -- see [BreakServicePort]. Any
|
||||||
/// message from the task isolate means "the queue has something in it".
|
/// 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
|
// coverage:ignore-end
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
import 'dart:io' show Platform;
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
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/break_notification_text.dart';
|
||||||
import 'package:workout_app/services/foreground_run_client.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.
|
/// 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.
|
/// shows it in system settings.
|
||||||
const kRunOngoingChannelId = 'run_ongoing_v1';
|
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<void> onStart(DateTime timestamp, TaskStarter starter) async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void onRepeatEvent(DateTime timestamp) {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void onNotificationPressed() => FlutterForegroundTask.launchApp();
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {}
|
|
||||||
}
|
|
||||||
// coverage:ignore-end
|
|
||||||
|
|
||||||
/// The real [ForegroundRunClient], driving `flutter_foreground_task`.
|
/// The real [ForegroundRunClient], driving `flutter_foreground_task`.
|
||||||
class FlutterForegroundRunClient implements ForegroundRunClient {
|
class FlutterForegroundRunClient implements ForegroundRunClient {
|
||||||
/// Creates a client. Cheap: nothing happens until [start].
|
/// 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
|
// Platform-channel passthroughs. `flutter test` runs on Linux, where
|
||||||
// isSupported is false and none of this is reachable; the decisions that
|
// 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
|
// coverage:ignore-start
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -64,12 +45,16 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
|
|||||||
await FlutterForegroundTask.requestNotificationPermission() ==
|
await FlutterForegroundTask.requestNotificationPermission() ==
|
||||||
NotificationPermission.granted;
|
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
|
@override
|
||||||
Future<bool> start({
|
Future<bool> start({
|
||||||
required bool withLocation,
|
required bool withLocation,
|
||||||
required String title,
|
required String title,
|
||||||
required String text,
|
required String text,
|
||||||
}) async {
|
}) async {
|
||||||
|
if (await FlutterForegroundTask.isRunningService) return true;
|
||||||
|
await _saveFlags();
|
||||||
FlutterForegroundTask.init(
|
FlutterForegroundTask.init(
|
||||||
androidNotificationOptions: AndroidNotificationOptions(
|
androidNotificationOptions: AndroidNotificationOptions(
|
||||||
channelId: kRunOngoingChannelId,
|
channelId: kRunOngoingChannelId,
|
||||||
@ -80,18 +65,17 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
|
|||||||
iosNotificationOptions: const IOSNotificationOptions(),
|
iosNotificationOptions: const IOSNotificationOptions(),
|
||||||
foregroundTaskOptions: ForegroundTaskOptions(
|
foregroundTaskOptions: ForegroundTaskOptions(
|
||||||
eventAction: ForegroundTaskEventAction.nothing(),
|
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
|
// allowWakeLock stays at its default (true): it is why GPS fixes keep
|
||||||
// arriving with the screen off.
|
// arriving with the screen off.
|
||||||
|
autoRunOnBoot: true,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (await FlutterForegroundTask.isRunningService) {
|
|
||||||
await FlutterForegroundTask.stopService();
|
|
||||||
}
|
|
||||||
final result = await FlutterForegroundTask.startService(
|
final result = await FlutterForegroundTask.startService(
|
||||||
serviceTypes: [
|
// `location` alone: Android 15 refuses a dataSync service from the boot
|
||||||
ForegroundServiceTypes.dataSync,
|
// broadcast, and dataSync has a 6 h budget a long run can exhaust.
|
||||||
if (withLocation) ForegroundServiceTypes.location,
|
serviceTypes: [ForegroundServiceTypes.location],
|
||||||
],
|
|
||||||
notificationTitle: title,
|
notificationTitle: title,
|
||||||
notificationText: text,
|
notificationText: text,
|
||||||
callback: runServiceStartCallback,
|
callback: runServiceStartCallback,
|
||||||
@ -99,6 +83,21 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
|
|||||||
return result is ServiceRequestSuccess;
|
return result is ServiceRequestSuccess;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _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
|
@override
|
||||||
Future<void> update({required String title, required String text}) async {
|
Future<void> update({required String title, required String text}) async {
|
||||||
await FlutterForegroundTask.updateService(
|
await FlutterForegroundTask.updateService(
|
||||||
@ -116,3 +115,34 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
|
|||||||
|
|
||||||
// coverage:ignore-end
|
// 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<Map<Object?, Object?>>.broadcast();
|
||||||
|
|
||||||
|
void _onData(Object data) {
|
||||||
|
// The break service shares this channel; only run messages pass.
|
||||||
|
if (isRunMessage(data)) _out.add(data as Map<Object?, Object?>);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Map<Object?, Object?>> get messages => _out.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void send(Map<String, Object?> command) =>
|
||||||
|
FlutterForegroundTask.sendDataToTask(command);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close() async {
|
||||||
|
FlutterForegroundTask.removeTaskDataCallback(_onData);
|
||||||
|
await _out.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// coverage:ignore-end
|
||||||
|
|||||||
@ -0,0 +1,24 @@
|
|||||||
|
// coverage:ignore-file
|
||||||
|
// A path_provider lookup only the phone can answer; the logic around it is
|
||||||
|
// tested against in-memory stores.
|
||||||
|
/// Where the active run's checkpoint lives on disk, for every isolate.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:path_provider/path_provider.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint_store.dart';
|
||||||
|
|
||||||
|
/// Opens the one checkpoint file of the app (shared by the UI isolate, the
|
||||||
|
/// service isolate and the boot path).
|
||||||
|
Future<RunCheckpointStore> openRunCheckpointStore() async {
|
||||||
|
final dir = await getApplicationSupportDirectory();
|
||||||
|
return FileRunCheckpointStore(File(p.join(dir.path, 'run_checkpoint.json')));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a run is owed: its checkpoint is on disk. While true the shared
|
||||||
|
/// foreground service belongs to the run, and nothing else may stop or
|
||||||
|
/// replace it.
|
||||||
|
Future<bool> runIsOwed() async =>
|
||||||
|
await (await openRunCheckpointStore()).load() != null;
|
||||||
@ -1,5 +1,9 @@
|
|||||||
/// Wires one recording to the phone: permission, foreground service, cues,
|
/// The run screen's side of a recording: location access, the foreground
|
||||||
/// notification and the save at the end.
|
/// service, the link to the host that holds the run, and the view of it.
|
||||||
|
///
|
||||||
|
/// The recording itself (GPS stream, numbers, checkpoint, cues, the save)
|
||||||
|
/// lives in the host. This controller can be disposed, replaced or killed at
|
||||||
|
/// any moment without touching the run: [dispose] only hangs up.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
@ -7,74 +11,87 @@ import 'dart:developer';
|
|||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:latlong2/latlong.dart';
|
import 'package:latlong2/latlong.dart';
|
||||||
import 'package:workout_app/models/run_track.dart';
|
|
||||||
import 'package:workout_app/sandbox/sandbox.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.dart';
|
||||||
import 'package:workout_app/services/idle_location.dart';
|
import 'package:workout_app/services/idle_location.dart';
|
||||||
import 'package:workout_app/services/pace_band.dart';
|
|
||||||
import 'package:workout_app/services/position_source.dart';
|
import 'package:workout_app/services/position_source.dart';
|
||||||
|
import 'package:workout_app/services/run_link.dart';
|
||||||
import 'package:workout_app/services/run_notification.dart';
|
import 'package:workout_app/services/run_notification.dart';
|
||||||
import 'package:workout_app/services/run_recorder.dart';
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
import 'package:workout_app/services/run_saver.dart';
|
import 'package:workout_app/services/run_saver.dart';
|
||||||
|
import 'package:workout_app/services/run_view.dart';
|
||||||
|
import 'package:workout_app/services/run_wire.dart';
|
||||||
|
|
||||||
/// Owns a [RunRecorder] and everything that must happen around it.
|
/// How long a command may wait for the host's answer before the screen stops
|
||||||
|
/// waiting (and says so in the log).
|
||||||
|
const kRunHostTimeout = Duration(seconds: 20);
|
||||||
|
|
||||||
|
/// Owns the [RunView] and everything the UI must do around a recording.
|
||||||
///
|
///
|
||||||
/// Order matters at the start: location access first (the recorder asks), then
|
/// Order matters at the start: location access first, then the foreground
|
||||||
/// the foreground service (Android 14 refuses a `location` service without
|
/// service (Android 14 refuses a `location` service without the permission),
|
||||||
/// the permission), then the first fix.
|
/// then the host's first fix.
|
||||||
class RunController extends ChangeNotifier {
|
class RunController extends ChangeNotifier {
|
||||||
/// Creates a controller; it builds its own [recorder] over [sourceFor].
|
/// Creates a controller over [link]; [idleSourceFor] feeds the idle map.
|
||||||
///
|
|
||||||
/// [idleSourceFor] feeds the idle map before the run (display only); it
|
|
||||||
/// defaults to [sourceFor].
|
|
||||||
RunController({
|
RunController({
|
||||||
required PositionSource Function() sourceFor,
|
required PositionSource Function() idleSourceFor,
|
||||||
required this._service,
|
required this._service,
|
||||||
required this._cues,
|
required this._link,
|
||||||
required this._save,
|
required this._soundOn,
|
||||||
PositionSource Function()? idleSourceFor,
|
this.hostTimeout = kRunHostTimeout,
|
||||||
|
this.retryEvery = const Duration(milliseconds: 750),
|
||||||
}) {
|
}) {
|
||||||
recorder = RunRecorder(
|
_idle = IdleLocation(idleSourceFor(), onAccess: _onAccess);
|
||||||
sourceFor: sourceFor,
|
view.addListener(notifyListeners);
|
||||||
onKilometre: _onKilometre,
|
view.onNeedSync = _hello;
|
||||||
onPaceCue: _onPaceCue,
|
_sub = _link.messages.listen(_onMessage);
|
||||||
)..addListener(_onRecorderChanged);
|
|
||||||
_idle = IdleLocation((idleSourceFor ?? sourceFor)(), onAccess: _onAccess);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The state machine; the live map reads its points.
|
/// What the screen shows.
|
||||||
late final RunRecorder recorder;
|
final view = RunView();
|
||||||
|
|
||||||
|
/// How long to wait for the host.
|
||||||
|
final Duration hostTimeout;
|
||||||
|
|
||||||
|
/// How often [attach] asks again while the host is silent.
|
||||||
|
final Duration retryEvery;
|
||||||
|
|
||||||
late final IdleLocation _idle;
|
late final IdleLocation _idle;
|
||||||
final ForegroundRunClient _service;
|
final ForegroundRunClient _service;
|
||||||
final FeedbackCues _cues;
|
final RunLink _link;
|
||||||
final Future<RunSaveResult> Function(RunTrack track) _save;
|
final Future<bool> Function() _soundOn;
|
||||||
|
late final StreamSubscription<Map<Object?, Object?>> _sub;
|
||||||
|
|
||||||
RunServiceState _serviceState = RunServiceState.none;
|
RunServiceState _serviceState = RunServiceState.none;
|
||||||
RunSaveResult? _saved;
|
bool _disposed = false;
|
||||||
bool _saving = false;
|
bool _attachGaveUp = false;
|
||||||
String _lastCopy = '';
|
|
||||||
|
/// The host never answered the screen's questions: nothing is there.
|
||||||
|
bool get attachGaveUp => _attachGaveUp;
|
||||||
|
|
||||||
/// Whether the foreground service is up (and with a notification).
|
/// Whether the foreground service is up (and with a notification).
|
||||||
RunServiceState get serviceState => _serviceState;
|
RunServiceState get serviceState => _serviceState;
|
||||||
|
|
||||||
/// What saving the finished run did, once it ran.
|
/// What saving the finished run did, once it ran.
|
||||||
RunSaveResult? get saved => _saved;
|
RunSaveResult? get saved => view.saved == null
|
||||||
|
? null
|
||||||
|
: RunSaveResult(
|
||||||
|
stored: view.saved!.stored,
|
||||||
|
reason: view.saved!.reason,
|
||||||
|
);
|
||||||
|
|
||||||
/// True while the finished run is being written.
|
/// True while the finished run is being written.
|
||||||
bool get saving => _saving;
|
bool get saving =>
|
||||||
|
view.saving || (view.phase == RunPhase.finished && !view.done);
|
||||||
|
|
||||||
/// True from start to finish: the screen must not be left meanwhile.
|
/// True from start to finish: the screen must not be left meanwhile.
|
||||||
bool get active => recorder.phase.isActive;
|
bool get active => view.phase.isActive;
|
||||||
|
|
||||||
/// Where the user is before the run starts (display only, never recorded).
|
/// Where the user is before the run starts (display only, never recorded).
|
||||||
ValueListenable<LatLng?> get position => _idle.position;
|
ValueListenable<LatLng?> get position => _idle.position;
|
||||||
|
|
||||||
/// True while location is refused and the run has not started: the screen
|
/// True while location is refused and the run has not started: the screen
|
||||||
/// shows only the problem icon, no map and no start.
|
/// shows only the problem icon, no map and no start.
|
||||||
bool get blocked =>
|
bool get blocked => view.phase == RunPhase.idle && view.issue.isAccess;
|
||||||
recorder.phase == RunPhase.idle && recorder.issue.isAccess;
|
|
||||||
|
|
||||||
/// Whether access has been found granted, so a start cannot race a prompt.
|
/// Whether access has been found granted, so a start cannot race a prompt.
|
||||||
bool get canStart => _idle.access?.isGranted ?? false;
|
bool get canStart => _idle.access?.isGranted ?? false;
|
||||||
@ -85,45 +102,98 @@ class RunController extends ChangeNotifier {
|
|||||||
|
|
||||||
/// Re-reads the access silently (the app came back to the foreground).
|
/// Re-reads the access silently (the app came back to the foreground).
|
||||||
Future<void> recheckAccess() =>
|
Future<void> recheckAccess() =>
|
||||||
recorder.phase == RunPhase.idle ? _idle.recheck() : Future.value();
|
view.phase == RunPhase.idle ? _idle.recheck() : Future.value();
|
||||||
|
|
||||||
/// Asks for access, starts the service, begins recording.
|
/// Asks the host where the run stands (and keeps asking until it answers:
|
||||||
Future<void> start() async {
|
/// a restarted service needs a moment to come up).
|
||||||
|
Future<void> attach() async {
|
||||||
|
for (var i = 0; i < 8 && !view.synced && !_disposed; i++) {
|
||||||
|
_hello();
|
||||||
|
await Future<void>.delayed(i == 0 ? Duration.zero : retryEvery);
|
||||||
|
}
|
||||||
|
if (!view.synced && !_disposed) {
|
||||||
|
_attachGaveUp = true;
|
||||||
|
_serviceState = RunServiceState.none;
|
||||||
|
} else if (view.phase.isActive && !_serviceState.isUp) {
|
||||||
|
_serviceState = RunServiceState.running;
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks for access, starts the service, begins recording. A run that is
|
||||||
|
/// already going is never restarted.
|
||||||
|
Future<void> start({int? paceTarget}) async {
|
||||||
|
if (view.phase.isActive) return;
|
||||||
await _idle.stop();
|
await _idle.stop();
|
||||||
await _cues.load();
|
await _startService();
|
||||||
final started = await recorder.start(afterAccess: _startService);
|
await attach();
|
||||||
|
_link.send({
|
||||||
|
'cmd': RunCmd.start,
|
||||||
|
'paceTarget': paceTarget,
|
||||||
|
'sound': await _soundOn(),
|
||||||
|
});
|
||||||
|
await _until(() => view.phase.isActive || view.issue != RunIssue.none);
|
||||||
// A refused start leaves the screen blocked; let a resume recheck it.
|
// A refused start leaves the screen blocked; let a resume recheck it.
|
||||||
if (!started && recorder.issue.isAccess) _idle.reopen();
|
if (!view.phase.isActive && view.issue.isAccess) _idle.reopen();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pauses crediting.
|
/// Pauses crediting.
|
||||||
void pause() => recorder.pause();
|
void pause() => _link.send({'cmd': RunCmd.pause});
|
||||||
|
|
||||||
/// Resumes crediting.
|
/// Resumes crediting.
|
||||||
void resume() => recorder.resume();
|
void resume() => _link.send({'cmd': RunCmd.resume});
|
||||||
|
|
||||||
/// Ends the run, stops the service and saves the track.
|
/// Changes the pace target of a running recording.
|
||||||
|
void setPaceTarget(int? seconds) =>
|
||||||
|
_link.send({'cmd': RunCmd.paceTarget, 'paceTarget': seconds});
|
||||||
|
|
||||||
|
/// Tells the host the finish modal the notification asked for is showing.
|
||||||
|
void ackPrompt() => _link.send({'cmd': RunCmd.ackPrompt});
|
||||||
|
|
||||||
|
/// Ends the run and waits until the host has saved it. Only the screen's
|
||||||
|
/// confirm modal calls this.
|
||||||
Future<void> finish() async {
|
Future<void> finish() async {
|
||||||
final track = await recorder.finish();
|
_link.send({'cmd': RunCmd.finish});
|
||||||
await _stopService();
|
await _until(
|
||||||
if (track == null) return;
|
() => view.phase == RunPhase.finished && view.done,
|
||||||
unawaited(_cues.workoutFinished());
|
);
|
||||||
_saving = true;
|
if (view.phase == RunPhase.finished) {
|
||||||
notifyListeners();
|
_serviceState = RunServiceState.none;
|
||||||
try {
|
notifyListeners();
|
||||||
_saved = await _save(track);
|
}
|
||||||
} on Exception catch (error, stack) {
|
}
|
||||||
log(
|
|
||||||
'RunController: saving ${track.id} failed ($error) -- the run is '
|
void _hello() => _link.send({'cmd': RunCmd.hello});
|
||||||
'lost unless it is recorded again.',
|
|
||||||
level: 1000,
|
void _onMessage(Map<Object?, Object?> message) {
|
||||||
error: error,
|
if (!isRunMessage(message)) return;
|
||||||
stackTrace: stack,
|
view.apply(message);
|
||||||
);
|
if (view.phase.isActive && !_serviceState.isUp) {
|
||||||
_saved = RunSaveResult(stored: false, reason: 'save failed: $error');
|
_serviceState = RunServiceState.running;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _until(bool Function() done) async {
|
||||||
|
if (done()) return;
|
||||||
|
final completer = Completer<void>();
|
||||||
|
void check() {
|
||||||
|
if (done() && !completer.isCompleted) completer.complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
view.addListener(check);
|
||||||
|
try {
|
||||||
|
await completer.future.timeout(hostTimeout);
|
||||||
|
} on TimeoutException {
|
||||||
|
log(
|
||||||
|
'RunController: the run host did not answer within '
|
||||||
|
'${hostTimeout.inSeconds}s (phase ${view.phase.name}, issue '
|
||||||
|
'${view.issue.name}). The run itself is not touched; reopen the '
|
||||||
|
'screen to ask again.',
|
||||||
|
level: 1000,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
view.removeListener(check);
|
||||||
}
|
}
|
||||||
_saving = false;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _startService() async {
|
Future<void> _startService() async {
|
||||||
@ -141,9 +211,8 @@ class RunController extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
final copy = runNotificationCopy(metres: 0, movingSeconds: 0);
|
final copy = runNotificationCopy(metres: 0, movingSeconds: 0);
|
||||||
_lastCopy = '${copy.title}|${copy.body}';
|
|
||||||
final started = await _service.start(
|
final started = await _service.start(
|
||||||
withLocation: !Sandbox.enabled,
|
withLocation: true,
|
||||||
title: copy.title,
|
title: copy.title,
|
||||||
text: copy.body,
|
text: copy.body,
|
||||||
);
|
);
|
||||||
@ -161,47 +230,22 @@ class RunController extends ChangeNotifier {
|
|||||||
: RunServiceState.runningHidden;
|
: RunServiceState.runningHidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _stopService() async {
|
|
||||||
if (!_serviceState.isUp) return;
|
|
||||||
await _service.stop();
|
|
||||||
_serviceState = RunServiceState.none;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _onKilometre(int km) => unawaited(_cues.kilometreReached(km));
|
|
||||||
|
|
||||||
void _onPaceCue(PaceCue cue) => unawaited(_cues.paceOff(cue));
|
|
||||||
|
|
||||||
void _onAccess(LocationAccess access) {
|
void _onAccess(LocationAccess access) {
|
||||||
recorder.noteAccess(access);
|
view.noteAccess(access);
|
||||||
// canStart follows the access, which the recorder does not report.
|
// canStart follows the access, which the view does not report.
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _onRecorderChanged() {
|
|
||||||
if (_serviceState == RunServiceState.running) {
|
|
||||||
final copy = runNotificationCopy(
|
|
||||||
metres: recorder.distanceM,
|
|
||||||
movingSeconds: recorder.seconds,
|
|
||||||
currentPace: recorder.coach.target == null ? null : recorder.coach.pace,
|
|
||||||
);
|
|
||||||
// Only when the words changed: an update per fix would redraw twice a
|
|
||||||
// second for nothing.
|
|
||||||
if ('${copy.title}|${copy.body}' != _lastCopy) {
|
|
||||||
_lastCopy = '${copy.title}|${copy.body}';
|
|
||||||
unawaited(_service.update(title: copy.title, text: copy.body));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hangs up. The run, if any, goes on in the host.
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
|
unawaited(_sub.cancel());
|
||||||
unawaited(_idle.dispose());
|
unawaited(_idle.dispose());
|
||||||
recorder
|
unawaited(_link.close());
|
||||||
..removeListener(_onRecorderChanged)
|
view
|
||||||
|
..removeListener(notifyListeners)
|
||||||
..dispose();
|
..dispose();
|
||||||
if (active) unawaited(_service.stop());
|
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,92 @@
|
|||||||
|
/// The recording the run host drives, as an interface.
|
||||||
|
///
|
||||||
|
/// The host (service isolate in production) never touches `RunRecorder`
|
||||||
|
/// directly: every call into it goes through `run_engine_recorder.dart`, so
|
||||||
|
/// the host is tested against a fake and a change to the recorder lands in one
|
||||||
|
/// adapter.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/pace_band.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
|
||||||
|
/// What a recording tells its host while it runs.
|
||||||
|
class RunEngineHooks {
|
||||||
|
/// Creates the hooks.
|
||||||
|
const RunEngineHooks({
|
||||||
|
required this.onKilometre,
|
||||||
|
required this.onPaceCue,
|
||||||
|
required this.onSuggest,
|
||||||
|
required this.onAutoEnd,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A whole kilometre was credited (1, 2, 3 ...).
|
||||||
|
final void Function(int km) onKilometre;
|
||||||
|
|
||||||
|
/// The runner left the pace band.
|
||||||
|
final void Function(PaceCue cue) onPaceCue;
|
||||||
|
|
||||||
|
/// Advice to finish, named after the recorder's suggestion
|
||||||
|
/// (`stationary`, `vehicleSpeed`, `gpsLost`, `restored`). Never ends a run.
|
||||||
|
final void Function(String why) onSuggest;
|
||||||
|
|
||||||
|
/// The 5 h limit passed; the host finishes the run like a manual finish.
|
||||||
|
final void Function() onAutoEnd;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One recording: a state machine over a position source.
|
||||||
|
abstract interface class RunEngine implements Listenable {
|
||||||
|
/// Where the recording stands.
|
||||||
|
RunPhase get phase;
|
||||||
|
|
||||||
|
/// The current problem, or [RunIssue.none].
|
||||||
|
RunIssue get issue;
|
||||||
|
|
||||||
|
/// Accepted points so far, oldest first.
|
||||||
|
List<RunPoint> get points;
|
||||||
|
|
||||||
|
/// Credited moving time in seconds.
|
||||||
|
int get seconds;
|
||||||
|
|
||||||
|
/// Credited distance in metres.
|
||||||
|
double get distanceM;
|
||||||
|
|
||||||
|
/// The pace target in seconds per kilometre, or null.
|
||||||
|
int? get paceTarget;
|
||||||
|
|
||||||
|
/// The current pace in seconds per kilometre, once warmed up.
|
||||||
|
double? get pace;
|
||||||
|
|
||||||
|
/// Where [pace] stands against [paceTarget].
|
||||||
|
PaceBand? get band;
|
||||||
|
|
||||||
|
/// A snapshot to rebuild the run from, or null when idle or finished.
|
||||||
|
RunCheckpoint? checkpoint();
|
||||||
|
|
||||||
|
/// Asks for access and begins recording; false when refused or busy.
|
||||||
|
Future<bool> start();
|
||||||
|
|
||||||
|
/// Resumes the run from [checkpoint] without prompting; false when it
|
||||||
|
/// cannot (the reason is logged by the engine).
|
||||||
|
Future<bool> restore(RunCheckpoint checkpoint);
|
||||||
|
|
||||||
|
/// Stops crediting until [resume].
|
||||||
|
void pause();
|
||||||
|
|
||||||
|
/// Continues after [pause].
|
||||||
|
void resume();
|
||||||
|
|
||||||
|
/// Sets the pace target (null turns it off).
|
||||||
|
void setPaceTarget(int? seconds);
|
||||||
|
|
||||||
|
/// Ends the recording; the track, or null when there were too few fixes.
|
||||||
|
Future<RunTrack?> finish();
|
||||||
|
|
||||||
|
/// Releases the position stream.
|
||||||
|
void dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a fresh engine wired to [hooks].
|
||||||
|
typedef RunEngineFactory = RunEngine Function(RunEngineHooks hooks);
|
||||||
@ -0,0 +1,94 @@
|
|||||||
|
/// The one place the run host meets `RunRecorder`: an adapter from the
|
||||||
|
/// recorder's API to [RunEngine].
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/pace_band.dart';
|
||||||
|
import 'package:workout_app/services/position_source.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint.dart';
|
||||||
|
import 'package:workout_app/services/run_engine.dart';
|
||||||
|
import 'package:workout_app/services/run_recorder.dart';
|
||||||
|
|
||||||
|
/// A [RunEngine] over a [RunRecorder].
|
||||||
|
class RunRecorderEngine implements RunEngine {
|
||||||
|
/// Wraps [recorder].
|
||||||
|
RunRecorderEngine(this._recorder);
|
||||||
|
|
||||||
|
final RunRecorder _recorder;
|
||||||
|
|
||||||
|
@override
|
||||||
|
RunPhase get phase => _recorder.phase;
|
||||||
|
|
||||||
|
@override
|
||||||
|
RunIssue get issue => _recorder.issue;
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<RunPoint> get points => _recorder.livePoints.value;
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get seconds => _recorder.seconds;
|
||||||
|
|
||||||
|
@override
|
||||||
|
double get distanceM => _recorder.distanceM;
|
||||||
|
|
||||||
|
@override
|
||||||
|
int? get paceTarget => _recorder.coach.target;
|
||||||
|
|
||||||
|
@override
|
||||||
|
double? get pace => _recorder.coach.pace;
|
||||||
|
|
||||||
|
@override
|
||||||
|
PaceBand? get band => _recorder.coach.band;
|
||||||
|
|
||||||
|
@override
|
||||||
|
RunCheckpoint? checkpoint() => _recorder.checkpoint();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> start() => _recorder.start();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> restore(RunCheckpoint checkpoint) =>
|
||||||
|
_recorder.restore(checkpoint);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void pause() => _recorder.pause();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void resume() => _recorder.resume();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setPaceTarget(int? seconds) => _recorder.setPaceTarget(seconds);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<RunTrack?> finish() => _recorder.finish();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() => _recorder.dispose();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void addListener(VoidCallback listener) => _recorder.addListener(listener);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void removeListener(VoidCallback listener) =>
|
||||||
|
_recorder.removeListener(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds recorders over [sourceFor]; [clock] and [autoEndAfter] are the
|
||||||
|
/// recorder's own seams (shrunk by tests and the sandbox).
|
||||||
|
RunEngineFactory recorderEngineFactory(
|
||||||
|
PositionSource Function() sourceFor, {
|
||||||
|
DateTime Function() clock = DateTime.now,
|
||||||
|
Duration autoEndAfter = const Duration(hours: 5),
|
||||||
|
}) =>
|
||||||
|
(hooks) => RunRecorderEngine(
|
||||||
|
RunRecorder(
|
||||||
|
sourceFor: sourceFor,
|
||||||
|
onKilometre: hooks.onKilometre,
|
||||||
|
onPaceCue: hooks.onPaceCue,
|
||||||
|
onSuggestFinish: (why) => hooks.onSuggest(why.name),
|
||||||
|
onAutoEnd: hooks.onAutoEnd,
|
||||||
|
clock: clock,
|
||||||
|
autoEndAfter: autoEndAfter,
|
||||||
|
),
|
||||||
|
);
|
||||||
249
stronglift_replacement/workout_app/lib/services/run_host.dart
Normal file
249
stronglift_replacement/workout_app/lib/services/run_host.dart
Normal file
@ -0,0 +1,249 @@
|
|||||||
|
/// The one place a recording lives: owns the engine, keeps its checkpoint,
|
||||||
|
/// gives the cues and writes the finished run.
|
||||||
|
///
|
||||||
|
/// In production this runs in the foreground-service isolate, so a swiped-away
|
||||||
|
/// app, a killed UI isolate or a dead process cannot end a run: only
|
||||||
|
/// [RunCmd.finish] (after the screen's confirm modal) or the 5 h limit does.
|
||||||
|
/// On Linux and in tests the same class runs in the UI isolate behind a
|
||||||
|
/// loopback link.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/feedback_cues.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint_store.dart';
|
||||||
|
import 'package:workout_app/services/run_engine.dart';
|
||||||
|
import 'package:workout_app/services/run_host_port.dart';
|
||||||
|
import 'package:workout_app/services/run_notification.dart';
|
||||||
|
import 'package:workout_app/services/run_wire.dart';
|
||||||
|
|
||||||
|
export 'package:workout_app/services/run_host_port.dart';
|
||||||
|
|
||||||
|
/// Hosts one recording at a time.
|
||||||
|
class RunHost {
|
||||||
|
/// Creates a host; nothing happens until a command or [restoreFromStore].
|
||||||
|
RunHost({
|
||||||
|
required this.engineFactory,
|
||||||
|
required this.port,
|
||||||
|
required this.store,
|
||||||
|
required this.cues,
|
||||||
|
required this.save,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Builds the recording.
|
||||||
|
final RunEngineFactory engineFactory;
|
||||||
|
|
||||||
|
/// Where messages and the notification go.
|
||||||
|
final RunHostPort port;
|
||||||
|
|
||||||
|
/// Where the active run's checkpoint lives.
|
||||||
|
final RunCheckpointStore store;
|
||||||
|
|
||||||
|
/// The sounds and buzzes.
|
||||||
|
final FeedbackCues cues;
|
||||||
|
|
||||||
|
/// Writes a finished track to the database.
|
||||||
|
final RunSaveFn save;
|
||||||
|
|
||||||
|
RunEngine? _engine;
|
||||||
|
int _sent = 0;
|
||||||
|
String? _suggestion;
|
||||||
|
bool _prompt = false;
|
||||||
|
bool _saving = false;
|
||||||
|
bool _finishing = false;
|
||||||
|
bool _done = false;
|
||||||
|
({bool stored, String reason})? _saved;
|
||||||
|
String _lastCopy = '';
|
||||||
|
|
||||||
|
/// The live engine, if any (tests read it).
|
||||||
|
RunEngine? get engine => _engine;
|
||||||
|
|
||||||
|
/// Resumes the run the checkpoint describes. False when there is none (the
|
||||||
|
/// caller then has nothing to host).
|
||||||
|
Future<bool> restoreFromStore() async {
|
||||||
|
final checkpoint = await store.load();
|
||||||
|
if (checkpoint == null) return false;
|
||||||
|
final engine = _fresh();
|
||||||
|
if (!await engine.restore(checkpoint)) {
|
||||||
|
log(
|
||||||
|
'RunHost: the checkpoint could not be resumed (${engine.issue.name}); '
|
||||||
|
'it is kept, and the run screen shows the problem.',
|
||||||
|
level: 1000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_emit(full: true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies one UI command.
|
||||||
|
Future<void> handle(Map<Object?, Object?> message) async {
|
||||||
|
switch (message['cmd']) {
|
||||||
|
case RunCmd.hello:
|
||||||
|
_engine ?? _fresh();
|
||||||
|
_emit(full: true);
|
||||||
|
case RunCmd.start:
|
||||||
|
await _start(message);
|
||||||
|
case RunCmd.pause:
|
||||||
|
_engine?.pause();
|
||||||
|
case RunCmd.resume:
|
||||||
|
_engine?.resume();
|
||||||
|
case RunCmd.paceTarget:
|
||||||
|
_engine?.setPaceTarget(message['paceTarget'] as int?);
|
||||||
|
case RunCmd.ackPrompt:
|
||||||
|
_prompt = false;
|
||||||
|
_emit();
|
||||||
|
case RunCmd.finish:
|
||||||
|
await _finish(auto: false);
|
||||||
|
default:
|
||||||
|
log('RunHost: unknown command ${message['cmd']} ignored.', level: 900);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ongoing notification was tapped: with advice standing, the UI opens
|
||||||
|
/// on the finish modal (it still needs the check tap).
|
||||||
|
void notificationPressed() {
|
||||||
|
if (_suggestion != null) {
|
||||||
|
_prompt = true;
|
||||||
|
_emit();
|
||||||
|
}
|
||||||
|
port.launchApp();
|
||||||
|
}
|
||||||
|
|
||||||
|
RunEngine _fresh() {
|
||||||
|
_engine
|
||||||
|
?..removeListener(_onChanged)
|
||||||
|
..dispose();
|
||||||
|
_sent = 0;
|
||||||
|
_suggestion = null;
|
||||||
|
_prompt = false;
|
||||||
|
_saved = null;
|
||||||
|
_saving = false;
|
||||||
|
_done = false;
|
||||||
|
return _engine = engineFactory(
|
||||||
|
RunEngineHooks(
|
||||||
|
onKilometre: (km) => unawaited(cues.kilometreReached(km)),
|
||||||
|
onPaceCue: (cue) => unawaited(cues.paceOff(cue)),
|
||||||
|
onSuggest: _suggest,
|
||||||
|
onAutoEnd: () => unawaited(_finish(auto: true)),
|
||||||
|
),
|
||||||
|
)..addListener(_onChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _start(Map<Object?, Object?> message) async {
|
||||||
|
final current = _engine;
|
||||||
|
if (current != null && current.phase.isActive) {
|
||||||
|
// A second "start" can never restart a live run: it only re-syncs.
|
||||||
|
return _emit(full: true);
|
||||||
|
}
|
||||||
|
final engine = _fresh();
|
||||||
|
cues.soundOn = message['sound'] as bool? ?? true;
|
||||||
|
engine.setPaceTarget(message['paceTarget'] as int?);
|
||||||
|
await engine.start();
|
||||||
|
_emit(full: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _suggest(String why) {
|
||||||
|
if (_finishing) return;
|
||||||
|
_suggestion = why;
|
||||||
|
unawaited(cues.finishSuggested());
|
||||||
|
_onChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onChanged() {
|
||||||
|
final engine = _engine;
|
||||||
|
if (engine == null) return;
|
||||||
|
if (engine.phase.isActive) {
|
||||||
|
saveCheckpointLoudly(store, engine.checkpoint());
|
||||||
|
_redrawNotification(engine);
|
||||||
|
}
|
||||||
|
_emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _redrawNotification(RunEngine engine) {
|
||||||
|
final copy = runNotificationCopy(
|
||||||
|
metres: engine.distanceM,
|
||||||
|
movingSeconds: engine.seconds,
|
||||||
|
currentPace: engine.paceTarget == null ? null : engine.pace,
|
||||||
|
);
|
||||||
|
final why = _suggestion;
|
||||||
|
final title = why == null
|
||||||
|
? copy.title
|
||||||
|
: '${suggestionGlyph(why)} ${copy.title}';
|
||||||
|
// Only when the words changed: an update per fix redraws twice a second
|
||||||
|
// for nothing.
|
||||||
|
if ('$title|${copy.body}' == _lastCopy) return;
|
||||||
|
_lastCopy = '$title|${copy.body}';
|
||||||
|
unawaited(port.notify(title: title, text: copy.body));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _emit({bool full = false}) {
|
||||||
|
final engine = _engine;
|
||||||
|
if (engine == null) return;
|
||||||
|
final from = full ? 0 : _sent.clamp(0, engine.points.length);
|
||||||
|
port.send(
|
||||||
|
encodeSnapshot(
|
||||||
|
engine,
|
||||||
|
from: from,
|
||||||
|
suggestion: _suggestion,
|
||||||
|
prompt: _prompt,
|
||||||
|
saving: _saving,
|
||||||
|
done: _done,
|
||||||
|
saved: _saved,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
_sent = engine.points.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _finish({required bool auto}) async {
|
||||||
|
final engine = _engine;
|
||||||
|
if (engine == null || !engine.phase.isActive || _finishing) return;
|
||||||
|
_finishing = true;
|
||||||
|
try {
|
||||||
|
final track = await engine.finish();
|
||||||
|
_suggestion = null;
|
||||||
|
_prompt = false;
|
||||||
|
unawaited(auto ? cues.autoEnded() : cues.workoutFinished());
|
||||||
|
final kept = track != null && !await _saveTrack(track);
|
||||||
|
// A save that said "no" (say, a duplicate) still ends the run; only one
|
||||||
|
// that threw keeps the checkpoint, so the run is not lost.
|
||||||
|
if (!kept) await store.clear();
|
||||||
|
_done = true;
|
||||||
|
_emit();
|
||||||
|
await port.stopService();
|
||||||
|
} finally {
|
||||||
|
_finishing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the save ran without throwing.
|
||||||
|
Future<bool> _saveTrack(RunTrack track) async {
|
||||||
|
_saving = true;
|
||||||
|
_emit();
|
||||||
|
try {
|
||||||
|
_saved = await save(track);
|
||||||
|
return true;
|
||||||
|
} on Exception catch (error, stack) {
|
||||||
|
log(
|
||||||
|
'RunHost: saving ${track.id} failed ($error) -- the checkpoint is '
|
||||||
|
'kept, so the run comes back on the next launch.',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stack,
|
||||||
|
);
|
||||||
|
_saved = (stored: false, reason: 'save failed: $error');
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
_saving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Releases the engine (never ends a run).
|
||||||
|
void dispose() {
|
||||||
|
_engine
|
||||||
|
?..removeListener(_onChanged)
|
||||||
|
..dispose();
|
||||||
|
_engine = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,54 @@
|
|||||||
|
/// The host's way out to the rest of the phone, and its two small types.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint_store.dart';
|
||||||
|
|
||||||
|
/// The host's way out to the rest of the phone.
|
||||||
|
abstract interface class RunHostPort {
|
||||||
|
/// Sends [message] to the UI (dropped when no UI is listening).
|
||||||
|
void send(Map<String, Object?> message);
|
||||||
|
|
||||||
|
/// Redraws the ongoing notification.
|
||||||
|
Future<void> notify({required String title, required String text});
|
||||||
|
|
||||||
|
/// Stops the foreground service (the run is over and saved).
|
||||||
|
Future<void> stopService();
|
||||||
|
|
||||||
|
/// Brings the app to the front.
|
||||||
|
void launchApp();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves a finished track; the reason reads like a sentence.
|
||||||
|
typedef RunSaveFn =
|
||||||
|
Future<({bool stored, String reason})> Function(RunTrack track);
|
||||||
|
|
||||||
|
/// Marks a notification title as carrying advice to finish: symbols only
|
||||||
|
/// (textgate), one per reason.
|
||||||
|
String suggestionGlyph(String why) => switch (why) {
|
||||||
|
'stationary' => '⏸',
|
||||||
|
'vehicleSpeed' => '⚡',
|
||||||
|
'gpsLost' => '⌖',
|
||||||
|
_ => '↻',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Stores [checkpoint] (when there is one) without waiting; a failed write is
|
||||||
|
/// logged, never swallowed.
|
||||||
|
void saveCheckpointLoudly(RunCheckpointStore store, RunCheckpoint? checkpoint) {
|
||||||
|
if (checkpoint == null) return;
|
||||||
|
unawaited(
|
||||||
|
store.save(checkpoint).catchError((Object error, StackTrace stack) {
|
||||||
|
log(
|
||||||
|
'RunHost: could not save the run checkpoint ($error) -- a dead '
|
||||||
|
'process would lose the run since the last good save.',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stack,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,37 @@
|
|||||||
|
/// What the app does at launch about a run that may be in progress.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:workout_app/services/foreground_run_client.dart';
|
||||||
|
import 'package:workout_app/services/run_notification.dart';
|
||||||
|
|
||||||
|
/// Whether the app must open on the live run, bringing its service back if it
|
||||||
|
/// is gone.
|
||||||
|
///
|
||||||
|
/// A run is owed while its checkpoint is on disk ([owed]). The service
|
||||||
|
/// normally survives (swipe-away, kill, reboot all restart it by themselves);
|
||||||
|
/// after a force-stop it does not, and this restarts it: the service restores
|
||||||
|
/// the run from the same checkpoint. [client.start] leaves a running service
|
||||||
|
/// alone, so asking while one is up is harmless.
|
||||||
|
Future<bool> resumeRunOnLaunch({
|
||||||
|
required Future<bool> Function() owed,
|
||||||
|
required ForegroundRunClient client,
|
||||||
|
}) async {
|
||||||
|
if (!await owed()) return false;
|
||||||
|
if (!client.isSupported) return true;
|
||||||
|
final copy = runNotificationCopy(metres: 0, movingSeconds: 0);
|
||||||
|
final up = await client.start(
|
||||||
|
withLocation: true,
|
||||||
|
title: copy.title,
|
||||||
|
text: copy.body,
|
||||||
|
);
|
||||||
|
if (!up) {
|
||||||
|
log(
|
||||||
|
'RunLaunch: a run is owed but its service would not start; the run '
|
||||||
|
'screen opens anyway and shows the problem. Its checkpoint is kept.',
|
||||||
|
level: 1000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
104
stronglift_replacement/workout_app/lib/services/run_link.dart
Normal file
104
stronglift_replacement/workout_app/lib/services/run_link.dart
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
/// The UI's line to the run host, and the in-process version of it.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:workout_app/services/feedback_cues.dart';
|
||||||
|
import 'package:workout_app/services/foreground_run_client.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint_store.dart';
|
||||||
|
import 'package:workout_app/services/run_engine.dart';
|
||||||
|
import 'package:workout_app/services/run_host.dart';
|
||||||
|
|
||||||
|
/// A conversation with the host. Closing it only hangs up: it never touches
|
||||||
|
/// the run.
|
||||||
|
abstract interface class RunLink {
|
||||||
|
/// The host's snapshots (see `run_wire.dart`).
|
||||||
|
Stream<Map<Object?, Object?>> get messages;
|
||||||
|
|
||||||
|
/// Sends a command (`cmd` key); a host that is not up never answers.
|
||||||
|
void send(Map<String, Object?> command);
|
||||||
|
|
||||||
|
/// Hangs up.
|
||||||
|
Future<void> close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host's side of a [LoopbackRunLink]: messages go to the link's stream,
|
||||||
|
/// the notification and the service go through the [ForegroundRunClient].
|
||||||
|
class LoopbackRunPort implements RunHostPort {
|
||||||
|
/// Creates a port over [_client].
|
||||||
|
LoopbackRunPort(this._client);
|
||||||
|
|
||||||
|
final ForegroundRunClient _client;
|
||||||
|
final _out = StreamController<Map<Object?, Object?>>.broadcast(sync: true);
|
||||||
|
|
||||||
|
/// What the host sends.
|
||||||
|
Stream<Map<Object?, Object?>> get messages => _out.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void send(Map<String, Object?> message) => _out.add(message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> notify({required String title, required String text}) =>
|
||||||
|
_client.update(title: title, text: text);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> stopService() => _client.stop();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void launchApp() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [RunLink] to a host in this very isolate: Linux, the tests, and any
|
||||||
|
/// platform with no foreground service.
|
||||||
|
class LoopbackRunLink implements RunLink {
|
||||||
|
/// Creates a link to [host]; [port] is the one the host was built with.
|
||||||
|
LoopbackRunLink(this.host, this._port);
|
||||||
|
|
||||||
|
/// Builds the host and its link in one go.
|
||||||
|
factory LoopbackRunLink.build({
|
||||||
|
required ForegroundRunClient client,
|
||||||
|
required RunEngineFactory engineFactory,
|
||||||
|
required FeedbackCues cues,
|
||||||
|
required RunSaveFn save,
|
||||||
|
RunCheckpointStore? store,
|
||||||
|
}) {
|
||||||
|
final port = LoopbackRunPort(client);
|
||||||
|
final host = RunHost(
|
||||||
|
engineFactory: engineFactory,
|
||||||
|
port: port,
|
||||||
|
store: store ?? MemoryRunCheckpointStore(),
|
||||||
|
cues: cues,
|
||||||
|
save: save,
|
||||||
|
);
|
||||||
|
return LoopbackRunLink(host, port);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The in-process host.
|
||||||
|
final RunHost host;
|
||||||
|
final LoopbackRunPort _port;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Map<Object?, Object?>> get messages => _port.messages;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void send(Map<String, Object?> command) => unawaited(host.handle(command));
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close() async {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A checkpoint kept in memory: enough where nothing can kill the process
|
||||||
|
/// separately from the UI.
|
||||||
|
class MemoryRunCheckpointStore implements RunCheckpointStore {
|
||||||
|
RunCheckpoint? _held;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> save(RunCheckpoint c) async => _held = c;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<RunCheckpoint?> load() async => _held;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> clear() async => _held = null;
|
||||||
|
}
|
||||||
@ -0,0 +1,145 @@
|
|||||||
|
// coverage:ignore-file
|
||||||
|
// Everything here runs only in the foreground-service isolate, where there is
|
||||||
|
// no widget binding a test can reach. The decisions are in run_host.dart and
|
||||||
|
// run_task_handler.dart, covered against fakes; this file only wires the real
|
||||||
|
// plugin, location source and database to them.
|
||||||
|
/// The run foreground service's entry point (the isolate the run lives in).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:audioplayers/audioplayers.dart';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/sandbox/sandbox.dart';
|
||||||
|
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
|
||||||
|
import 'package:workout_app/services/feedback_cues.dart';
|
||||||
|
import 'package:workout_app/services/gps_filter.dart';
|
||||||
|
import 'package:workout_app/services/position_source.dart';
|
||||||
|
import 'package:workout_app/services/position_source_geolocator.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint_location.dart';
|
||||||
|
import 'package:workout_app/services/run_engine_recorder.dart';
|
||||||
|
import 'package:workout_app/services/run_host.dart';
|
||||||
|
import 'package:workout_app/services/run_saver.dart';
|
||||||
|
import 'package:workout_app/services/run_task_handler.dart';
|
||||||
|
import 'package:workout_app/services/storage_service.dart';
|
||||||
|
|
||||||
|
/// `FlutterForegroundTask.saveData` keys the UI isolate writes before it
|
||||||
|
/// starts the service (the service isolate cannot ask MainActivity).
|
||||||
|
const kRunFlagSandbox = 'run_sandbox';
|
||||||
|
|
||||||
|
/// See [kRunFlagSandbox].
|
||||||
|
const kRunFlagReplayFactor = 'run_replay_factor';
|
||||||
|
|
||||||
|
/// See [kRunFlagSandbox].
|
||||||
|
const kRunFlagSound = 'run_sound';
|
||||||
|
|
||||||
|
/// Entry point the plugin calls in the background isolate.
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
void runServiceStartCallback() {
|
||||||
|
FlutterForegroundTask.setTaskHandler(_RunServiceTaskHandler());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A position source that never shows a prompt: the service has no Activity
|
||||||
|
/// to ask from, and the UI already settled the permission.
|
||||||
|
class NoPromptSource implements PositionSource {
|
||||||
|
/// Wraps [_inner].
|
||||||
|
NoPromptSource(this._inner);
|
||||||
|
|
||||||
|
final PositionSource _inner;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<LocationAccess> requestAccess() => _inner.checkAccess();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<LocationAccess> checkAccess() => _inner.checkAccess();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
|
||||||
|
_inner.fixes(interval: interval);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ServicePort implements RunHostPort {
|
||||||
|
@override
|
||||||
|
void send(Map<String, Object?> message) =>
|
||||||
|
FlutterForegroundTask.sendDataToMain(message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> notify({required String title, required String text}) async {
|
||||||
|
await FlutterForegroundTask.updateService(
|
||||||
|
notificationTitle: title,
|
||||||
|
notificationText: text,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> stopService() async {
|
||||||
|
final result = await FlutterForegroundTask.stopService();
|
||||||
|
if (result is! ServiceRequestSuccess) {
|
||||||
|
log('RunService: stopping the service failed ($result).', level: 1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void launchApp() => FlutterForegroundTask.launchApp();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<({bool stored, String reason})> _saveInService(RunTrack track) async {
|
||||||
|
final result = await saveRecordedRun(
|
||||||
|
track,
|
||||||
|
storage: await StorageService.init(),
|
||||||
|
// The UI isolate uploads on its next start and resume; this isolate keeps
|
||||||
|
// the sandbox's offline guarantee (no HTTP overrides here).
|
||||||
|
enqueue: () async => null,
|
||||||
|
);
|
||||||
|
return (stored: result.stored, reason: result.reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RunServiceTaskHandler extends TaskHandler {
|
||||||
|
RunTaskHandler? _handler;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
|
||||||
|
Sandbox.enabled =
|
||||||
|
await FlutterForegroundTask.getData<bool>(key: kRunFlagSandbox) ??
|
||||||
|
false;
|
||||||
|
Sandbox.runReplayFactor =
|
||||||
|
await FlutterForegroundTask.getData<int>(key: kRunFlagReplayFactor) ??
|
||||||
|
Sandbox.defaultReplayFactor;
|
||||||
|
final cues = FeedbackCues(AudioPlayer())
|
||||||
|
..soundOn =
|
||||||
|
await FlutterForegroundTask.getData<bool>(key: kRunFlagSound) ?? true;
|
||||||
|
final port = _ServicePort();
|
||||||
|
final host = RunHost(
|
||||||
|
engineFactory: recorderEngineFactory(
|
||||||
|
() => Sandbox.enabled
|
||||||
|
? sandboxRunSource()
|
||||||
|
: NoPromptSource(GeolocatorPositionSource()),
|
||||||
|
),
|
||||||
|
port: port,
|
||||||
|
store: await openRunCheckpointStore(),
|
||||||
|
cues: cues,
|
||||||
|
save: _saveInService,
|
||||||
|
);
|
||||||
|
final handler = _handler = RunTaskHandler(host: host, port: port);
|
||||||
|
debugPrint('RunService: onStart ${starter.name}');
|
||||||
|
await handler.onStart(startedBySystem: starter == TaskStarter.system);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onRepeatEvent(DateTime timestamp) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onReceiveData(Object data) => _handler?.onReceiveData(data);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onNotificationPressed() => _handler?.onNotificationPressed();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {
|
||||||
|
debugPrint('RunService: onDestroy timeout=$isTimeout');
|
||||||
|
_handler?.onDestroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,59 @@
|
|||||||
|
/// What the run foreground service does at each plugin callback, without the
|
||||||
|
/// plugin: [RunTaskHandler] is tested against a fake port, the thin adapter in
|
||||||
|
/// `run_service_isolate.dart` only forwards.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:workout_app/services/run_host.dart';
|
||||||
|
|
||||||
|
/// Drives a [RunHost] from the service's lifecycle.
|
||||||
|
class RunTaskHandler {
|
||||||
|
/// Creates a handler over [host]; [port] is the one the host was built with.
|
||||||
|
RunTaskHandler({required this.host, required this.port});
|
||||||
|
|
||||||
|
/// The recording's home.
|
||||||
|
final RunHost host;
|
||||||
|
|
||||||
|
/// Used to stop the service when it has nothing to host.
|
||||||
|
final RunHostPort port;
|
||||||
|
|
||||||
|
/// The service came up. A checkpoint on disk means a run is owed: resume it,
|
||||||
|
/// whoever started the service (the OS after a kill or a reboot, or the app
|
||||||
|
/// after a force-stop). With none, a system start has no run to serve (a
|
||||||
|
/// stale service or a leftover boot flag), so it stops itself; an app start
|
||||||
|
/// waits for the start command.
|
||||||
|
Future<void> onStart({required bool startedBySystem}) async {
|
||||||
|
final restored = await host.restoreFromStore();
|
||||||
|
if (restored) return;
|
||||||
|
if (startedBySystem) {
|
||||||
|
log(
|
||||||
|
'RunTaskHandler: the system started the run service but there is no '
|
||||||
|
'run checkpoint -- nothing to record, so it stops itself.',
|
||||||
|
level: 900,
|
||||||
|
);
|
||||||
|
await port.stopService();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A message from the UI.
|
||||||
|
void onReceiveData(Object data) {
|
||||||
|
if (data is Map && data['cmd'] is String) {
|
||||||
|
unawaited(host.handle(data));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log(
|
||||||
|
'RunTaskHandler: ignored a message that is not a run command '
|
||||||
|
'(${data.runtimeType}); the break service shares this channel.',
|
||||||
|
level: 900,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ongoing notification was tapped.
|
||||||
|
void onNotificationPressed() => host.notificationPressed();
|
||||||
|
|
||||||
|
/// The service is going away: the host lets go. This never ends the run;
|
||||||
|
/// its checkpoint stays for the next start.
|
||||||
|
void onDestroy() => host.dispose();
|
||||||
|
}
|
||||||
127
stronglift_replacement/workout_app/lib/services/run_view.dart
Normal file
127
stronglift_replacement/workout_app/lib/services/run_view.dart
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
/// What the run screen shows: a mirror of the host's last snapshot.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/pace_band.dart';
|
||||||
|
import 'package:workout_app/services/position_source.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
import 'package:workout_app/services/run_wire.dart';
|
||||||
|
|
||||||
|
/// The recording as the UI sees it. The numbers belong to the host; this only
|
||||||
|
/// keeps the newest copy, so a dead screen loses nothing.
|
||||||
|
class RunView extends ChangeNotifier {
|
||||||
|
/// Asks the host for a full copy ([RunCmd.hello]) when points were missed.
|
||||||
|
void Function()? onNeedSync;
|
||||||
|
|
||||||
|
/// Where the recording stands.
|
||||||
|
RunPhase phase = RunPhase.idle;
|
||||||
|
|
||||||
|
/// The current problem, or [RunIssue.none].
|
||||||
|
RunIssue issue = RunIssue.none;
|
||||||
|
|
||||||
|
/// Credited moving time in seconds.
|
||||||
|
int seconds = 0;
|
||||||
|
|
||||||
|
/// Credited distance in metres.
|
||||||
|
double distanceM = 0;
|
||||||
|
|
||||||
|
/// The pace target in seconds per kilometre, or null.
|
||||||
|
int? paceTarget;
|
||||||
|
|
||||||
|
/// The current pace in seconds per kilometre, once warmed up.
|
||||||
|
double? pace;
|
||||||
|
|
||||||
|
/// Where [pace] stands against [paceTarget].
|
||||||
|
PaceBand? band;
|
||||||
|
|
||||||
|
/// The reason the host suggests finishing, or null.
|
||||||
|
String? suggestion;
|
||||||
|
|
||||||
|
/// The notification was tapped while a suggestion stood: show the modal.
|
||||||
|
bool promptFinish = false;
|
||||||
|
|
||||||
|
/// The host is writing the finished run.
|
||||||
|
bool saving = false;
|
||||||
|
|
||||||
|
/// The host is through with the finished run (saved, or nothing to save).
|
||||||
|
bool done = false;
|
||||||
|
|
||||||
|
/// What saving did, once the host finished.
|
||||||
|
({bool stored, String reason})? saved;
|
||||||
|
|
||||||
|
/// Whether any snapshot has arrived yet.
|
||||||
|
bool synced = false;
|
||||||
|
|
||||||
|
/// Accepted points so far, for the live map.
|
||||||
|
final livePoints = ValueNotifier<List<RunPoint>>(const []);
|
||||||
|
|
||||||
|
/// Folds an access check in while idle: a refusal becomes the issue, a
|
||||||
|
/// grant clears it. Local: with no run there is no host to ask.
|
||||||
|
void noteAccess(LocationAccess access) {
|
||||||
|
if (phase != RunPhase.idle) return;
|
||||||
|
if (!access.isGranted) {
|
||||||
|
issue = RunIssue.forAccess(access);
|
||||||
|
return notifyListeners();
|
||||||
|
}
|
||||||
|
if (!issue.isAccess) return;
|
||||||
|
issue = RunIssue.none;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes the host's newest message.
|
||||||
|
void apply(Map<Object?, Object?> m) {
|
||||||
|
final next = RunPhase.values.byName(m['phase']! as String);
|
||||||
|
final incoming = RunIssue.values.byName(m['issue']! as String);
|
||||||
|
// An idle host knows nothing of the permission the UI just checked: its
|
||||||
|
// "no issue" must not wipe a refusal the UI found itself.
|
||||||
|
if (next != RunPhase.idle || incoming != RunIssue.none) issue = incoming;
|
||||||
|
phase = next;
|
||||||
|
seconds = m['seconds']! as int;
|
||||||
|
distanceM = (m['distanceM']! as num).toDouble();
|
||||||
|
paceTarget = m['paceTarget'] as int?;
|
||||||
|
pace = (m['pace'] as num?)?.toDouble();
|
||||||
|
final bandName = m['band'] as String?;
|
||||||
|
band = bandName == null ? null : PaceBand.values.byName(bandName);
|
||||||
|
suggestion = m['suggestion'] as String?;
|
||||||
|
promptFinish = m['prompt']! as bool;
|
||||||
|
saving = m['saving']! as bool;
|
||||||
|
done = m['done']! as bool;
|
||||||
|
final savedRaw = m['saved'] as Map<Object?, Object?>?;
|
||||||
|
saved = savedRaw == null
|
||||||
|
? null
|
||||||
|
: (
|
||||||
|
stored: savedRaw['stored']! as bool,
|
||||||
|
reason: savedRaw['reason']! as String,
|
||||||
|
);
|
||||||
|
synced = true;
|
||||||
|
_applyPoints(m);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _applyPoints(Map<Object?, Object?> m) {
|
||||||
|
final from = m['from']! as int;
|
||||||
|
final total = m['total']! as int;
|
||||||
|
final fresh = [
|
||||||
|
for (final raw in m['pts']! as List<Object?>)
|
||||||
|
decodePoint((raw! as List<Object?>).cast<Object?>()),
|
||||||
|
];
|
||||||
|
final held = livePoints.value;
|
||||||
|
if (from == 0) {
|
||||||
|
livePoints.value = fresh;
|
||||||
|
} else if (from == held.length) {
|
||||||
|
livePoints.value = [...held, ...fresh];
|
||||||
|
} else {
|
||||||
|
// A message was lost (the screen was away): ask for everything again.
|
||||||
|
onNeedSync?.call();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (livePoints.value.length != total) onNeedSync?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
livePoints.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,92 @@
|
|||||||
|
/// The messages the run UI and the run host (the foreground-service isolate)
|
||||||
|
/// exchange. JSON-safe maps only: they cross an isolate boundary.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/run_engine.dart';
|
||||||
|
|
||||||
|
/// Key every host message carries, so the break service's data channel (the
|
||||||
|
/// same plugin channel) can tell the two apart.
|
||||||
|
const kRunWireKey = 'run';
|
||||||
|
|
||||||
|
/// UI -> host commands, under the `cmd` key.
|
||||||
|
abstract final class RunCmd {
|
||||||
|
/// "Send me everything": answered with a full snapshot.
|
||||||
|
static const hello = 'hello';
|
||||||
|
|
||||||
|
/// Begin recording; carries `paceTarget` and `sound`.
|
||||||
|
static const start = 'start';
|
||||||
|
|
||||||
|
/// Pause crediting.
|
||||||
|
static const pause = 'pause';
|
||||||
|
|
||||||
|
/// Resume crediting.
|
||||||
|
static const resume = 'resume';
|
||||||
|
|
||||||
|
/// End the run (only after the confirm modal).
|
||||||
|
static const finish = 'finish';
|
||||||
|
|
||||||
|
/// Change the pace target; carries `paceTarget`.
|
||||||
|
static const paceTarget = 'paceTarget';
|
||||||
|
|
||||||
|
/// The UI showed the finish modal the notification asked for.
|
||||||
|
static const ackPrompt = 'ackPrompt';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One point as `[ms, lat, lon, distanceM, altitudeM?]`.
|
||||||
|
List<Object?> encodePoint(RunPoint p) => [
|
||||||
|
p.time.millisecondsSinceEpoch,
|
||||||
|
p.latitude,
|
||||||
|
p.longitude,
|
||||||
|
p.distanceM,
|
||||||
|
p.altitudeM,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Inverse of [encodePoint].
|
||||||
|
RunPoint decodePoint(List<Object?> raw) => RunPoint(
|
||||||
|
time: DateTime.fromMillisecondsSinceEpoch(raw[0]! as int, isUtc: true),
|
||||||
|
latitude: (raw[1]! as num).toDouble(),
|
||||||
|
longitude: (raw[2]! as num).toDouble(),
|
||||||
|
distanceM: (raw[3]! as num).toDouble(),
|
||||||
|
altitudeM: (raw[4] as num?)?.toDouble(),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The host's state as one message.
|
||||||
|
///
|
||||||
|
/// [from] says which point index `pts` starts at, so a UI that already holds
|
||||||
|
/// the first [from] points appends, and one that does not sends
|
||||||
|
/// [RunCmd.hello] for a full copy.
|
||||||
|
Map<String, Object?> encodeSnapshot(
|
||||||
|
RunEngine engine, {
|
||||||
|
required int from,
|
||||||
|
String? suggestion,
|
||||||
|
bool prompt = false,
|
||||||
|
bool saving = false,
|
||||||
|
bool done = false,
|
||||||
|
({bool stored, String reason})? saved,
|
||||||
|
}) {
|
||||||
|
final points = engine.points;
|
||||||
|
return {
|
||||||
|
kRunWireKey: 1,
|
||||||
|
'phase': engine.phase.name,
|
||||||
|
'issue': engine.issue.name,
|
||||||
|
'seconds': engine.seconds,
|
||||||
|
'distanceM': engine.distanceM,
|
||||||
|
'paceTarget': engine.paceTarget,
|
||||||
|
'pace': engine.pace,
|
||||||
|
'band': engine.band?.name,
|
||||||
|
'suggestion': suggestion,
|
||||||
|
'prompt': prompt,
|
||||||
|
'saving': saving,
|
||||||
|
'done': done,
|
||||||
|
'saved': saved == null
|
||||||
|
? null
|
||||||
|
: {'stored': saved.stored, 'reason': saved.reason},
|
||||||
|
'from': from,
|
||||||
|
'total': points.length,
|
||||||
|
'pts': [for (var i = from; i < points.length; i++) encodePoint(points[i])],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether [data] is a host message (not a break-service one).
|
||||||
|
bool isRunMessage(Object? data) => data is Map && data[kRunWireKey] == 1;
|
||||||
@ -0,0 +1,50 @@
|
|||||||
|
// coverage:ignore-file
|
||||||
|
// The composition root of a recording: it only names the real plugin,
|
||||||
|
// database and GPS. Every decision is in the classes it connects, covered
|
||||||
|
// against fakes.
|
||||||
|
/// The real parts a run is built from, installed by `main`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:audioplayers/audioplayers.dart';
|
||||||
|
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
|
||||||
|
import 'package:workout_app/screens/run_screen.dart';
|
||||||
|
import 'package:workout_app/services/feedback_cues.dart';
|
||||||
|
import 'package:workout_app/services/foreground_run_client_flutter.dart';
|
||||||
|
import 'package:workout_app/services/run_controller.dart';
|
||||||
|
import 'package:workout_app/services/run_engine_recorder.dart';
|
||||||
|
import 'package:workout_app/services/run_link.dart';
|
||||||
|
import 'package:workout_app/services/run_saver.dart';
|
||||||
|
import 'package:workout_app/services/run_uploader.dart';
|
||||||
|
import 'package:workout_app/services/storage_service.dart';
|
||||||
|
|
||||||
|
/// Real GPS (or the sandbox replay), the real service and database. On
|
||||||
|
/// Android the run lives in the service isolate behind a [ServiceRunLink];
|
||||||
|
/// elsewhere it lives in this isolate behind a loopback.
|
||||||
|
RunController buildRunController() {
|
||||||
|
final client = FlutterForegroundRunClient();
|
||||||
|
return RunController(
|
||||||
|
idleSourceFor: idlePositionSourceFor,
|
||||||
|
service: client,
|
||||||
|
link: client.isSupported
|
||||||
|
? ServiceRunLink()
|
||||||
|
: LoopbackRunLink.build(
|
||||||
|
client: client,
|
||||||
|
engineFactory: recorderEngineFactory(positionSourceFor),
|
||||||
|
cues: FeedbackCues(AudioPlayer()),
|
||||||
|
save: (track) async {
|
||||||
|
final result = await saveRecordedRun(
|
||||||
|
track,
|
||||||
|
storage: StorageService.instance,
|
||||||
|
enqueue: RunUploader.instance.uploadPending,
|
||||||
|
);
|
||||||
|
return (stored: result.stored, reason: result.reason);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
soundOn: () => StorageService.instance.getSoundEnabled(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs [buildRunController] as the run screen's default.
|
||||||
|
void installRunWiring() {
|
||||||
|
RunScreen.defaultControllerFactory = buildRunController;
|
||||||
|
}
|
||||||
@ -0,0 +1,50 @@
|
|||||||
|
/// The confirm step before a run ends: a red check ends it, a cross goes back.
|
||||||
|
/// No words (textgate): colour and two icons carry the whole question.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:workout_app/ui/theme.dart';
|
||||||
|
|
||||||
|
/// Asks whether to end the run. True only for the red check; the cross, the
|
||||||
|
/// back button and a tap outside all answer false, so nothing but a deliberate
|
||||||
|
/// check ends a run.
|
||||||
|
Future<bool> showRunFinishDialog(BuildContext context) async {
|
||||||
|
final end = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
Widget choice(String id, IconData icon, Color fill, bool answer) =>
|
||||||
|
IconButton.filled(
|
||||||
|
key: Key('run_finish_$id'),
|
||||||
|
onPressed: () => Navigator.of(context).pop(answer),
|
||||||
|
iconSize: 48,
|
||||||
|
style: IconButton.styleFrom(
|
||||||
|
fixedSize: const Size.square(96),
|
||||||
|
backgroundColor: fill,
|
||||||
|
foregroundColor: scheme.onPrimary,
|
||||||
|
),
|
||||||
|
icon: Icon(icon, semanticLabel: id),
|
||||||
|
);
|
||||||
|
return Dialog(
|
||||||
|
key: const Key('run_finish_dialog'),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.lg),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||||
|
children: [
|
||||||
|
choice('confirm', Icons.check, scheme.error, true),
|
||||||
|
choice(
|
||||||
|
'cancel',
|
||||||
|
Icons.close,
|
||||||
|
scheme.surfaceContainerHighest,
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return end ?? false;
|
||||||
|
}
|
||||||
@ -0,0 +1,55 @@
|
|||||||
|
/// Keeps the app on the live run: when it comes back to the front with a run
|
||||||
|
/// owed and nothing above home, the run screen opens again.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:workout_app/screens/run_screen.dart';
|
||||||
|
|
||||||
|
/// Wraps the home route of the app.
|
||||||
|
class RunLanding extends StatefulWidget {
|
||||||
|
/// Creates the wrapper; a null [owed] (no run can exist here) never lands.
|
||||||
|
const RunLanding({required this.child, this.owed, super.key});
|
||||||
|
|
||||||
|
/// Whether a run is owed right now.
|
||||||
|
final Future<bool> Function()? owed;
|
||||||
|
|
||||||
|
/// The home screen.
|
||||||
|
final Widget child;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<RunLanding> createState() => _RunLandingState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RunLandingState extends State<RunLanding> 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) {
|
||||||
|
if (state == AppLifecycleState.resumed) unawaited(_land());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _land() async {
|
||||||
|
final owed = widget.owed;
|
||||||
|
// Anything above home (the run itself, a workout) already has the screen.
|
||||||
|
if (owed == null || !(ModalRoute.of(context)?.isCurrent ?? false)) return;
|
||||||
|
if (!await owed() || !mounted) return;
|
||||||
|
await Navigator.of(context).push(
|
||||||
|
MaterialPageRoute<void>(builder: (_) => const RunScreen(resuming: true)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => widget.child;
|
||||||
|
}
|
||||||
157
stronglift_replacement/workout_app/test/fake_run_engine.dart
Normal file
157
stronglift_replacement/workout_app/test/fake_run_engine.dart
Normal file
@ -0,0 +1,157 @@
|
|||||||
|
/// A hand-driven [RunEngine] for the host, controller and screen tests.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/pace_band.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint.dart';
|
||||||
|
import 'package:workout_app/services/run_engine.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
|
||||||
|
/// A checkpoint the tests only need to hand around.
|
||||||
|
class FakeCheckpoint implements RunCheckpoint {
|
||||||
|
/// Creates one marked with [tag].
|
||||||
|
FakeCheckpoint(this.tag);
|
||||||
|
|
||||||
|
/// Which snapshot this is.
|
||||||
|
final int tag;
|
||||||
|
|
||||||
|
@override
|
||||||
|
dynamic noSuchMethod(Invocation invocation) => null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records what the host asked of it; the test moves it along.
|
||||||
|
class FakeRunEngine extends ChangeNotifier implements RunEngine {
|
||||||
|
/// Creates an idle engine; [startResult] is what [start] answers.
|
||||||
|
FakeRunEngine({this.startResult = true, this.restoreResult = true});
|
||||||
|
|
||||||
|
/// Answer of [start].
|
||||||
|
bool startResult;
|
||||||
|
|
||||||
|
/// Answer of [restore].
|
||||||
|
bool restoreResult;
|
||||||
|
|
||||||
|
/// How many times [start] ran.
|
||||||
|
int starts = 0;
|
||||||
|
|
||||||
|
/// The checkpoints handed to [restore].
|
||||||
|
final restored = <RunCheckpoint>[];
|
||||||
|
|
||||||
|
/// Whether [dispose] ran.
|
||||||
|
bool disposed = false;
|
||||||
|
|
||||||
|
/// What [finish] returns.
|
||||||
|
RunTrack? track;
|
||||||
|
|
||||||
|
/// Calls in order, for ordering assertions.
|
||||||
|
final calls = <String>[];
|
||||||
|
|
||||||
|
RunPhase _phase = RunPhase.idle;
|
||||||
|
RunIssue _issue = RunIssue.none;
|
||||||
|
final _points = <RunPoint>[];
|
||||||
|
int _checkpoints = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
RunPhase get phase => _phase;
|
||||||
|
|
||||||
|
@override
|
||||||
|
RunIssue get issue => _issue;
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<RunPoint> get points => List.unmodifiable(_points);
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get seconds => _points.length * 2;
|
||||||
|
|
||||||
|
@override
|
||||||
|
double get distanceM => _points.length * 6.0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
int? paceTarget;
|
||||||
|
|
||||||
|
@override
|
||||||
|
double? get pace => null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
PaceBand? get band => null;
|
||||||
|
|
||||||
|
/// Sets the phase and tells the listeners.
|
||||||
|
void setPhase(RunPhase phase, {RunIssue issue = RunIssue.none}) {
|
||||||
|
_phase = phase;
|
||||||
|
_issue = issue;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One accepted fix 6 m further on.
|
||||||
|
void addFix() {
|
||||||
|
final n = _points.length;
|
||||||
|
_points.add(
|
||||||
|
RunPoint(
|
||||||
|
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: n * 2)),
|
||||||
|
latitude: 48.8584 + n * 0.00005,
|
||||||
|
longitude: 2.2945,
|
||||||
|
distanceM: n * 6.0,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
RunCheckpoint? checkpoint() =>
|
||||||
|
_phase.isActive ? FakeCheckpoint(++_checkpoints) : null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> start() async {
|
||||||
|
starts++;
|
||||||
|
calls.add('start');
|
||||||
|
if (!startResult) {
|
||||||
|
setPhase(RunPhase.idle, issue: RunIssue.denied);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
setPhase(RunPhase.recording);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> restore(RunCheckpoint checkpoint) async {
|
||||||
|
restored.add(checkpoint);
|
||||||
|
calls.add('restore');
|
||||||
|
if (!restoreResult) {
|
||||||
|
setPhase(RunPhase.idle, issue: RunIssue.streamError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
setPhase(RunPhase.recording);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void pause() {
|
||||||
|
calls.add('pause');
|
||||||
|
setPhase(RunPhase.paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void resume() {
|
||||||
|
calls.add('resume');
|
||||||
|
setPhase(RunPhase.recording);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setPaceTarget(int? seconds) {
|
||||||
|
paceTarget = seconds;
|
||||||
|
calls.add('pace $seconds');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<RunTrack?> finish() async {
|
||||||
|
calls.add('finish');
|
||||||
|
setPhase(RunPhase.finished);
|
||||||
|
return track;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
disposed = true;
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -100,4 +100,16 @@ class QuietCues extends FeedbackCues {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> workoutFinished() async => finishes++;
|
Future<void> workoutFinished() async => finishes++;
|
||||||
|
|
||||||
|
/// How many times advice to finish was cued.
|
||||||
|
int suggestions = 0;
|
||||||
|
|
||||||
|
/// How many times the 5 h end was cued.
|
||||||
|
int autoEnds = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> finishSuggested() async => suggestions++;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> autoEnded() async => autoEnds++;
|
||||||
}
|
}
|
||||||
|
|||||||
144
stronglift_replacement/workout_app/test/run_host_rig.dart
Normal file
144
stronglift_replacement/workout_app/test/run_host_rig.dart
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
/// A [RunHost] over fakes, with every outward call recorded.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint.dart';
|
||||||
|
import 'package:workout_app/services/run_checkpoint_store.dart';
|
||||||
|
import 'package:workout_app/services/run_engine.dart';
|
||||||
|
import 'package:workout_app/services/run_host.dart';
|
||||||
|
|
||||||
|
import 'fake_run_engine.dart';
|
||||||
|
import 'fake_run_service.dart';
|
||||||
|
import 'run_test_fixtures.dart';
|
||||||
|
|
||||||
|
/// A port that remembers everything.
|
||||||
|
class FakePort implements RunHostPort {
|
||||||
|
/// Messages sent to the UI.
|
||||||
|
final sent = <Map<String, Object?>>[];
|
||||||
|
|
||||||
|
/// Notification redraws as `title|text`.
|
||||||
|
final notes = <String>[];
|
||||||
|
|
||||||
|
/// How often the service was stopped.
|
||||||
|
int stops = 0;
|
||||||
|
|
||||||
|
/// How often the app was brought forward.
|
||||||
|
int launches = 0;
|
||||||
|
|
||||||
|
/// The newest message.
|
||||||
|
Map<String, Object?> get last => sent.last;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void send(Map<String, Object?> message) => sent.add(message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> notify({required String title, required String text}) async =>
|
||||||
|
notes.add('$title|$text');
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> stopService() async => stops++;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void launchApp() => launches++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store in memory that can be told to fail.
|
||||||
|
class FakeStore implements RunCheckpointStore {
|
||||||
|
/// The held checkpoint.
|
||||||
|
RunCheckpoint? held;
|
||||||
|
|
||||||
|
/// Saves that went through.
|
||||||
|
int saves = 0;
|
||||||
|
|
||||||
|
/// Clears.
|
||||||
|
int clears = 0;
|
||||||
|
|
||||||
|
/// Makes [save] throw.
|
||||||
|
bool failSave = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> save(RunCheckpoint c) async {
|
||||||
|
if (failSave) throw Exception('disk full');
|
||||||
|
saves++;
|
||||||
|
held = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<RunCheckpoint?> load() async => held;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> clear() async {
|
||||||
|
clears++;
|
||||||
|
held = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything a host test touches.
|
||||||
|
class HostRig {
|
||||||
|
/// Builds the rig; [save] defaults to "stored".
|
||||||
|
HostRig({
|
||||||
|
this.saveThrows = false,
|
||||||
|
this.saveStores = true,
|
||||||
|
RunHostPort? hostPort,
|
||||||
|
}) {
|
||||||
|
host = RunHost(
|
||||||
|
engineFactory: (hooks) {
|
||||||
|
lastHooks = hooks;
|
||||||
|
final engine = FakeRunEngine(
|
||||||
|
startResult: startResult,
|
||||||
|
restoreResult: restoreResult,
|
||||||
|
)..track = sampleTrack();
|
||||||
|
engines.add(engine);
|
||||||
|
return engine;
|
||||||
|
},
|
||||||
|
port: hostPort ?? port,
|
||||||
|
store: store,
|
||||||
|
cues: cues,
|
||||||
|
save: (track) async {
|
||||||
|
if (saveThrows) throw Exception('db locked');
|
||||||
|
saved.add(track);
|
||||||
|
return (stored: saveStores, reason: 'saved');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the save throws.
|
||||||
|
final bool saveThrows;
|
||||||
|
|
||||||
|
/// What the save answers.
|
||||||
|
final bool saveStores;
|
||||||
|
|
||||||
|
/// What new engines answer to start / restore.
|
||||||
|
bool startResult = true;
|
||||||
|
|
||||||
|
/// See [startResult].
|
||||||
|
bool restoreResult = true;
|
||||||
|
|
||||||
|
/// The host under test.
|
||||||
|
late final RunHost host;
|
||||||
|
|
||||||
|
/// Recorded port.
|
||||||
|
final port = FakePort();
|
||||||
|
|
||||||
|
/// Recorded store.
|
||||||
|
final store = FakeStore();
|
||||||
|
|
||||||
|
/// Recorded cues.
|
||||||
|
final cues = QuietCues();
|
||||||
|
|
||||||
|
/// Tracks the host saved.
|
||||||
|
final saved = <RunTrack>[];
|
||||||
|
|
||||||
|
/// Every engine the host built, oldest first.
|
||||||
|
final engines = <FakeRunEngine>[];
|
||||||
|
|
||||||
|
/// The hooks of the newest engine.
|
||||||
|
late RunEngineHooks lastHooks;
|
||||||
|
|
||||||
|
/// The newest engine.
|
||||||
|
FakeRunEngine get engine => engines.last;
|
||||||
|
|
||||||
|
/// Sends a UI command.
|
||||||
|
Future<void> cmd(String name, [Map<String, Object?> extra = const {}]) =>
|
||||||
|
host.handle({'cmd': name, ...extra});
|
||||||
|
}
|
||||||
110
stronglift_replacement/workout_app/test/run_persist_rig.dart
Normal file
110
stronglift_replacement/workout_app/test/run_persist_rig.dart
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
/// A run screen/controller over the in-process host and a fake engine: the
|
||||||
|
/// run lives in the rig, so a test can throw the screen away and look at it.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart' show WidgetTester;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:workout_app/screens/run_screen.dart';
|
||||||
|
import 'package:workout_app/services/position_source.dart';
|
||||||
|
import 'package:workout_app/services/run_controller.dart';
|
||||||
|
import 'package:workout_app/services/run_link.dart';
|
||||||
|
import 'package:workout_app/ui/theme.dart';
|
||||||
|
|
||||||
|
import 'fake_run_engine.dart';
|
||||||
|
import 'fake_run_service.dart';
|
||||||
|
import 'fake_run_uploader.dart';
|
||||||
|
import 'run_host_rig.dart';
|
||||||
|
import 'run_test_fixtures.dart';
|
||||||
|
import 'screens/_run_screen_helpers.dart';
|
||||||
|
|
||||||
|
/// The in-process host the controllers talk to, shared by every controller
|
||||||
|
/// the rig builds (as the real service is shared by every screen).
|
||||||
|
class PersistRig {
|
||||||
|
/// Creates the rig; [supported] says whether a service exists.
|
||||||
|
PersistRig({bool supported = true})
|
||||||
|
: service = FakeForegroundRunClient(isSupported: supported) {
|
||||||
|
port = LoopbackRunPort(service);
|
||||||
|
host = HostRig(hostPort: port);
|
||||||
|
link = _RigLink(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fake Android service.
|
||||||
|
final FakeForegroundRunClient service;
|
||||||
|
|
||||||
|
/// The host and its recorded collaborators.
|
||||||
|
late final HostRig host;
|
||||||
|
|
||||||
|
/// The port the host would use (loopback to [service]).
|
||||||
|
late final LoopbackRunPort port;
|
||||||
|
|
||||||
|
/// The link every controller gets.
|
||||||
|
late final RunLink link;
|
||||||
|
|
||||||
|
/// Controllers built, oldest first.
|
||||||
|
final controllers = <RunController>[];
|
||||||
|
|
||||||
|
final uploader = FakeRunUploader();
|
||||||
|
final paceStore = MemoryPaceStore();
|
||||||
|
final navigator = GlobalKey<NavigatorState>();
|
||||||
|
|
||||||
|
/// The newest engine.
|
||||||
|
FakeRunEngine get engine => host.engine;
|
||||||
|
|
||||||
|
/// A controller over the shared host and an idle source that grants.
|
||||||
|
RunController build() {
|
||||||
|
final c = RunController(
|
||||||
|
idleSourceFor: ManualPositionSource.new,
|
||||||
|
service: service,
|
||||||
|
link: link,
|
||||||
|
soundOn: () async => true,
|
||||||
|
hostTimeout: const Duration(milliseconds: 200),
|
||||||
|
retryEvery: const Duration(milliseconds: 1),
|
||||||
|
);
|
||||||
|
controllers.add(c);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A screen over [build].
|
||||||
|
RunScreen screen({bool resuming = false}) => RunScreen(
|
||||||
|
controllerFactory: build,
|
||||||
|
uploader: uploader,
|
||||||
|
paceStore: paceStore,
|
||||||
|
mapBuilder: fakeTileMap,
|
||||||
|
resuming: resuming,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Pumps an app with the run screen pushed on an empty route.
|
||||||
|
Future<void> pump(WidgetTester tester, {bool resuming = false}) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
navigatorKey: navigator,
|
||||||
|
theme: buildAppTheme(),
|
||||||
|
home: const SizedBox(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
navigator.currentState!.push(
|
||||||
|
MaterialPageRoute<void>(builder: (_) => screen(resuming: resuming)),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends commands to the rig's host and relays its snapshots.
|
||||||
|
class _RigLink implements RunLink {
|
||||||
|
_RigLink(this._rig);
|
||||||
|
|
||||||
|
final PersistRig _rig;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Map<Object?, Object?>> get messages => _rig.port.messages;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void send(Map<String, Object?> command) => unawaited(
|
||||||
|
_rig.host.host.handle(command),
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close() async {}
|
||||||
|
}
|
||||||
@ -20,35 +20,6 @@ import '../fake_run_uploader.dart';
|
|||||||
import '../run_test_fixtures.dart';
|
import '../run_test_fixtures.dart';
|
||||||
import '../widgets/_run_map_fixtures.dart';
|
import '../widgets/_run_map_fixtures.dart';
|
||||||
|
|
||||||
/// An in-memory [PaceTargetStore].
|
|
||||||
class MemoryPaceStore implements PaceTargetStore {
|
|
||||||
/// The stored target.
|
|
||||||
int value = kDefaultPaceTarget;
|
|
||||||
|
|
||||||
/// How many times [save] ran.
|
|
||||||
int saves = 0;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<int> load() async => value;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> save(int seconds) async {
|
|
||||||
saves++;
|
|
||||||
value = seconds;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The real map slot over fake tiles, so nothing reaches the network.
|
|
||||||
Widget fakeTileMap(
|
|
||||||
BuildContext context,
|
|
||||||
ValueListenable<List<RunPoint>> points,
|
|
||||||
ValueListenable<LatLng?> position,
|
|
||||||
) => RunMapSlot(
|
|
||||||
points: points,
|
|
||||||
position: position,
|
|
||||||
tileProviderOpener: fakeTiles(),
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Everything a test needs to drive and inspect one screen.
|
/// Everything a test needs to drive and inspect one screen.
|
||||||
class RunHarness {
|
class RunHarness {
|
||||||
RunHarness({
|
RunHarness({
|
||||||
@ -125,14 +96,3 @@ class RunHarness {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Finder key(String id) => find.byKey(Key(id));
|
|
||||||
|
|
||||||
Future<void> tapKey(WidgetTester tester, String id) async {
|
|
||||||
await tester.tap(key(id));
|
|
||||||
// Stream cancel only completes on the real event loop, so give it a turn
|
|
||||||
// before settling the frames.
|
|
||||||
await tester.runAsync(
|
|
||||||
() => Future<void>.delayed(const Duration(milliseconds: 10)),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
}
|
|
||||||
|
|||||||
@ -0,0 +1,53 @@
|
|||||||
|
// Pieces of the run screen harness that do not need a recorder.
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:latlong2/latlong.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:workout_app/models/run_track.dart';
|
||||||
|
import 'package:workout_app/services/pace_target_store.dart';
|
||||||
|
import 'package:workout_app/widgets/run_map_slot.dart';
|
||||||
|
|
||||||
|
import '../widgets/_run_map_fixtures.dart';
|
||||||
|
|
||||||
|
/// An in-memory [PaceTargetStore].
|
||||||
|
class MemoryPaceStore implements PaceTargetStore {
|
||||||
|
/// The stored target.
|
||||||
|
int value = kDefaultPaceTarget;
|
||||||
|
|
||||||
|
/// How many times [save] ran.
|
||||||
|
int saves = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<int> load() async => value;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> save(int seconds) async {
|
||||||
|
saves++;
|
||||||
|
value = seconds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The real map slot over fake tiles, so nothing reaches the network.
|
||||||
|
Widget fakeTileMap(
|
||||||
|
BuildContext context,
|
||||||
|
ValueListenable<List<RunPoint>> points,
|
||||||
|
ValueListenable<LatLng?> position,
|
||||||
|
) => RunMapSlot(
|
||||||
|
points: points,
|
||||||
|
position: position,
|
||||||
|
tileProviderOpener: fakeTiles(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Finder key(String id) => find.byKey(Key(id));
|
||||||
|
|
||||||
|
Future<void> tapKey(WidgetTester tester, String id) async {
|
||||||
|
await tester.tap(key(id));
|
||||||
|
// Stream cancel only completes on the real event loop, so give it a turn
|
||||||
|
// before settling the frames.
|
||||||
|
await tester.runAsync(
|
||||||
|
() => Future<void>.delayed(const Duration(milliseconds: 10)),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
@ -11,6 +11,7 @@ import 'package:workout_app/services/storage_service.dart';
|
|||||||
import '../fake_audio_platform.dart';
|
import '../fake_audio_platform.dart';
|
||||||
import '../fake_geolocator.dart';
|
import '../fake_geolocator.dart';
|
||||||
import '../fake_secure_storage.dart';
|
import '../fake_secure_storage.dart';
|
||||||
|
import '../run_persist_rig.dart';
|
||||||
import '_home_test_fixtures.dart';
|
import '_home_test_fixtures.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
@ -31,6 +32,9 @@ void main() {
|
|||||||
final original = GeolocatorPlatform.instance;
|
final original = GeolocatorPlatform.instance;
|
||||||
GeolocatorPlatform.instance = FakeGeolocator();
|
GeolocatorPlatform.instance = FakeGeolocator();
|
||||||
addTearDown(() => GeolocatorPlatform.instance = original);
|
addTearDown(() => GeolocatorPlatform.instance = original);
|
||||||
|
// `main` installs the real wiring; here the run lives in a fake host.
|
||||||
|
RunScreen.defaultControllerFactory = PersistRig().build;
|
||||||
|
addTearDown(() => RunScreen.defaultControllerFactory = null);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('the run icon opens the run screen and back returns home', (
|
testWidgets('the run icon opens the run screen and back returns home', (
|
||||||
|
|||||||
@ -0,0 +1,71 @@
|
|||||||
|
// (c) A run in progress opens the app on the live run screen.
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
||||||
|
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||||
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||||
|
import 'package:workout_app/screens/home_screen.dart';
|
||||||
|
import 'package:workout_app/screens/run_screen.dart';
|
||||||
|
import 'package:workout_app/services/storage_service.dart';
|
||||||
|
import 'package:workout_app/ui/theme.dart';
|
||||||
|
|
||||||
|
import '../fake_audio_platform.dart';
|
||||||
|
import '../fake_secure_storage.dart';
|
||||||
|
import '../run_persist_rig.dart';
|
||||||
|
import '_home_test_fixtures.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUpAll(() {
|
||||||
|
sqfliteFfiInit();
|
||||||
|
databaseFactory = databaseFactoryFfi;
|
||||||
|
});
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
SharedPreferencesAsyncPlatform.instance =
|
||||||
|
InMemorySharedPreferencesAsync.empty();
|
||||||
|
StorageService.resetForTesting();
|
||||||
|
await StorageService.init();
|
||||||
|
installFakeSecureStorage();
|
||||||
|
installFakeAudioPlatform();
|
||||||
|
});
|
||||||
|
|
||||||
|
Widget app({required bool openRun, bool openWorkout = false}) => MaterialApp(
|
||||||
|
theme: buildAppTheme(),
|
||||||
|
home: HomeScreen(
|
||||||
|
configuredProbe: () async => false,
|
||||||
|
clock: () => DateTime(2026, 8, 15, 18),
|
||||||
|
openWorkoutOnLaunch: openWorkout,
|
||||||
|
openRunOnLaunch: openRun,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('a cold start with a run owed lands on the run screen', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
RunScreen.defaultControllerFactory = rig.build;
|
||||||
|
addTearDown(() => RunScreen.defaultControllerFactory = null);
|
||||||
|
await rig.host.cmd('start'); // the host restored the run
|
||||||
|
rig.engine.addFix();
|
||||||
|
|
||||||
|
await pumpHome(tester, app(openRun: true, openWorkout: true));
|
||||||
|
await tester.pump(const Duration(milliseconds: 400));
|
||||||
|
|
||||||
|
expect(find.byType(RunScreen), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('run_pause')), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('run_start')), findsNothing);
|
||||||
|
// The workout did not open over it, and back does nothing.
|
||||||
|
await tester.binding.handlePopRoute();
|
||||||
|
await tester.pump(const Duration(milliseconds: 400));
|
||||||
|
expect(find.byType(RunScreen), findsOneWidget);
|
||||||
|
await tester.runAsync(
|
||||||
|
() => Future<void>.delayed(const Duration(milliseconds: 300)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('with no run owed home shows as before', (tester) async {
|
||||||
|
await pumpHome(tester, app(openRun: false));
|
||||||
|
expect(find.byType(RunScreen), findsNothing);
|
||||||
|
expect(find.byKey(const Key('home_run')), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,266 @@
|
|||||||
|
// The run outlives the screen: nothing but the finish button plus its confirm
|
||||||
|
// modal ends it. Checks (a) leaving or replacing the screen never stops an
|
||||||
|
// active run, (b) finishing needs the modal's red check, (c) the app opens on
|
||||||
|
// the live run.
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
import 'package:workout_app/screens/run_screen.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
import 'package:workout_app/widgets/run_landing.dart';
|
||||||
|
|
||||||
|
import '../fake_audio_platform.dart';
|
||||||
|
import '../run_persist_rig.dart';
|
||||||
|
import '_run_screen_helpers.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(installFakeAudioPlatform);
|
||||||
|
|
||||||
|
Future<void> startRun(WidgetTester tester, PersistRig rig) async {
|
||||||
|
await tapKey(tester, 'run_start');
|
||||||
|
rig.engine.addFix();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
|
||||||
|
group('(a) the run outlives the screen', () {
|
||||||
|
testWidgets('disposing the screen leaves the run recording', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
final engine = rig.engine;
|
||||||
|
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.byType(RunScreen), findsNothing);
|
||||||
|
expect(engine.phase, RunPhase.recording);
|
||||||
|
expect(engine.disposed, isFalse);
|
||||||
|
expect(rig.service.calls, isNot(contains('stop')));
|
||||||
|
expect(rig.host.saved, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('back and pop do nothing while recording or paused', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
|
||||||
|
await tester.binding.handlePopRoute();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(RunScreen), findsOneWidget);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_pause');
|
||||||
|
await tester.binding.handlePopRoute();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(RunScreen), findsOneWidget);
|
||||||
|
expect(rig.engine.phase, RunPhase.paused);
|
||||||
|
expect(rig.service.calls, isNot(contains('stop')));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a second screen finds the run and cannot restart it', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
final engine = rig.engine;
|
||||||
|
|
||||||
|
// The system closed the screen; the app opens a new one.
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
await rig.pump(tester, resuming: true);
|
||||||
|
|
||||||
|
expect(key('run_pause'), findsOneWidget, reason: 'live run, not idle');
|
||||||
|
expect(key('run_start'), findsNothing);
|
||||||
|
// A start command from the new controller is refused by the host.
|
||||||
|
await rig.controllers.last.start();
|
||||||
|
expect(rig.host.engines, hasLength(1));
|
||||||
|
expect(engine.starts, 1);
|
||||||
|
expect(engine.phase, RunPhase.recording);
|
||||||
|
expect(rig.service.calls, isNot(contains('stop')));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('"new run" cannot replace a run that is still going', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
final engine = rig.engine;
|
||||||
|
|
||||||
|
// A rebuilt controller (what "new run" makes) asking to start.
|
||||||
|
final second = rig.build();
|
||||||
|
await second.attach();
|
||||||
|
await second.start();
|
||||||
|
|
||||||
|
expect(rig.host.engines, hasLength(1));
|
||||||
|
expect(engine.phase, RunPhase.recording);
|
||||||
|
expect(engine.disposed, isFalse);
|
||||||
|
second.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('(b) finishing needs the modal', () {
|
||||||
|
testWidgets('the finish button asks, the cross keeps recording', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_finish');
|
||||||
|
expect(key('run_finish_dialog'), findsOneWidget);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_finish_cancel');
|
||||||
|
expect(key('run_finish_dialog'), findsNothing);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(rig.host.saved, isEmpty);
|
||||||
|
expect(key('run_pause'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('tapping outside or pressing back cancels', (tester) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_finish');
|
||||||
|
await tester.binding.handlePopRoute();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(key('run_finish_dialog'), findsNothing);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_finish');
|
||||||
|
await tester.tapAt(const Offset(2, 2));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(key('run_finish_dialog'), findsNothing);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the red check ends and saves the run', (tester) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_finish');
|
||||||
|
await tapKey(tester, 'run_finish_confirm');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(rig.engine.phase, RunPhase.finished);
|
||||||
|
expect(rig.host.saved, hasLength(1));
|
||||||
|
expect(key('run_saved_ok'), findsOneWidget);
|
||||||
|
expect(rig.service.calls.last, 'stop');
|
||||||
|
expect(key('run_again'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the modal shows icons only, no words', (tester) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
await tapKey(tester, 'run_finish');
|
||||||
|
|
||||||
|
final dialog = find.byKey(const Key('run_finish_dialog'));
|
||||||
|
expect(
|
||||||
|
find.descendant(of: dialog, matching: find.byType(Text)),
|
||||||
|
findsNothing,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
find.descendant(of: dialog, matching: find.byIcon(Icons.check)),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
find.descendant(of: dialog, matching: find.byIcon(Icons.close)),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('advice makes the finish button pulse, nothing more', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
expect(key('run_finish_still'), findsOneWidget);
|
||||||
|
|
||||||
|
rig.host.lastHooks.onSuggest('stationary');
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
expect(key('run_finish_pulse'), findsOneWidget);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(key('run_finish_dialog'), findsNothing);
|
||||||
|
expect(rig.host.saved, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a notification tap on advice opens the modal, still unconfirmed', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
await rig.pump(tester);
|
||||||
|
await startRun(tester, rig);
|
||||||
|
rig.host.lastHooks.onSuggest('gpsLost');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
rig.host.host.notificationPressed();
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(key('run_finish_dialog'), findsOneWidget);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
|
||||||
|
await tapKey(tester, 'run_finish_cancel');
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(key('run_finish_dialog'), findsNothing);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('(c) the app opens on the run', () {
|
||||||
|
testWidgets('coming back to the front lands on the run again', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final rig = PersistRig();
|
||||||
|
RunScreen.defaultControllerFactory = rig.build;
|
||||||
|
addTearDown(() => RunScreen.defaultControllerFactory = null);
|
||||||
|
await rig.host.cmd('start');
|
||||||
|
var owed = false;
|
||||||
|
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: RunLanding(
|
||||||
|
owed: () async => owed,
|
||||||
|
child: const SizedBox(key: Key('home')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(RunScreen), findsNothing);
|
||||||
|
|
||||||
|
owed = true;
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(RunScreen), findsOneWidget);
|
||||||
|
|
||||||
|
// Already on the run: another resume does not stack a second one.
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.binding.handlePopRoute();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(RunScreen), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('with no run owed home stays home', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: RunLanding(
|
||||||
|
owed: () async => false,
|
||||||
|
child: const SizedBox(key: Key('home')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(key('home'), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,326 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
import 'package:workout_app/services/run_wire.dart';
|
||||||
|
|
||||||
|
import '../fake_audio_platform.dart';
|
||||||
|
import '../fake_run_engine.dart';
|
||||||
|
import '../run_host_rig.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(installFakeAudioPlatform);
|
||||||
|
|
||||||
|
group('start', () {
|
||||||
|
test('builds an engine, records, and tells the UI', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start, {'paceTarget': 330, 'sound': false});
|
||||||
|
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(rig.engine.paceTarget, 330);
|
||||||
|
expect(rig.cues.soundOn, isFalse);
|
||||||
|
expect(rig.port.last['phase'], 'recording');
|
||||||
|
expect(rig.port.last['from'], 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a second start never restarts a live run', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine.addFix();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
|
||||||
|
expect(rig.engines, hasLength(1));
|
||||||
|
expect(rig.engine.starts, 1);
|
||||||
|
expect(rig.engine.disposed, isFalse);
|
||||||
|
expect(rig.port.last['total'], 1);
|
||||||
|
expect(rig.port.last['from'], 0, reason: 'a re-sync sends it all');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a refused start leaves the issue for the UI', () async {
|
||||||
|
final rig = HostRig()..startResult = false;
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
|
||||||
|
expect(rig.port.last['phase'], 'idle');
|
||||||
|
expect(rig.port.last['issue'], 'denied');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a start after a finished run builds a fresh engine', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
await rig.cmd(RunCmd.finish);
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
|
||||||
|
expect(rig.engines, hasLength(2));
|
||||||
|
expect(rig.engines.first.disposed, isTrue);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(rig.port.last['done'], isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('snapshots', () {
|
||||||
|
test('send only the new points, hello sends all', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine
|
||||||
|
..addFix()
|
||||||
|
..addFix();
|
||||||
|
expect(rig.port.last['from'], 1);
|
||||||
|
expect(rig.port.last['pts'], hasLength(1));
|
||||||
|
|
||||||
|
await rig.cmd(RunCmd.hello);
|
||||||
|
expect(rig.port.last['from'], 0);
|
||||||
|
expect(rig.port.last['pts'], hasLength(2));
|
||||||
|
expect(isRunMessage(rig.port.last), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hello with no run answers idle', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.hello);
|
||||||
|
expect(rig.port.last['phase'], 'idle');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('checkpoint and notification', () {
|
||||||
|
test('every change of an active run is saved and redrawn', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine
|
||||||
|
..addFix()
|
||||||
|
..addFix();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.store.saves, greaterThanOrEqualTo(3));
|
||||||
|
expect(rig.port.notes, isNotEmpty);
|
||||||
|
final redraws = rig.port.notes.length;
|
||||||
|
rig.engine.notifyListeners();
|
||||||
|
expect(rig.port.notes, hasLength(redraws), reason: 'same words');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pause and resume are saved too', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
await pumpEventQueue();
|
||||||
|
final before = rig.store.saves;
|
||||||
|
await rig.cmd(RunCmd.pause);
|
||||||
|
await rig.cmd(RunCmd.resume);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.engine.calls, containsAllInOrder(['pause', 'resume']));
|
||||||
|
expect(rig.store.saves, before + 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed checkpoint write is logged, not fatal', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
rig.store.failSave = true;
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine.addFix();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a pace target change goes to the engine', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
await rig.cmd(RunCmd.paceTarget, {'paceTarget': 300});
|
||||||
|
expect(rig.engine.paceTarget, 300);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('finish', () {
|
||||||
|
test('saves, clears the checkpoint, cues and stops the service', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine.addFix();
|
||||||
|
await rig.cmd(RunCmd.finish);
|
||||||
|
|
||||||
|
expect(rig.saved, hasLength(1));
|
||||||
|
expect(rig.store.held, isNull);
|
||||||
|
expect(rig.cues.finishes, 1);
|
||||||
|
expect(rig.port.stops, 1);
|
||||||
|
expect(rig.port.last['done'], isTrue);
|
||||||
|
expect(rig.port.last['saved'], {'stored': true, 'reason': 'saved'});
|
||||||
|
expect(rig.port.sent.any((m) => m['saving'] == true), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a refused save (duplicate) still ends the run cleanly', () async {
|
||||||
|
final rig = HostRig(saveStores: false);
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
await rig.cmd(RunCmd.finish);
|
||||||
|
|
||||||
|
expect(rig.store.held, isNull);
|
||||||
|
expect(rig.port.last['saved'], {'stored': false, 'reason': 'saved'});
|
||||||
|
expect(rig.port.stops, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a save that throws keeps the checkpoint', () async {
|
||||||
|
final rig = HostRig(saveThrows: true);
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
await pumpEventQueue();
|
||||||
|
await rig.cmd(RunCmd.finish);
|
||||||
|
|
||||||
|
expect(rig.store.held, isNotNull);
|
||||||
|
expect(rig.port.last['saved'], {
|
||||||
|
'stored': false,
|
||||||
|
'reason': 'save failed: Exception: db locked',
|
||||||
|
});
|
||||||
|
expect(rig.port.last['done'], isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('too few fixes: nothing saved, checkpoint cleared', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine.track = null;
|
||||||
|
await rig.cmd(RunCmd.finish);
|
||||||
|
|
||||||
|
expect(rig.saved, isEmpty);
|
||||||
|
expect(rig.store.held, isNull);
|
||||||
|
expect(rig.port.last['saved'], isNull);
|
||||||
|
expect(rig.port.last['done'], isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('finishing with no active run does nothing', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.finish);
|
||||||
|
expect(rig.saved, isEmpty);
|
||||||
|
expect(rig.port.stops, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('finishing twice at once saves once', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
await Future.wait([rig.cmd(RunCmd.finish), rig.cmd(RunCmd.finish)]);
|
||||||
|
expect(rig.saved, hasLength(1));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('suggestions never end the run', () {
|
||||||
|
test('cue, glyph in the notification, run keeps recording', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine.addFix();
|
||||||
|
rig.lastHooks.onSuggest('stationary');
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.cues.suggestions, 1);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(rig.port.last['suggestion'], 'stationary');
|
||||||
|
expect(rig.port.notes.last, startsWith('⏸ '));
|
||||||
|
expect(rig.saved, isEmpty);
|
||||||
|
expect(rig.port.stops, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each reason has its own symbol', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
for (final (why, glyph) in [
|
||||||
|
('vehicleSpeed', '⚡'),
|
||||||
|
('gpsLost', '⌖'),
|
||||||
|
('restored', '↻'),
|
||||||
|
]) {
|
||||||
|
rig.lastHooks.onSuggest(why);
|
||||||
|
rig.engine.addFix();
|
||||||
|
expect(rig.port.notes.last, startsWith('$glyph '), reason: why);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a tap on the notification asks for the finish modal', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.lastHooks.onSuggest('gpsLost');
|
||||||
|
rig.host.notificationPressed();
|
||||||
|
|
||||||
|
expect(rig.port.launches, 1);
|
||||||
|
expect(rig.port.last['prompt'], isTrue);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording, reason: 'still needs a tap');
|
||||||
|
|
||||||
|
await rig.cmd(RunCmd.ackPrompt);
|
||||||
|
expect(rig.port.last['prompt'], isFalse);
|
||||||
|
expect(rig.port.last['suggestion'], 'gpsLost');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a tap with no advice only opens the app', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.host.notificationPressed();
|
||||||
|
expect(rig.port.launches, 1);
|
||||||
|
expect(rig.port.last['prompt'], isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('advice while finishing is dropped', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
final finishing = rig.cmd(RunCmd.finish);
|
||||||
|
rig.lastHooks.onSuggest('stationary');
|
||||||
|
await finishing;
|
||||||
|
expect(rig.cues.suggestions, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('5 h auto end', () {
|
||||||
|
test('saves like a finish and plays its own cue', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.engine.addFix();
|
||||||
|
rig.lastHooks.onAutoEnd();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.saved, hasLength(1));
|
||||||
|
expect(rig.cues.autoEnds, 1);
|
||||||
|
expect(rig.cues.finishes, 0);
|
||||||
|
expect(rig.store.held, isNull);
|
||||||
|
expect(rig.port.stops, 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('hooks', () {
|
||||||
|
test('kilometres and pace cues reach the cues', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.lastHooks.onKilometre(1);
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(rig.cues.kilometres, [1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('restoreFromStore', () {
|
||||||
|
test('false with no checkpoint, and no engine is built', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
expect(await rig.host.restoreFromStore(), isFalse);
|
||||||
|
expect(rig.engines, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('resumes the run and tells the UI', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
rig.store.held = FakeCheckpoint(7);
|
||||||
|
expect(await rig.host.restoreFromStore(), isTrue);
|
||||||
|
|
||||||
|
expect(rig.engine.restored.single, isA<FakeCheckpoint>());
|
||||||
|
expect(rig.port.last['phase'], 'recording');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a checkpoint that cannot resume is kept and the issue shown', () async {
|
||||||
|
final rig = HostRig()..restoreResult = false;
|
||||||
|
rig.store.held = FakeCheckpoint(7);
|
||||||
|
expect(await rig.host.restoreFromStore(), isTrue);
|
||||||
|
|
||||||
|
expect(rig.store.held, isNotNull);
|
||||||
|
expect(rig.port.last['issue'], 'streamError');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unknown commands are ignored', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd('nonsense');
|
||||||
|
expect(rig.engines, isEmpty);
|
||||||
|
expect(rig.port.sent, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dispose lets go without ending anything', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await rig.cmd(RunCmd.start);
|
||||||
|
rig.host.dispose();
|
||||||
|
expect(rig.engine.disposed, isTrue);
|
||||||
|
expect(rig.saved, isEmpty);
|
||||||
|
expect(rig.store.clears, 0);
|
||||||
|
rig.host.dispose();
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,92 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
import 'package:workout_app/services/run_task_handler.dart';
|
||||||
|
import 'package:workout_app/services/run_wire.dart';
|
||||||
|
|
||||||
|
import '../fake_audio_platform.dart';
|
||||||
|
import '../fake_run_engine.dart';
|
||||||
|
import '../run_host_rig.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(installFakeAudioPlatform);
|
||||||
|
|
||||||
|
RunTaskHandler handlerFor(HostRig rig) =>
|
||||||
|
RunTaskHandler(host: rig.host, port: rig.port);
|
||||||
|
|
||||||
|
group('onStart', () {
|
||||||
|
test('a system start with a checkpoint resumes the run', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
rig.store.held = FakeCheckpoint(1);
|
||||||
|
await handlerFor(rig).onStart(startedBySystem: true);
|
||||||
|
|
||||||
|
expect(rig.engine.restored, hasLength(1));
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
expect(rig.port.stops, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an app start with a checkpoint resumes it too (force-stop)', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
rig.store.held = FakeCheckpoint(1);
|
||||||
|
await handlerFor(rig).onStart(startedBySystem: false);
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a system start with no checkpoint stops itself', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await handlerFor(rig).onStart(startedBySystem: true);
|
||||||
|
|
||||||
|
expect(rig.port.stops, 1);
|
||||||
|
expect(rig.engines, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an app start with no checkpoint waits for the start command', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
await handlerFor(rig).onStart(startedBySystem: false);
|
||||||
|
|
||||||
|
expect(rig.port.stops, 0);
|
||||||
|
expect(rig.engines, isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('messages', () {
|
||||||
|
test('run commands reach the host', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
final handler = handlerFor(rig)
|
||||||
|
..onReceiveData({'cmd': RunCmd.start});
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.engine.phase, RunPhase.recording);
|
||||||
|
handler.onReceiveData({'cmd': RunCmd.pause});
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(rig.engine.phase, RunPhase.paused);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a break-service message is ignored', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
handlerFor(rig)
|
||||||
|
..onReceiveData({'workoutType': 'A', 'restEndsAtMs': 5})
|
||||||
|
..onReceiveData('nudge');
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(rig.engines, isEmpty);
|
||||||
|
expect(rig.port.sent, isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a notification tap goes to the host', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
handlerFor(rig).onNotificationPressed();
|
||||||
|
expect(rig.port.launches, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('destroy lets go and never ends the run', () async {
|
||||||
|
final rig = HostRig();
|
||||||
|
final handler = handlerFor(rig)..onReceiveData({'cmd': RunCmd.start});
|
||||||
|
await pumpEventQueue();
|
||||||
|
handler.onDestroy();
|
||||||
|
|
||||||
|
expect(rig.engine.disposed, isTrue);
|
||||||
|
expect(rig.saved, isEmpty);
|
||||||
|
expect(rig.store.clears, 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,181 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:workout_app/services/pace_band.dart';
|
||||||
|
import 'package:workout_app/services/position_source.dart';
|
||||||
|
import 'package:workout_app/services/run_phase.dart';
|
||||||
|
import 'package:workout_app/services/run_view.dart';
|
||||||
|
import 'package:workout_app/services/run_wire.dart';
|
||||||
|
|
||||||
|
import '../fake_run_engine.dart';
|
||||||
|
|
||||||
|
Map<String, Object?> snapshot(
|
||||||
|
FakeRunEngine engine, {
|
||||||
|
int from = 0,
|
||||||
|
String? suggestion,
|
||||||
|
bool prompt = false,
|
||||||
|
bool done = false,
|
||||||
|
({bool stored, String reason})? saved,
|
||||||
|
}) => encodeSnapshot(
|
||||||
|
engine,
|
||||||
|
from: from,
|
||||||
|
suggestion: suggestion,
|
||||||
|
prompt: prompt,
|
||||||
|
done: done,
|
||||||
|
saved: saved,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a snapshot fills every field', () {
|
||||||
|
final engine = FakeRunEngine()
|
||||||
|
..paceTarget = 330
|
||||||
|
..setPhase(RunPhase.recording)
|
||||||
|
..addFix()
|
||||||
|
..addFix();
|
||||||
|
final view = RunView()
|
||||||
|
..apply(
|
||||||
|
snapshot(
|
||||||
|
engine,
|
||||||
|
suggestion: 'gpsLost',
|
||||||
|
prompt: true,
|
||||||
|
done: true,
|
||||||
|
saved: (stored: true, reason: 'ok'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(view.phase, RunPhase.recording);
|
||||||
|
expect(view.seconds, 4);
|
||||||
|
expect(view.distanceM, 12);
|
||||||
|
expect(view.paceTarget, 330);
|
||||||
|
expect(view.pace, isNull);
|
||||||
|
expect(view.band, isNull);
|
||||||
|
expect(view.suggestion, 'gpsLost');
|
||||||
|
expect(view.promptFinish, isTrue);
|
||||||
|
expect(view.done, isTrue);
|
||||||
|
expect(view.saved, (stored: true, reason: 'ok'));
|
||||||
|
expect(view.synced, isTrue);
|
||||||
|
expect(view.livePoints.value, hasLength(2));
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a band name decodes', () {
|
||||||
|
final view = RunView();
|
||||||
|
final message = snapshot(FakeRunEngine())..['band'] = PaceBand.onPace.name;
|
||||||
|
view.apply(message);
|
||||||
|
expect(view.band, PaceBand.onPace);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
group('points', () {
|
||||||
|
test('an increment appends', () {
|
||||||
|
final engine = FakeRunEngine()
|
||||||
|
..setPhase(RunPhase.recording)
|
||||||
|
..addFix();
|
||||||
|
final view = RunView()..apply(snapshot(engine));
|
||||||
|
engine.addFix();
|
||||||
|
view.apply(snapshot(engine, from: 1));
|
||||||
|
|
||||||
|
expect(view.livePoints.value, hasLength(2));
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a gap asks for everything again', () {
|
||||||
|
final engine = FakeRunEngine()..setPhase(RunPhase.recording);
|
||||||
|
var asked = 0;
|
||||||
|
final view = RunView()
|
||||||
|
..onNeedSync = () {
|
||||||
|
asked++;
|
||||||
|
}
|
||||||
|
..apply(snapshot(engine));
|
||||||
|
engine
|
||||||
|
..addFix()
|
||||||
|
..addFix()
|
||||||
|
..addFix();
|
||||||
|
view.apply(snapshot(engine, from: 2));
|
||||||
|
|
||||||
|
expect(asked, 1);
|
||||||
|
expect(view.livePoints.value, isEmpty);
|
||||||
|
|
||||||
|
view.apply(snapshot(engine));
|
||||||
|
expect(view.livePoints.value, hasLength(3));
|
||||||
|
expect(asked, 1);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a count that does not add up asks again', () {
|
||||||
|
final engine = FakeRunEngine()
|
||||||
|
..setPhase(RunPhase.recording)
|
||||||
|
..addFix();
|
||||||
|
var asked = 0;
|
||||||
|
final view = RunView()..onNeedSync = () {
|
||||||
|
asked++;
|
||||||
|
};
|
||||||
|
final message = snapshot(engine)..['total'] = 5;
|
||||||
|
view.apply(message);
|
||||||
|
expect(asked, 1);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a new run replaces the old points', () {
|
||||||
|
final engine = FakeRunEngine()
|
||||||
|
..setPhase(RunPhase.recording)
|
||||||
|
..addFix()
|
||||||
|
..addFix();
|
||||||
|
final view = RunView()..apply(snapshot(engine));
|
||||||
|
final fresh = FakeRunEngine()..setPhase(RunPhase.recording);
|
||||||
|
view.apply(snapshot(fresh));
|
||||||
|
expect(view.livePoints.value, isEmpty);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('access', () {
|
||||||
|
test('a refusal becomes the issue while idle', () {
|
||||||
|
final view = RunView()..noteAccess(LocationAccess.deniedForever);
|
||||||
|
expect(view.issue, RunIssue.deniedForever);
|
||||||
|
view.noteAccess(LocationAccess.granted);
|
||||||
|
expect(view.issue, RunIssue.none);
|
||||||
|
view.noteAccess(LocationAccess.granted);
|
||||||
|
expect(view.issue, RunIssue.none);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an idle host answer does not wipe the UI refusal', () {
|
||||||
|
final view = RunView()..noteAccess(LocationAccess.denied);
|
||||||
|
view.apply(snapshot(FakeRunEngine()));
|
||||||
|
expect(view.issue, RunIssue.denied);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a run is never touched by an access check', () {
|
||||||
|
final engine = FakeRunEngine()..setPhase(RunPhase.recording);
|
||||||
|
final view = RunView()
|
||||||
|
..apply(snapshot(engine))
|
||||||
|
..noteAccess(LocationAccess.denied);
|
||||||
|
expect(view.issue, RunIssue.none);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a host issue while idle shows', () {
|
||||||
|
final engine = FakeRunEngine()
|
||||||
|
..setPhase(RunPhase.idle, issue: RunIssue.denied);
|
||||||
|
final view = RunView()..apply(snapshot(engine));
|
||||||
|
expect(view.issue, RunIssue.denied);
|
||||||
|
view.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wire points round-trip with and without altitude', () {
|
||||||
|
final engine = FakeRunEngine()..addFix();
|
||||||
|
final point = engine.points.single;
|
||||||
|
expect(decodePoint(encodePoint(point)), point);
|
||||||
|
final withAltitude = decodePoint([
|
||||||
|
0,
|
||||||
|
1.5,
|
||||||
|
2.5,
|
||||||
|
3,
|
||||||
|
40.0,
|
||||||
|
]);
|
||||||
|
expect(withAltitude.altitudeM, 40);
|
||||||
|
expect(isRunMessage({'cmd': 'x'}), isFalse);
|
||||||
|
expect(isRunMessage('x'), isFalse);
|
||||||
|
});
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user