From 172f33df567450793b1f3ff78a8f43c91d4616a0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 5 Oct 2026 15:54:55 +0200 Subject: [PATCH 01/28] Use stronger haptic when the gym mode rest countdown ends --- lib/features/routines/widgets/gym_mode/timer.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index 5cd171fa7..4310a613b 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -134,7 +134,9 @@ class _TimerCountdownWidgetState extends ConsumerState { // When countdown finishes, notify ONCE, and respect settings if (remainingSeconds == 0 && !_hasNotified) { if (gymState.alertOnCountdownEnd) { - HapticFeedback.mediumImpact(); + // Strongest built-in haptic on both platforms (iOS: full vibration, + // Android: LONG_PRESS). heavyImpact maps to a weak tick on Android. + HapticFeedback.vibrate(); // Not that this only works on desktop platforms SystemSound.play(SystemSoundType.alert); From 016568b6b720f0a2dae5d299ffd49ac7f3715416 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 5 Oct 2026 19:32:01 +0200 Subject: [PATCH 02/28] Track the rest period in the gym mode state --- .../routines/providers/gym_state.dart | 26 ++++ .../providers/gym_state_notifier.dart | 25 ++++ .../routines/widgets/gym_mode/gym_mode.dart | 10 +- .../routines/providers/gym_state_test.dart | 124 ++++++++++++++++++ 4 files changed, 178 insertions(+), 7 deletions(-) diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index e77cc1dcd..dee42f3a5 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -176,6 +176,12 @@ class GymModeState { final DateTime workoutStart; final DateTime validUntil; + /// When the rest on the current timer page started, null on other pages + final DateTime? restStartedAt; + + /// When the countdown on the current timer page ends, null if it counts up + final DateTime? restEndsAt; + // User settings final bool showExercisePages; final bool showTimerPages; @@ -195,6 +201,8 @@ class GymModeState { this.isInitialized = false, this.pages = const [], this.currentPage = 0, + this.restStartedAt, + this.restEndsAt, this.showExercisePages = true, this.showTimerPages = true, @@ -231,6 +239,11 @@ class GymModeState { List? pages, int? currentPage, + // Rest data. clearRest drops both rest fields before the passed ones apply + DateTime? restStartedAt, + DateTime? restEndsAt, + bool clearRest = false, + // Routine data int? dayId, int? iteration, @@ -253,6 +266,8 @@ class GymModeState { isInitialized: isInitialized ?? this.isInitialized, pages: pages ?? this.pages, currentPage: currentPage ?? this.currentPage, + restStartedAt: restStartedAt ?? (clearRest ? null : this.restStartedAt), + restEndsAt: restEndsAt ?? (clearRest ? null : this.restEndsAt), dayId: dayId ?? this.dayId, iteration: iteration ?? this.iteration, @@ -276,6 +291,15 @@ class GymModeState { /// The start of the workout as a [TimeOfDay], e.g. for the session form TimeOfDay get startTime => TimeOfDay.fromDateTime(workoutStart); + /// Countdown length of a timer page, or null if the rest counts up + Duration? restDurationFor(SlotPageEntry slotPage) { + final restTime = slotPage.setConfigData?.restTime; + if (restTime != null) { + return Duration(seconds: restTime.toInt()); + } + return useCountdownBetweenSets ? countdownDuration : null; + } + int get totalPages { // Main pages (start, session, etc.) var count = pages.where((p) => p.type != PageType.set).length; @@ -339,6 +363,8 @@ class GymModeState { String toString() { return 'GymState(' 'currentPage: $currentPage, ' + 'restStartedAt: $restStartedAt, ' + 'restEndsAt: $restEndsAt, ' 'validUntil: $validUntil ' 'workoutStart: $workoutStart, ' 'showExercisePages: $showExercisePages, ' diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 83e4bd186..e6de67f62 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -290,6 +290,7 @@ class GymStateNotifier extends _$GymStateNotifier { routine: routine, iteration: iteration, currentPage: initialPage, + clearRest: shouldReset, // A fresh workout also restarts the elapsed timer workoutStart: shouldReset ? clock.now() : null, ); @@ -306,7 +307,9 @@ class GymStateNotifier extends _$GymStateNotifier { } void setCurrentPage(int page) { + final pageChanged = page != state.currentPage; state = state.copyWith(currentPage: page); + _updateRest(restart: pageChanged); // Ensure that there is a log entry for the current slot entry final slotEntryPage = state.getSlotEntryPageByIndex(); @@ -322,6 +325,27 @@ class GymStateNotifier extends _$GymStateNotifier { ref.read(gymLogProvider.notifier).setLog(log); } + /// Starts the rest when on a timer page, ends it everywhere else. A rest + /// that is already running on the current page keeps going unless [restart]. + void _updateRest({required bool restart}) { + final slotPage = state.getSlotEntryPageByIndex(); + if (slotPage?.type != SlotPageType.timer) { + state = state.copyWith(clearRest: true); + return; + } + if (!restart && state.restStartedAt != null) { + return; + } + + final now = clock.now(); + final duration = state.restDurationFor(slotPage!); + state = state.copyWith( + clearRest: true, + restStartedAt: now, + restEndsAt: duration == null ? null : now.add(duration), + ); + } + void setShowExercisePages(bool value) { state = state.copyWith(showExercisePages: value); calculatePages(); @@ -493,6 +517,7 @@ class GymStateNotifier extends _$GymStateNotifier { isInitialized: false, pages: [], currentPage: 0, + clearRest: true, validUntil: clock.now().add(DEFAULT_DURATION), workoutStart: clock.now(), diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 3fdeb938a..6ea7262c9 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -128,15 +128,11 @@ class _GymModeState extends ConsumerState { out.add(LogPage(_controller, slotPage.uuid)); } - // Timer. Use rest time from config data if available, otherwise use user settings - final rest = slotPage.setConfigData?.restTime; if (slotPage.type == SlotPageType.timer) { + final rest = gymState.restDurationFor(slotPage); out.add( - (rest != null || gymState.useCountdownBetweenSets) - ? TimerCountdownWidget( - _controller, - (rest ?? gymState.countdownDuration.inSeconds).toInt(), - ) + rest != null + ? TimerCountdownWidget(_controller, rest.inSeconds) : TimerWidget(_controller), ); } diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 790beaa09..741dd5ffa 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -508,6 +508,103 @@ void main() { }); }); + group('GymStateNotifier.setCurrentPage, rest', () { + final start = DateTime.utc(2024, 5, 1, 17, 30); + final later = DateTime.utc(2024, 5, 1, 17, 45); + + Iterable slotPages() => notifier.state.pages.expand((p) => p.slotPages); + + // The fixture's first slot has a rest time of 120 s, the second has none + int timerWithRestTime() => slotPages() + .firstWhere((p) => p.type == SlotPageType.timer && p.setConfigData!.restTime != null) + .pageIndex; + int timerWithoutRestTime() => slotPages() + .firstWhere((p) => p.type == SlotPageType.timer && p.setConfigData!.restTime == null) + .pageIndex; + + void goTo(int page, {DateTime? at}) => + withClock(Clock.fixed(at ?? start), () => notifier.setCurrentPage(page)); + + test('A timer page counts down from the rest time of its set', () { + notifier.state = notifier.state.copyWith(useCountdownBetweenSets: false); + + goTo(timerWithRestTime()); + + expect(notifier.state.restStartedAt, start); + expect(notifier.state.restEndsAt, start.add(const Duration(seconds: 120))); + }); + + test('Without a rest time the countdown uses the user setting', () { + notifier.state = notifier.state.copyWith( + useCountdownBetweenSets: true, + countdownDuration: 90, + ); + + goTo(timerWithoutRestTime()); + + expect(notifier.state.restEndsAt, start.add(const Duration(seconds: 90))); + }); + + test('Without a rest time and the countdown setting off, the rest counts up', () { + notifier.state = notifier.state.copyWith(useCountdownBetweenSets: false); + + goTo(timerWithoutRestTime()); + + expect(notifier.state.restStartedAt, start); + expect(notifier.state.restEndsAt, isNull); + }); + + test('Leaving the timer page clears the rest', () { + final timer = timerWithRestTime(); + goTo(timer); + + goTo(timer + 1); + + expect(notifier.state.getSlotEntryPageByIndex()!.type, SlotPageType.log); + expect(notifier.state.restStartedAt, isNull); + expect(notifier.state.restEndsAt, isNull); + }); + + test('Setting the same timer page again keeps the running rest', () { + // gym_mode reports the restored page again when it is reopened + final timer = timerWithRestTime(); + goTo(timer); + + goTo(timer, at: later); + + expect(notifier.state.restStartedAt, start); + }); + + test('Coming back to a timer page restarts the rest', () { + final timer = timerWithRestTime(); + goTo(timer); + goTo(timer + 1); + + goTo(timer, at: later); + + expect(notifier.state.restStartedAt, later); + expect(notifier.state.restEndsAt, later.add(const Duration(seconds: 120))); + }); + + test('clear() ends the rest', () { + goTo(timerWithRestTime()); + + notifier.clear(); + + expect(notifier.state.restStartedAt, isNull); + expect(notifier.state.restEndsAt, isNull); + }); + + test('A reset in initData ends the rest', () { + goTo(timerWithRestTime()); + + notifier.initData(getTestRoutine(), 2, 1); + + expect(notifier.state.restStartedAt, isNull); + expect(notifier.state.restEndsAt, isNull); + }); + }); + group('GymStateNotifier.startWorkout', () { test('Resets the workout start time to now', () { // Arrange @@ -624,5 +721,32 @@ void main() { expect(state.copyWith(clearLogScopeWeeks: true).logScopeWeeks, isNull); }); + + test('Keeps the rest when it is not passed', () { + final state = notifier.state.copyWith( + restStartedAt: DateTime.utc(2024, 5, 1, 17, 30), + restEndsAt: DateTime.utc(2024, 5, 1, 17, 32), + ); + + final copy = state.copyWith(currentPage: 3); + + expect(copy.restStartedAt, DateTime.utc(2024, 5, 1, 17, 30)); + expect(copy.restEndsAt, DateTime.utc(2024, 5, 1, 17, 32)); + }); + + test('clearRest drops both rest fields before applying the passed ones', () { + final state = notifier.state.copyWith( + restStartedAt: DateTime.utc(2024, 5, 1, 17, 30), + restEndsAt: DateTime.utc(2024, 5, 1, 17, 32), + ); + + final cleared = state.copyWith(clearRest: true); + expect(cleared.restStartedAt, isNull); + expect(cleared.restEndsAt, isNull); + + final countUp = state.copyWith(clearRest: true, restStartedAt: DateTime.utc(2024, 5, 1, 18)); + expect(countUp.restStartedAt, DateTime.utc(2024, 5, 1, 18)); + expect(countUp.restEndsAt, isNull); + }); }); } From 23c99ba2ba36802abb2b414e633a8aa4067898ba Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 8 Oct 2026 16:50:52 +0200 Subject: [PATCH 03/28] Move set logging and rest skipping into the gym mode notifier --- .../providers/gym_state_notifier.dart | 78 ++++++- lib/features/routines/validators.dart | 11 +- .../routines/widgets/gym_mode/log_page.dart | 8 +- .../routines/providers/gym_state_test.dart | 204 +++++++++++++++++- .../providers/gym_state_test.mocks.dart | 79 +++++++ 5 files changed, 362 insertions(+), 18 deletions(-) create mode 100644 test/features/routines/providers/gym_state_test.mocks.dart diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index e6de67f62..42b33f34c 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -31,6 +31,8 @@ import 'package:wger/features/routines/models/weight_unit.dart'; import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_notifier.dart'; +import 'package:wger/features/routines/validators.dart'; part 'gym_state_notifier.g.dart'; @@ -317,12 +319,76 @@ class GymStateNotifier extends _$GymStateNotifier { return; } - final log = Log.fromSetConfigData( - slotEntryPage.setConfigData!, - routineId: state.routine.id, - iteration: state.iteration, - ); - ref.read(gymLogProvider.notifier).setLog(log); + ref.read(gymLogProvider.notifier).setLog(_draftFor(slotEntryPage)); + } + + /// The log draft a slot page starts with, prefilled with the planned values + Log _draftFor(SlotPageEntry slotPage) => Log.fromSetConfigData( + slotPage.setConfigData!, + routineId: state.routine.id, + iteration: state.iteration, + ); + + /// Ends the rest of the current timer page and moves on. No-op on other pages. + void skipRest() { + if (state.getSlotEntryPageByIndex()?.type != SlotPageType.timer) { + return; + } + setCurrentPage(state.currentPage + 1); + } + + /// Saves the log draft of the current log page, marks the page as done and + /// moves on to the next page. A failed write propagates to the caller. + Future logCurrentSet() async { + final slotPage = state.getSlotEntryPageByIndex(); + final log = ref.read(gymLogProvider); + if (slotPage == null || slotPage.type != SlotPageType.log || log == null) { + _logger.warning('logCurrentSet called without a log draft on a log page'); + return; + } + + // Done before the write, so a repeated logPlannedSet is rejected meanwhile + markSlotPageAsDone(slotPage.uuid, isDone: true); + try { + await ref.read(workoutLogProvider).addEntry(log, dayId: state.dayId); + } catch (_) { + markSlotPageAsDone(slotPage.uuid, isDone: false); + rethrow; + } + + // The user may have moved on or left gym mode during the write + if (state.currentPage == slotPage.pageIndex) { + setCurrentPage(slotPage.pageIndex + 1); + } + } + + /// Logs the set of the log page [slotPageUuid] without the UI, e.g. from a + /// notification. From the rest right before it the planned values are logged, + /// on the page itself the current draft. False if stale, done or incomplete. + Future logPlannedSet(String slotPageUuid) async { + final target = state.getSlotPageByUUID(slotPageUuid); + if (target == null || target.type != SlotPageType.log || target.logDone) { + return false; + } + + final onTarget = state.currentPage == target.pageIndex; + final onRestBefore = + state.currentPage == target.pageIndex - 1 && + state.getSlotEntryPageByIndex()?.type == SlotPageType.timer; + if (!onTarget && !onRestBefore) { + return false; + } + + final log = onTarget ? ref.read(gymLogProvider) : _draftFor(target); + if (log == null || !isWorkoutLogComplete(repetitions: log.repetitions, weight: log.weight)) { + return false; + } + + if (onRestBefore) { + setCurrentPage(target.pageIndex); + } + await logCurrentSet(); + return true; } /// Starts the rest when on a timer page, ends it everywhere else. A rest diff --git a/lib/features/routines/validators.dart b/lib/features/routines/validators.dart index 305982764..271338f5c 100644 --- a/lib/features/routines/validators.dart +++ b/lib/features/routines/validators.dart @@ -19,15 +19,18 @@ import 'package:wger/features/routines/models/session.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -/// Cross-field validation for a workout log entry, mirroring the -/// reachable part of the backend `WorkoutLog.clean()` rule: at least -/// one of [repetitions] or [weight] must be set. +/// Whether a workout log entry passes the reachable part of the backend +/// `WorkoutLog.clean()` rule: at least one of [repetitions] or [weight] is set. +bool isWorkoutLogComplete({required num? repetitions, required num? weight}) => + repetitions != null || weight != null; + +/// Cross-field validation for a workout log entry, see [isWorkoutLogComplete] String? validateWorkoutLogCrossField({ required num? repetitions, required num? weight, required AppLocalizations i18n, }) { - if (repetitions == null && weight == null) { + if (!isWorkoutLogComplete(repetitions: repetitions, weight: weight)) { return i18n.weightOrRepsRequired; } return null; diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 97b8794c2..ea153598d 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -301,7 +301,6 @@ class _LogFormWidgetState extends ConsumerState { @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); - final logProvider = ref.read(workoutLogProvider); final log = ref.watch(gymLogProvider); // The log is populated when the page becomes current: the PageView can lay @@ -387,18 +386,13 @@ class _LogFormWidgetState extends ConsumerState { return; } - final gymState = ref.read(gymStateProvider); - final gymProvider = ref.read(gymStateProvider.notifier); - final page = gymState.getSlotEntryPageByIndex()!; - // A failed write is intentionally left to propagate to the global // error handler; the success path below is then skipped. - await logProvider.addEntry(log, dayId: gymState.dayId); + await ref.read(gymStateProvider.notifier).logCurrentSet(); if (!context.mounted) { return; } - gymProvider.markSlotPageAsDone(page.uuid, isDone: true); showSnackbar( context, i18n.successfullySaved, diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 741dd5ffa..fc999b569 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -16,10 +16,13 @@ * along with this program. If not, see . */ +import 'dart:async'; + import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.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'; @@ -30,26 +33,36 @@ import 'package:wger/features/account/providers/user_profile_repository.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day.dart'; import 'package:wger/features/routines/models/day_data.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_data.dart'; +import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_repository.dart'; import '../../../../test_data/exercises.dart'; import '../../../../test_data/routines.dart'; import '../helpers/routine_form_test_overrides.dart'; +import 'gym_state_test.mocks.dart'; +@GenerateMocks([WorkoutLogRepository]) void main() { late GymStateNotifier notifier; late ProviderContainer container; + late MockWorkoutLogRepository mockLogRepo; setUp(() { TestWidgetsFlutterBinding.ensureInitialized(); SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); - container = ProviderContainer.test(); + mockLogRepo = MockWorkoutLogRepository(); + when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); + container = ProviderContainer.test( + overrides: [workoutLogRepositoryProvider.overrideWithValue(mockLogRepo)], + ); notifier = container.read(gymStateProvider.notifier); notifier.state = notifier.state.copyWith( showExercisePages: true, @@ -605,6 +618,195 @@ void main() { }); }); + group('GymStateNotifier logging and skipping', () { + final start = DateTime.utc(2024, 5, 1, 17, 30); + + List slotPages() => notifier.state.pages.expand((p) => p.slotPages).toList(); + + // First slot of the fixture: overview, then log/timer pairs with 3x100kg + // and a rest time of 120 s + SlotPageEntry firstLog() => slotPages().firstWhere((p) => p.type == SlotPageType.log); + SlotPageEntry secondLog() => slotPages().where((p) => p.type == SlotPageType.log).elementAt(1); + + Log capturedLog() => + verify(mockLogRepo.addLocalDrift(captureAny, dayId: anyNamed('dayId'))).captured.single + as Log; + + test('logCurrentSet saves the draft, marks the page done and starts the rest', () async { + final log = firstLog(); + notifier.setCurrentPage(log.pageIndex); + container.read(gymLogProvider.notifier).setRepetitions(12); + + await withClock(Clock.fixed(start), notifier.logCurrentSet); + + final captured = verify( + mockLogRepo.addLocalDrift(captureAny, dayId: captureAnyNamed('dayId')), + ).captured; + expect((captured[0] as Log).repetitions, 12); + expect(captured[1], 1); + expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isTrue); + expect(notifier.state.currentPage, log.pageIndex + 1); + expect(notifier.state.restEndsAt, start.add(const Duration(seconds: 120))); + }); + + test('logCurrentSet keeps the page open when the write fails', () async { + final log = firstLog(); + notifier.setCurrentPage(log.pageIndex); + when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenThrow(Exception('db')); + + await expectLater(notifier.logCurrentSet(), throwsException); + + expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isFalse); + expect(notifier.state.currentPage, log.pageIndex); + }); + + test('logCurrentSet does not move on when the user left the page meanwhile', () async { + final write = Completer(); + when( + mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), + ).thenAnswer((_) => write.future); + notifier.setCurrentPage(firstLog().pageIndex); + + final saving = notifier.logCurrentSet(); + notifier.setCurrentPage(0); + write.complete(); + await saving; + + expect(notifier.state.currentPage, 0); + }); + + test('logPlannedSet from the rest before the set logs the planned values', () async { + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex - 1); + + final logged = await withClock( + Clock.fixed(start), + () => notifier.logPlannedSet(log.uuid), + ); + + expect(logged, isTrue); + final saved = capturedLog(); + expect(saved.repetitions, log.setConfigData!.repetitions); + expect(saved.weight, log.setConfigData!.weight); + expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isTrue); + expect(notifier.state.currentPage, log.pageIndex + 1); + expect(notifier.state.restStartedAt, start); + }); + + test('logPlannedSet on the set page itself logs the edited draft', () async { + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex); + container.read(gymLogProvider.notifier).setRepetitions(7); + + expect(await notifier.logPlannedSet(log.uuid), isTrue); + + expect(capturedLog().repetitions, 7); + }); + + test('logPlannedSet on the set page needs the draft', () async { + // A restored state points at the page before onPageChanged seeds the draft + final log = secondLog(); + notifier.state = notifier.state.copyWith(currentPage: log.pageIndex); + + expect(await notifier.logPlannedSet(log.uuid), isFalse); + verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + }); + + test('logPlannedSet ignores a second action while the first one is saving', () async { + final write = Completer(); + when( + mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), + ).thenAnswer((_) => write.future); + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex - 1); + + final first = notifier.logPlannedSet(log.uuid); + final second = await notifier.logPlannedSet(log.uuid); + write.complete(); + + expect(second, isFalse); + expect(await first, isTrue); + verify(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1); + }); + + test('logPlannedSet ignores stale actions', () async { + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex - 1); + final timerUuid = notifier.state.getSlotEntryPageByIndex()!.uuid; + + expect(await notifier.logPlannedSet('unknown'), isFalse, reason: 'unknown page'); + expect(await notifier.logPlannedSet(timerUuid), isFalse, reason: 'not a log page'); + expect(await notifier.logPlannedSet(firstLog().uuid), isFalse, reason: 'not the next set'); + + notifier.markSlotPageAsDone(log.uuid, isDone: true); + expect(await notifier.logPlannedSet(log.uuid), isFalse, reason: 'already logged'); + + verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + expect(notifier.state.currentPage, log.pageIndex - 1); + }); + + test('logPlannedSet only starts from a rest, not from the exercise overview', () async { + final log = firstLog(); + notifier.setCurrentPage(log.pageIndex - 1); + expect(notifier.state.getSlotEntryPageByIndex()!.type, SlotPageType.exerciseOverview); + + expect(await notifier.logPlannedSet(log.uuid), isFalse); + verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + }); + + test('logPlannedSet leaves a set without planned values to the app', () async { + final config = SetConfigData( + exerciseId: 1, + exercise: getTestExercises().first, + slotEntryId: 1, + nrOfSets: 1, + repetitions: null, + weight: null, + restTime: 60, + textRepr: '', + ); + final routine = getTestRoutine() + ..dayDataGym = [ + DayData( + iteration: 1, + date: DateTime(2024, 11, 1), + day: Day(id: 1, routineId: 1, name: 'Open sets'), + slots: [ + SlotData(isSuperset: false, exerciseIds: [1], setConfigs: [config, config]), + ], + ), + ]; + notifier.state = notifier.state.copyWith(routine: routine); + notifier.calculatePages(); + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex - 1); + + expect(await notifier.logPlannedSet(log.uuid), isFalse); + + verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + expect(notifier.state.currentPage, log.pageIndex - 1, reason: 'stays on the rest'); + }); + + test('skipRest moves from the timer page to the next set', () { + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex - 1); + + notifier.skipRest(); + + expect(notifier.state.currentPage, log.pageIndex); + expect(notifier.state.restStartedAt, isNull); + }); + + test('skipRest does nothing outside a rest', () { + final log = firstLog(); + notifier.setCurrentPage(log.pageIndex); + + notifier.skipRest(); + + expect(notifier.state.currentPage, log.pageIndex); + }); + }); + group('GymStateNotifier.startWorkout', () { test('Resets the workout start time to now', () { // Arrange diff --git a/test/features/routines/providers/gym_state_test.mocks.dart b/test/features/routines/providers/gym_state_test.mocks.dart new file mode 100644 index 000000000..60a3dfa88 --- /dev/null +++ b/test/features/routines/providers/gym_state_test.mocks.dart @@ -0,0 +1,79 @@ +// Mocks generated by Mockito from annotations +// in wger/test/features/routines/providers/gym_state_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes + +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/routines/models/log.dart' as _i4; +import 'package:wger/features/routines/providers/workout_logs_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: experimental_member_use +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [WorkoutLogRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogRepository { + MockWorkoutLogRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchLogsByExerciseDrift({ + int? routineId, + required int? exerciseId, + DateTime? since, + }) => + (super.noSuchMethod( + Invocation.method(#watchLogsByExerciseDrift, [], { + #routineId: routineId, + #exerciseId: exerciseId, + #since: since, + }), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i4.Log? log) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [log]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i4.Log? log, {int? dayId}) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [log], {#dayId: dayId}), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} From edb48cfe499693fba952ae8a8e359bd90b483196 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 8 Oct 2026 17:02:53 +0200 Subject: [PATCH 04/28] Let the gym mode PageView follow the gym state --- .../routines/widgets/gym_mode/gym_mode.dart | 32 +++- .../routines/widgets/gym_mode/log_page.dart | 8 +- .../routines/widgets/gym_mode/timer.dart | 62 +++++--- .../routines/screens/gym_mode_test.dart | 68 ++++++++ .../routines/widgets/gym_mode/timer_test.dart | 149 ++++++++++++++++++ 5 files changed, 289 insertions(+), 30 deletions(-) create mode 100644 test/features/routines/widgets/gym_mode/timer_test.dart diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 6ea7262c9..a15b977e0 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -23,6 +23,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/core/build_safety.dart'; +import 'package:wger/core/consts.dart'; import 'package:wger/core/errors.dart'; import 'package:wger/core/network/network_provider.dart'; import 'package:wger/core/widgets/error.dart'; @@ -132,8 +133,8 @@ class _GymModeState extends ConsumerState { final rest = gymState.restDurationFor(slotPage); out.add( rest != null - ? TimerCountdownWidget(_controller, rest.inSeconds) - : TimerWidget(_controller), + ? TimerCountdownWidget(_controller, slotPage.uuid) + : TimerWidget(_controller, slotPage.uuid), ); } } @@ -146,8 +147,35 @@ class _GymModeState extends ConsumerState { return out; } + /// Shows [page] when the state moved without the PageView, e.g. after a + /// notification action or a logged set + void _followCurrentPage(int page) { + final shown = _controller.hasClients ? _controller.page?.round() : null; + if (shown == null || shown == page) { + return; + } + + final resumed = WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed; + if (resumed && (page - shown).abs() == 1) { + _controller.animateToPage( + page, + duration: DEFAULT_ANIMATION_DURATION, + curve: DEFAULT_ANIMATION_CURVE, + ); + } else { + _controller.jumpToPage(page); + } + } + @override Widget build(BuildContext context) { + ref.listen(gymStateProvider.select((s) => s.currentPage), (_, page) { + // clear() also resets the page, but the summary has to stay visible + if (ref.read(gymStateProvider).isInitialized) { + _followCurrentPage(page); + } + }); + return FutureBuilder( future: _initData, builder: (context, snapshot) { diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index ea153598d..46704615c 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -19,7 +19,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:material_ui/material_ui.dart'; -import 'package:wger/core/consts.dart'; import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/core/snackbar.dart'; import 'package:wger/core/widgets/core.dart'; @@ -387,7 +386,8 @@ class _LogFormWidgetState extends ConsumerState { } // A failed write is intentionally left to propagate to the global - // error handler; the success path below is then skipped. + // error handler; the success path below is then skipped. The + // PageView follows the page change from the gym state. await ref.read(gymStateProvider.notifier).logCurrentSet(); if (!context.mounted) { return; @@ -399,10 +399,6 @@ class _LogFormWidgetState extends ConsumerState { center: true, duration: const Duration(seconds: 2), ); - widget.controller.nextPage( - duration: DEFAULT_ANIMATION_DURATION, - curve: DEFAULT_ANIMATION_CURVE, - ); }, child: Text(i18n.save), ), diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index 4310a613b..c76ef3ed4 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -16,7 +16,9 @@ * along with this program. If not, see . */ import 'dart:async'; +import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; @@ -25,24 +27,26 @@ import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/navigation.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -class TimerWidget extends StatefulWidget { +/// Rest that counts up, from the rest start in the gym state +class TimerWidget extends ConsumerStatefulWidget { final PageController _controller; - const TimerWidget(this._controller); + /// The timer page this widget renders + final String slotUuid; + + const TimerWidget(this._controller, this.slotUuid); @override _TimerWidgetState createState() => _TimerWidgetState(); } -class _TimerWidgetState extends State { - late DateTime _startTime; +class _TimerWidgetState extends ConsumerState { final _maxSeconds = 600; late Timer _uiTimer; @override void initState() { super.initState(); - _startTime = DateTime.now(); _uiTimer = Timer.periodic(const Duration(seconds: 1), (_) { // ignore: no-empty-block, avoid-empty-setstate @@ -60,7 +64,15 @@ class _TimerWidgetState extends State { @override Widget build(BuildContext context) { - final elapsed = DateTime.now().difference(_startTime).inSeconds; + final gymState = ref.watch(gymStateProvider); + final slotPage = gymState.getSlotPageByUUID(widget.slotUuid); + if (slotPage == null) { + return Container(); + } + + // The rest only runs while this is the current page + final startedAt = gymState.currentPage == slotPage.pageIndex ? gymState.restStartedAt : null; + final elapsed = startedAt == null ? 0 : clock.now().difference(startedAt).inSeconds; final displaySeconds = elapsed > _maxSeconds ? _maxSeconds : elapsed; final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: displaySeconds)); @@ -86,29 +98,28 @@ class _TimerWidgetState extends State { } } +/// Rest that counts down to the rest end in the gym state class TimerCountdownWidget extends ConsumerStatefulWidget { final PageController _controller; - final int _seconds; - const TimerCountdownWidget( - this._controller, - this._seconds, - ); + /// The timer page this widget renders + final String slotUuid; + + const TimerCountdownWidget(this._controller, this.slotUuid); @override _TimerCountdownWidgetState createState() => _TimerCountdownWidgetState(); } class _TimerCountdownWidgetState extends ConsumerState { - late DateTime _endTime; late Timer _uiTimer; - bool _hasNotified = false; + /// The rest end the alert was played for, so each rest alerts once + DateTime? _alertedFor; @override void initState() { super.initState(); - _endTime = DateTime.now().add(Duration(seconds: widget._seconds)); _uiTimer = Timer.periodic(const Duration(seconds: 1), (_) { // ignore: no-empty-block, avoid-empty-setstate @@ -126,13 +137,23 @@ class _TimerCountdownWidgetState extends ConsumerState { @override Widget build(BuildContext context) { - final remaining = _endTime.difference(DateTime.now()); - final remainingSeconds = remaining.inSeconds <= 0 ? 0 : remaining.inSeconds; - final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds)); final gymState = ref.watch(gymStateProvider); + final slotPage = gymState.getSlotPageByUUID(widget.slotUuid); + if (slotPage == null) { + return Container(); + } - // When countdown finishes, notify ONCE, and respect settings - if (remainingSeconds == 0 && !_hasNotified) { + // The rest only runs while this is the current page, the neighbours show + // their full length + final endsAt = gymState.currentPage == slotPage.pageIndex ? gymState.restEndsAt : null; + final remaining = endsAt == null + ? gymState.restDurationFor(slotPage)! + : endsAt.difference(clock.now()); + final remainingSeconds = max(0, remaining.inSeconds); + final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds)); + + if (endsAt != null && remainingSeconds == 0 && _alertedFor != endsAt) { + _alertedFor = endsAt; if (gymState.alertOnCountdownEnd) { // Strongest built-in haptic on both platforms (iOS: full vibration, // Android: LONG_PRESS). heavyImpact maps to a weak tick on Android. @@ -141,9 +162,6 @@ class _TimerCountdownWidgetState extends ConsumerState { // Not that this only works on desktop platforms SystemSound.play(SystemSoundType.alert); } - setState(() { - _hasNotified = true; - }); } return Column( diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index bc7ae4bbf..14bacae1d 100644 --- a/test/features/routines/screens/gym_mode_test.dart +++ b/test/features/routines/screens/gym_mode_test.dart @@ -506,6 +506,74 @@ void main() { }); }); + /// Opens gym mode and walks to the first log page (start, overview, log) + Future openOnFirstLogPage(WidgetTester tester) async { + await tester.pumpWidget(renderGymMode()); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + await tester.tap(find.byIcon(Icons.chevron_right)); + await tester.pumpAndSettle(); + await tester.tap(find.byIcon(Icons.chevron_right)); + await tester.pumpAndSettle(); + expect(find.byType(LogPage), findsOneWidget); + + return riverpod.ProviderScope.containerOf(tester.element(find.byType(PageView))); + } + + testWidgets( + 'the PageView follows page changes made in the gym state', + (WidgetTester tester) async { + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + final container = await openOnFirstLogPage(tester); + final notifier = container.read(gymStateProvider.notifier); + PageController controller() => tester.widget(find.byType(PageView)).controller!; + + // One page, e.g. skipping the rest from a notification + await tester.tap(find.byIcon(Icons.chevron_right)); + await tester.pumpAndSettle(); + expect(find.byType(TimerCountdownWidget), findsOneWidget); + notifier.skipRest(); + await tester.pumpAndSettle(); + expect(find.byType(LogPage), findsOneWidget); + expect(controller().page, notifier.state.currentPage); + + // Several pages at once + final sessionPage = notifier.state.pages.firstWhere((p) => p.type == PageType.session); + notifier.setCurrentPage(sessionPage.pageIndex); + await tester.pumpAndSettle(); + expect(find.byType(SessionPage), findsOneWidget); + expect(controller().page, sessionPage.pageIndex); + }); + }, + semanticsEnabled: false, + ); + + testWidgets( + 'saving a set moves on to the pause exactly once', + (WidgetTester tester) async { + // The gym state advances and the PageView follows it, the save button + // must not add a page change of its own + when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); + + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + final container = await openOnFirstLogPage(tester); + final logPage = container.read(gymStateProvider).currentPage; + + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + + expect(find.byType(TimerCountdownWidget), findsOneWidget); + expect(container.read(gymStateProvider).currentPage, logPage + 1); + expect( + tester.widget(find.byType(PageView)).controller!.page, + logPage + 1, + ); + }); + }, + semanticsEnabled: false, + ); + testWidgets( 'resuming an interrupted session reopens the page it was left on', (WidgetTester tester) async { diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart new file mode 100644 index 000000000..226542caa --- /dev/null +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -0,0 +1,149 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:clock/clock.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +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:wger/features/routines/providers/gym_state.dart'; +import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/features/routines/widgets/gym_mode/timer.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/l10n/localizations_delegates.dart'; + +import '../../../../../test_data/routines.dart'; + +void main() { + final now = DateTime.utc(2025, 3, 29, 14, 33); + late ProviderContainer container; + late GymStateNotifier notifier; + + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + container = ProviderContainer.test(); + notifier = container.read(gymStateProvider.notifier); + final routine = getTestRoutine(); + notifier.initData(routine, routine.days.first.id!, 1); + }); + + // In the fixture the first slot rests 120 s, the second has no rest time + SlotPageEntry timerPage({required bool withRestTime}) => notifier.state.pages + .expand((p) => p.slotPages) + .firstWhere( + (p) => p.type == SlotPageType.timer && (p.setConfigData!.restTime != null) == withRestTime, + ); + + Future pumpTimer(WidgetTester tester, Widget timer) async { + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: appLocalizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) { + final controller = PageController(); + return PageView(controller: controller, children: [timer]); + }, + ), + ), + ), + ), + ); + } + + group('TimerCountdownWidget', () { + testWidgets('counts down to the rest end of the gym state', (tester) async { + final page = timerPage(withRestTime: true); + notifier.state = notifier.state.copyWith( + currentPage: page.pageIndex, + restStartedAt: now.subtract(const Duration(seconds: 75)), + restEndsAt: now.add(const Duration(seconds: 45)), + ); + + await withClock(Clock.fixed(now), () async { + await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid)); + }); + + expect(find.text('0:45'), findsOneWidget); + }); + + testWidgets('a timer page that is not current shows its full rest', (tester) async { + // The rest end in the state belongs to the current page only + final page = timerPage(withRestTime: true); + notifier.state = notifier.state.copyWith( + currentPage: page.pageIndex + 1, + restEndsAt: now.add(const Duration(seconds: 45)), + ); + + await withClock(Clock.fixed(now), () async { + await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid)); + }); + + expect(find.text('2:00'), findsOneWidget); + }); + + testWidgets('alerts once when the rest is over', (tester) async { + final calls = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + calls.add(call.method); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final page = timerPage(withRestTime: true); + notifier.state = notifier.state.copyWith(currentPage: page.pageIndex, restEndsAt: now); + + await withClock(Clock.fixed(now), () async { + await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid)); + // The widget repaints every second and keeps seeing the end + await tester.pump(const Duration(seconds: 3)); + }); + + expect(calls.where((m) => m == 'HapticFeedback.vibrate'), hasLength(1)); + }); + }); + + group('TimerWidget', () { + testWidgets('counts up from the rest start of the gym state', (tester) async { + final page = timerPage(withRestTime: false); + notifier.state = notifier.state.copyWith( + currentPage: page.pageIndex, + restStartedAt: now.subtract(const Duration(seconds: 30)), + ); + + await withClock(Clock.fixed(now), () async { + await pumpTimer(tester, TimerWidget(PageController(), page.uuid)); + }); + + expect(find.text('0:30'), findsOneWidget); + }); + }); +} From f34542d53549a4084a51de1deed5ad508caf69dd Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 10 Oct 2026 16:35:28 +0200 Subject: [PATCH 05/28] Add flutter_local_notifications and its platform setup --- android/app/build.gradle | 6 +++ android/app/src/main/AndroidManifest.xml | 9 ++++ ios/Runner/AppDelegate.swift | 30 +++++++++++ macos/Flutter/GeneratedPluginRegistrant.swift | 2 + pubspec.lock | 52 ++++++++++++++++--- pubspec.yaml | 1 + windows/flutter/generated_plugins.cmake | 1 + 7 files changed, 95 insertions(+), 6 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index f81c24ede..be6c05e4a 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -33,6 +33,8 @@ android { compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 + // Required by flutter_local_notifications + coreLibraryDesugaringEnabled true } @@ -80,3 +82,7 @@ kotlin { flutter { source '../..' } + +dependencies { + coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.4' +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index fe564095e..9e65ff240 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -110,6 +110,15 @@ + + + + Bool { + // Lets notifications show in the foreground and delivers action responses + UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate return super.application(application, didFinishLaunchingWithOptions: launchOptions) } + // A notification action is handled by the main isolate, but the plugin + // completes the response right away and iOS suspends the app again. + // Keep it running briefly so the action is processed now. + override func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void + ) { + var task: UIBackgroundTaskIdentifier = .invalid + task = UIApplication.shared.beginBackgroundTask { + UIApplication.shared.endBackgroundTask(task) + task = .invalid + } + DispatchQueue.main.asyncAfter(deadline: .now() + 10) { + if task != .invalid { + UIApplication.shared.endBackgroundTask(task) + task = .invalid + } + } + super.userNotificationCenter( + center, didReceive: response, withCompletionHandler: completionHandler) + } + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + // Notification actions run in a separate engine, which needs the plugins too + FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { registry in + GeneratedPluginRegistrant.register(with: registry) + } GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) guard let registrar = engineBridge.pluginRegistry.registrar( diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 316227cfd..fd9b51dc2 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -10,6 +10,7 @@ import connectivity_plus import device_info_plus import dynamic_color import file_selector_macos +import flutter_local_notifications import flutter_secure_storage_darwin import flutter_timezone import package_info_plus @@ -23,6 +24,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) DynamicColorPlugin.register(with: registry.registrar(forPlugin: "DynamicColorPlugin")) FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) FlutterSecureStorageDarwinPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageDarwinPlugin")) FlutterTimezonePlugin.register(with: registry.registrar(forPlugin: "FlutterTimezonePlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) diff --git a/pubspec.lock b/pubspec.lock index 54448efbf..26ab56331 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -277,10 +277,10 @@ packages: dependency: "direct main" description: name: connectivity_plus - sha256: d7749fd36d8b404a4935612b94eca7c3ce3705377ab678e24ff2a4301436f741 + sha256: "762c99f890ca8bf87f7337236f99edd42793843bc6c3631da294a76653a54bd0" url: "https://pub.dev" source: hosted - version: "7.3.2" + version: "7.3.1" connectivity_plus_platform_interface: dependency: "direct dev" description: @@ -349,10 +349,10 @@ packages: dependency: transitive description: name: dbus - sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 + sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383 url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.7.15" device_info_plus: dependency: transitive description: @@ -547,6 +547,46 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: "357be7ff996dc272e2037c69c1bdd5d1bd21172219d55f8bd2e11aeea602e6d3" + url: "https://pub.dev" + source: hosted + version: "22.3.1" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: "9ca97e63776f29ab1b955725c09999fc2c150523269db150c39274f2a43c5a8b" + url: "https://pub.dev" + source: hosted + version: "8.0.1" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: "43c3761d916c9bd3d5c7ebbc44d82f4990329840c0c5d62ad5260cc1b5d399bd" + url: "https://pub.dev" + source: hosted + version: "12.2.0" + flutter_local_notifications_web: + dependency: transitive + description: + name: flutter_local_notifications_web + sha256: "516afaf97a2d1e67a036c6617321b00d205d72f7a67b6eccf936cd565f985878" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_local_notifications_windows: + dependency: transitive + description: + name: flutter_local_notifications_windows + sha256: "6f43bdd03b171b7a90f22647506fea33e2bb12294b7c7c7a3d690e960a382945" + url: "https://pub.dev" + source: hosted + version: "3.1.1" flutter_localizations: dependency: "direct main" description: flutter @@ -1073,10 +1113,10 @@ packages: dependency: transitive description: name: nm - sha256: "2ae480aa3379716b8bb58dfebb168e2919394c92b629efaaa0baaa5d140786e6" + sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" url: "https://pub.dev" source: hosted - version: "0.6.0" + version: "0.5.0" objective_c: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 60b723881..fffd1406f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -83,6 +83,7 @@ dependencies: flutter_timezone: ^5.1.0 timezone: ^0.11.1 material_ui: ^1.4.0 + flutter_local_notifications: ^22.3.1 dev_dependencies: flutter_test: diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index 0df1af527..1388064da 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -13,6 +13,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + flutter_local_notifications_windows flutter_zxing jni ) From c9ec3aed8eaa4ab1b513250f48cfaae82260c064 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 10 Oct 2026 22:07:44 +0200 Subject: [PATCH 06/28] Add gym mode settings for the rest alarm and workout notification --- .../routines/providers/gym_state.dart | 14 ++++++++ .../providers/gym_state_notifier.dart | 30 ++++++++++++++-- .../routines/widgets/gym_mode/start_page.dart | 19 ++++++++++ lib/l10n/app_en.arb | 4 +++ .../routines/providers/gym_state_test.dart | 36 +++++++++++++++++++ .../widgets/gym_mode/start_page_test.dart | 30 ++++++++++++++++ 6 files changed, 131 insertions(+), 2 deletions(-) diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index dee42f3a5..c2e22d32a 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -34,6 +34,8 @@ const PREFS_COUNTDOWN_DURATION = 'countdownDurationSecondsPrefs'; const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs'; const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs'; const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs'; +const PREFS_REST_ALARM = 'restAlarmPrefs'; +const PREFS_WORKOUT_NOTIFICATION = 'workoutNotificationPrefs'; /// In seconds const DEFAULT_COUNTDOWN_DURATION = 180; @@ -192,6 +194,12 @@ class GymModeState { final bool showDistinctLogs; final bool showWorkoutDuration; + /// OS notification when the rest is over, also with the app in the background + final bool restAlarmEnabled; + + /// Ongoing notification with the rest and the next set (Android) + final bool showWorkoutNotification; + // Routine data late final int dayId; late final int iteration; @@ -212,6 +220,8 @@ class GymModeState { this.logScopeWeeks, this.showDistinctLogs = true, this.showWorkoutDuration = true, + this.restAlarmEnabled = true, + this.showWorkoutNotification = true, int? dayId, int? iteration, Routine? routine, @@ -261,6 +271,8 @@ class GymModeState { bool clearLogScopeWeeks = false, bool? showDistinctLogs, bool? showWorkoutDuration, + bool? restAlarmEnabled, + bool? showWorkoutNotification, }) { return GymModeState( isInitialized: isInitialized ?? this.isInitialized, @@ -285,6 +297,8 @@ class GymModeState { logScopeWeeks: clearLogScopeWeeks ? null : (logScopeWeeks ?? this.logScopeWeeks), showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, + restAlarmEnabled: restAlarmEnabled ?? this.restAlarmEnabled, + showWorkoutNotification: showWorkoutNotification ?? this.showWorkoutNotification, ); } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 42b33f34c..cef4f2245 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -93,6 +93,16 @@ class GymStateNotifier extends _$GymStateNotifier { state = state.copyWith(showWorkoutDuration: showWorkoutDuration); } + final restAlarm = await prefs.getBool(PREFS_REST_ALARM); + if (restAlarm != null && restAlarm != state.restAlarmEnabled) { + state = state.copyWith(restAlarmEnabled: restAlarm); + } + + final workoutNotification = await prefs.getBool(PREFS_WORKOUT_NOTIFICATION); + if (workoutNotification != null && workoutNotification != state.showWorkoutNotification) { + state = state.copyWith(showWorkoutNotification: workoutNotification); + } + _logger.finer( 'Loaded saved preferences: ' 'showExercise=$showExercise ' @@ -102,7 +112,9 @@ class GymStateNotifier extends _$GymStateNotifier { 'defaultCountdownDurationSeconds=$defaultCountdownDurationSeconds' 'logScopeWeeks=$logScopeWeeks ' 'showDistinctLogs=$showDistinctLogs ' - 'showWorkoutDuration=$showWorkoutDuration ', + 'showWorkoutDuration=$showWorkoutDuration ' + 'restAlarm=$restAlarm ' + 'workoutNotification=$workoutNotification ', ); } @@ -123,6 +135,8 @@ class GymStateNotifier extends _$GymStateNotifier { } await prefs.setBool(PREFS_SHOW_DISTINCT_LOGS, state.showDistinctLogs); await prefs.setBool(PREFS_SHOW_WORKOUT_DURATION, state.showWorkoutDuration); + await prefs.setBool(PREFS_REST_ALARM, state.restAlarmEnabled); + await prefs.setBool(PREFS_WORKOUT_NOTIFICATION, state.showWorkoutNotification); _logger.finer( 'Saved preferences: ' @@ -133,7 +147,9 @@ class GymStateNotifier extends _$GymStateNotifier { 'defaultCountdownDuration=${state.countdownDuration.inSeconds}' 'logScopeWeeks=${state.logScopeWeeks} ' 'showDistinctLogs=${state.showDistinctLogs} ' - 'showWorkoutDuration=${state.showWorkoutDuration} ', + 'showWorkoutDuration=${state.showWorkoutDuration} ' + 'restAlarm=${state.restAlarmEnabled} ' + 'workoutNotification=${state.showWorkoutNotification} ', ); } @@ -455,6 +471,16 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } + void setRestAlarmEnabled(bool value) { + state = state.copyWith(restAlarmEnabled: value); + _savePrefs(); + } + + void setShowWorkoutNotification(bool value) { + state = state.copyWith(showWorkoutNotification: value); + _savePrefs(); + } + void markSlotPageAsDone(String uuid, {required bool isDone}) { final slotPage = state.getSlotPageByUUID(uuid); if (slotPage == null) { diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 272d6866b..db541fc63 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; @@ -166,6 +167,24 @@ class _GymModeOptionsState extends ConsumerState { ? (value) => gymNotifier.setAlertOnCountdownEnd(value) : null, ), + SwitchListTile( + key: const ValueKey('gym-mode-rest-alarm'), + title: Text(i18n.gymModeRestAlarm), + subtitle: Text(i18n.gymModeRestAlarmHelp), + value: gymState.restAlarmEnabled, + onChanged: gymState.showTimerPages + ? (value) => gymNotifier.setRestAlarmEnabled(value) + : null, + ), + // The ongoing notification only exists on Android + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) + SwitchListTile( + key: const ValueKey('gym-mode-workout-notification'), + title: Text(i18n.gymModeWorkoutNotification), + subtitle: Text(i18n.gymModeWorkoutNotificationHelp), + value: gymState.showWorkoutNotification, + onChanged: (value) => gymNotifier.setShowWorkoutNotification(value), + ), const Divider(), ListTile( diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b86d70a4e..a33003716 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -376,6 +376,10 @@ "stopwatch": "Stopwatch", "gymModeDefaultCountdownTime": "Default countdown time, in seconds", "gymModeNotifyOnCountdownFinish": "Notify on countdown end", + "gymModeRestAlarm": "Rest alarm", + "gymModeRestAlarmHelp": "System notification when the rest is over, also with the screen locked", + "gymModeWorkoutNotification": "Workout notification", + "gymModeWorkoutNotificationHelp": "Shows the rest and the next set, with buttons to log it or skip the rest", "duration": "Duration", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index fc999b569..e600e91d7 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -521,6 +521,42 @@ void main() { }); }); + group('GymStateNotifier notification settings', () { + // PreferenceHelper keeps the store of the first test, start from empty + setUp(() => PreferenceHelper.asyncPref.clear()); + + test('Both are on without stored preferences', () async { + await notifier.loadPrefs(); + + expect(notifier.state.restAlarmEnabled, isTrue); + expect(notifier.state.showWorkoutNotification, isTrue); + }); + + test('Stored values are loaded', () async { + await PreferenceHelper.asyncPref.setBool(PREFS_REST_ALARM, false); + await PreferenceHelper.asyncPref.setBool(PREFS_WORKOUT_NOTIFICATION, false); + + await notifier.loadPrefs(); + + expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.showWorkoutNotification, isFalse); + }); + + test('The setters change only their own flag and persist it', () async { + notifier.setRestAlarmEnabled(false); + await pumpEventQueue(); + expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.showWorkoutNotification, isTrue); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_REST_ALARM), false); + + notifier.setShowWorkoutNotification(false); + await pumpEventQueue(); + expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.showWorkoutNotification, isFalse); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_WORKOUT_NOTIFICATION), false); + }); + }); + group('GymStateNotifier.setCurrentPage, rest', () { final start = DateTime.utc(2024, 5, 1, 17, 30); final later = DateTime.utc(2024, 5, 1, 17, 45); diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index 0b7a6d9d8..a290f0244 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; @@ -96,21 +97,35 @@ void main() { await tester.tap(notifySwitch); await tester.pump(); + // The rest alarm is only enabled while timer pages are shown + final restAlarmSwitch = find.byKey(const ValueKey('gym-mode-rest-alarm')); + await tester.ensureVisible(restAlarmSwitch); + await tester.tap(restAlarmSwitch); + await tester.pump(); + + final workoutNotificationSwitch = find.byKey(const ValueKey('gym-mode-workout-notification')); + await tester.ensureVisible(workoutNotificationSwitch); + await tester.tap(workoutNotificationSwitch); + await tester.pump(); + // Now toggle show exercises final showExercisesSwitch = find.byKey(const ValueKey('gym-mode-option-show-exercises')); expect(showExercisesSwitch, findsOneWidget); + await tester.ensureVisible(showExercisesSwitch); await tester.tap(showExercisesSwitch); await tester.pump(); // Toggle show timer (this will disable notify switch) final showTimerSwitch = find.byKey(const ValueKey('gym-mode-option-show-timer')); expect(showTimerSwitch, findsOneWidget); + await tester.ensureVisible(showTimerSwitch); await tester.tap(showTimerSwitch); await tester.pump(); // Toggle show workout duration final durationSwitch = find.byKey(const ValueKey('gym-mode-option-show-workout-duration')); expect(durationSwitch, findsOneWidget); + await tester.ensureVisible(durationSwitch); await tester.tap(durationSwitch); await tester.pump(); @@ -119,6 +134,21 @@ void main() { expect(notifier.state.showTimerPages, isFalse); expect(notifier.state.alertOnCountdownEnd, isTrue); expect(notifier.state.showWorkoutDuration, isFalse); + expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.showWorkoutNotification, isFalse); + }); + + testWidgets('The workout notification switch only shows on Android', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + + await pumpGymModeOptions(tester); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('gym-mode-rest-alarm')), findsOneWidget); + expect(find.byKey(const ValueKey('gym-mode-workout-notification')), findsNothing); + debugDefaultTargetPlatformOverride = null; }); testWidgets('Dropdown, text field and refresh button update notifier state', (tester) async { From 88f3df98f5167be09d110972408c169097085abb Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 21 Oct 2026 09:15:19 +0200 Subject: [PATCH 07/28] Add gym mode settings for the rest alarm and workout notification --- lib/core/shared_preferences.dart | 7 +- .../workout_notification_content.dart | 289 ++++++++++++++++++ .../workout_notification_controller.dart | 129 ++++++++ .../workout_notification_service.dart | 204 +++++++++++++ .../routines/widgets/gym_mode/gym_mode.dart | 24 ++ lib/l10n/app_en.arb | 31 ++ lib/main.dart | 3 + .../workout_notification_content_test.dart | 217 +++++++++++++ .../workout_notification_controller_test.dart | 166 ++++++++++ ...ut_notification_controller_test.mocks.dart | 86 ++++++ .../routines/providers/gym_state_test.dart | 3 - .../routines/screens/gym_mode_test.dart | 53 ++++ .../routines/screens/gym_mode_test.mocks.dart | 64 ++++ test/helpers/fake_auth_environment.dart | 5 +- 14 files changed, 1271 insertions(+), 10 deletions(-) create mode 100644 lib/features/routines/notifications/workout_notification_content.dart create mode 100644 lib/features/routines/notifications/workout_notification_controller.dart create mode 100644 lib/features/routines/notifications/workout_notification_service.dart create mode 100644 test/features/routines/notifications/workout_notification_content_test.dart create mode 100644 test/features/routines/notifications/workout_notification_controller_test.dart create mode 100644 test/features/routines/notifications/workout_notification_controller_test.mocks.dart diff --git a/lib/core/shared_preferences.dart b/lib/core/shared_preferences.dart index 33eaf1cf0..ff003e780 100644 --- a/lib/core/shared_preferences.dart +++ b/lib/core/shared_preferences.dart @@ -11,13 +11,13 @@ import 'package:wger/features/nutrition/models/ingredient_filters.dart'; /// and handles migration from the legacy SharedPreferences to /// SharedPreferencesAsync. class PreferenceHelper { - SharedPreferencesAsync _asyncPref = SharedPreferencesAsync(); - PreferenceHelper._instantiate(); static final PreferenceHelper _instance = PreferenceHelper._instantiate(); - static SharedPreferencesAsync get asyncPref => _instance._asyncPref; + /// Bound to the current `SharedPreferencesAsyncPlatform.instance` on every + /// read, so a platform swapped in later (e.g. per test) takes effect. + static SharedPreferencesAsync get asyncPref => SharedPreferencesAsync(); static PreferenceHelper get instance => _instance; @@ -35,7 +35,6 @@ class PreferenceHelper { sharedPreferencesAsyncOptions: sharedPreferencesOptions, migrationCompletedKey: 'migrationCompleted', ); - _asyncPref = SharedPreferencesAsync(); } //ingredients filters diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart new file mode 100644 index 000000000..99b7730e2 --- /dev/null +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -0,0 +1,289 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:convert'; + +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:wger/features/routines/providers/gym_state.dart'; +import 'package:wger/features/routines/validators.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Identifies the gym session and the slot pages a notification action targets +class WorkoutNotificationPayload extends Equatable { + final int routineId; + final int dayId; + final int iteration; + final DateTime workoutStart; + + /// The log page the "log set" action logs + final String? logSlotUuid; + + /// The timer page the "skip rest" action leaves + final String? restSlotUuid; + + const WorkoutNotificationPayload({ + required this.routineId, + required this.dayId, + required this.iteration, + required this.workoutStart, + this.logSlotUuid, + this.restSlotUuid, + }); + + String encode() => jsonEncode({ + 'routineId': routineId, + 'dayId': dayId, + 'iteration': iteration, + 'workoutStart': workoutStart.toUtc().toIso8601String(), + 'logSlotUuid': logSlotUuid, + 'restSlotUuid': restSlotUuid, + }); + + /// Null if [payload] is missing or not one of ours + static WorkoutNotificationPayload? decode(String? payload) { + if (payload == null) { + return null; + } + try { + final json = jsonDecode(payload) as Map; + return WorkoutNotificationPayload( + routineId: json['routineId'] as int, + dayId: json['dayId'] as int, + iteration: json['iteration'] as int, + workoutStart: DateTime.parse(json['workoutStart'] as String), + logSlotUuid: json['logSlotUuid'] as String?, + restSlotUuid: json['restSlotUuid'] as String?, + ); + } on Object { + return null; + } + } + + @override + List get props => [routineId, dayId, iteration, workoutStart, logSlotUuid, restSlotUuid]; +} + +/// The ongoing notification while a workout runs (Android) +class WorkoutControls extends Equatable { + final String title; + final String body; + + /// Reference time of the chronometer, none if null + final DateTime? chronometerAt; + final bool chronometerCountsDown; + + final bool canLogSet; + final bool canSkipRest; + final WorkoutNotificationPayload payload; + + const WorkoutControls({ + required this.title, + required this.body, + required this.payload, + this.chronometerAt, + this.chronometerCountsDown = false, + this.canLogSet = false, + this.canSkipRest = false, + }); + + @override + List get props => [ + title, + body, + chronometerAt, + chronometerCountsDown, + canLogSet, + canSkipRest, + payload, + ]; +} + +/// The notification that fires when the rest is over +class RestAlarm extends Equatable { + final DateTime at; + final String title; + final String body; + final bool canLogSet; + final WorkoutNotificationPayload payload; + + const RestAlarm({ + required this.at, + required this.title, + required this.body, + required this.payload, + this.canLogSet = false, + }); + + @override + List get props => [at, title, body, canLogSet, payload]; +} + +/// Localized texts the platform needs besides the notification content +class WorkoutNotificationLabels extends Equatable { + final String logSet; + final String skipRest; + final String controlsChannel; + final String alarmChannel; + + const WorkoutNotificationLabels({ + required this.logSet, + required this.skipRest, + required this.controlsChannel, + required this.alarmChannel, + }); + + WorkoutNotificationLabels.of(AppLocalizations i18n) + : logSet = i18n.workoutNotificationLogSet, + skipRest = i18n.workoutNotificationSkipRest, + controlsChannel = i18n.workoutNotificationChannel, + alarmChannel = i18n.gymModeRestAlarm; + + @override + List get props => [logSet, skipRest, controlsChannel, alarmChannel]; +} + +/// What the OS should show for the workout, nothing if both are null +class WorkoutNotificationTarget extends Equatable { + final WorkoutControls? controls; + final RestAlarm? alarm; + + const WorkoutNotificationTarget({this.controls, this.alarm}); + + static const none = WorkoutNotificationTarget(); + + bool get isEmpty => controls == null && alarm == null; + + @override + List get props => [controls, alarm]; +} + +/// Derives the workout notifications from [state] at [now]. +/// +/// [withControls] is whether the ongoing notification is supported and wanted. +WorkoutNotificationTarget buildWorkoutNotification( + GymModeState state, { + required DateTime now, + required AppLocalizations i18n, + required String languageCode, + required bool withControls, +}) { + if (!state.isInitialized) { + return WorkoutNotificationTarget.none; + } + + final slotPages = state.pages.expand((p) => p.slotPages).toList(); + final current = state.getSlotEntryPageByIndex(); + + String setText(SlotPageEntry page) { + final config = page.setConfigData!; + return '${config.exercise.getTranslation(languageCode).name} ${config.textRepr}'; + } + + bool plannedComplete(SlotPageEntry page) => isWorkoutLogComplete( + repetitions: page.setConfigData!.repetitions, + weight: page.setConfigData!.weight, + ); + + WorkoutNotificationPayload payload({String? logSlotUuid, String? restSlotUuid}) => + WorkoutNotificationPayload( + routineId: state.routine.id!, + dayId: state.dayId, + iteration: state.iteration, + workoutStart: state.workoutStart, + logSlotUuid: logSlotUuid, + restSlotUuid: restSlotUuid, + ); + + if (current?.type == SlotPageType.timer) { + final next = slotPages.firstWhereOrNull( + (p) => p.type == SlotPageType.log && p.pageIndex > current!.pageIndex, + ); + final body = next == null ? '' : i18n.workoutNotificationNext(setText(next)); + // "Log set" only works from the rest right before the set + final canLogSet = + next != null && + next.pageIndex == current!.pageIndex + 1 && + !next.logDone && + plannedComplete(next); + final actionPayload = payload(logSlotUuid: next?.uuid, restSlotUuid: current!.uuid); + + final endsAt = state.restEndsAt; + final restRunning = endsAt != null && endsAt.isAfter(now); + + final alarm = state.restAlarmEnabled && restRunning + ? RestAlarm( + at: endsAt, + title: i18n.workoutNotificationRestOver, + body: body, + canLogSet: canLogSet, + payload: actionPayload, + ) + : null; + + final controls = withControls + ? WorkoutControls( + title: endsAt != null && !restRunning ? i18n.workoutNotificationRestOver : i18n.pause, + body: body, + chronometerAt: endsAt == null ? state.restStartedAt : (restRunning ? endsAt : null), + chronometerCountsDown: restRunning, + canLogSet: canLogSet, + canSkipRest: true, + payload: actionPayload, + ) + : null; + + return WorkoutNotificationTarget(controls: controls, alarm: alarm); + } + + if (!withControls) { + return WorkoutNotificationTarget.none; + } + + if (current?.type == SlotPageType.log) { + final page = state.getPageByIndex(current!.pageIndex)!; + final sameExercise = page.slotPages + .where( + (p) => + p.type == SlotPageType.log && + p.setConfigData!.exerciseId == current.setConfigData!.exerciseId, + ) + .toList(); + final config = current.setConfigData!; + + return WorkoutNotificationTarget( + controls: WorkoutControls( + title: config.exercise.getTranslation(languageCode).name, + body: + '${i18n.workoutNotificationSetOf(sameExercise.indexOf(current) + 1, sameExercise.length)}' + ' · ${config.textRepr}', + canLogSet: !current.logDone && plannedComplete(current), + payload: payload(logSlotUuid: current.uuid), + ), + ); + } + + return WorkoutNotificationTarget( + controls: WorkoutControls( + title: i18n.workoutNotificationInProgress, + body: '', + chronometerAt: state.workoutStart, + payload: payload(), + ), + ); +} diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart new file mode 100644 index 000000000..55e27761f --- /dev/null +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -0,0 +1,129 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:async'; +import 'dart:ui'; + +import 'package:clock/clock.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; +import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; +import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Whether the gym mode screen is mounted +final gymModeVisibleProvider = NotifierProvider( + GymModeVisibleNotifier.new, +); + +class GymModeVisibleNotifier extends Notifier { + @override + bool build() => false; + + void set(bool visible) { + // The screen reports leaving after its own disposal, maybe after the app's + if (ref.mounted) { + state = visible; + } + } +} + +/// Keeps the platform notifications in line with the desired target +class WorkoutNotificationController { + final _logger = Logger('WorkoutNotificationController'); + final WorkoutNotificationService _service; + + var _shown = WorkoutNotificationTarget.none; + Future _queue = Future.value(); + + WorkoutNotificationController(this._service); + + /// Applies [target], in call order. Unchanged targets cause no platform calls. + Future apply(WorkoutNotificationTarget target, WorkoutNotificationLabels labels) { + return _queue = _queue + .then((_) => _apply(target, labels)) + .catchError((Object e) => _logger.warning('Could not update the notification: $e')); + } + + Future _apply(WorkoutNotificationTarget target, WorkoutNotificationLabels labels) async { + if (target == _shown) { + return; + } + _shown = target; + + // Alarm and controls share one notification, so every change starts over + await _service.cancelAll(); + if (target.alarm != null) { + await _service.scheduleRestAlarm(target.alarm!, labels); + } + if (target.controls != null) { + await _service.showControls(target.controls!, labels); + } + } +} + +/// The locale the app renders in, also without a BuildContext +Locale _appLocale(Ref ref) { + final userLocale = ref.read(appSettingsProvider).value?.userLocale; + return userLocale ?? + basicLocaleListResolution( + PlatformDispatcher.instance.locales, + AppLocalizations.supportedLocales, + ); +} + +const _backgroundStates = { + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.detached, +}; + +/// Derives the workout notifications from the gym state. While gym mode is on +/// screen there are none, the screen itself shows the rest. +final workoutNotificationControllerProvider = Provider((ref) { + final service = ref.read(workoutNotificationServiceProvider); + final controller = WorkoutNotificationController(service); + + void update() { + final state = ref.read(gymStateProvider); + final inForeground = !_backgroundStates.contains(WidgetsBinding.instance.lifecycleState); + final locale = _appLocale(ref); + final i18n = lookupAppLocalizations(locale); + + final target = inForeground && ref.read(gymModeVisibleProvider) + ? WorkoutNotificationTarget.none + : buildWorkoutNotification( + state, + now: clock.now(), + i18n: i18n, + languageCode: locale.languageCode, + withControls: service.supportsControls && state.showWorkoutNotification, + ); + unawaited(controller.apply(target, WorkoutNotificationLabels.of(i18n))); + } + + ref.listen(gymStateProvider, (_, _) => update()); + ref.listen(gymModeVisibleProvider, (_, _) => update()); + final lifecycle = AppLifecycleListener(onStateChange: (_) => update()); + ref.onDispose(lifecycle.dispose); + + return controller; +}); diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart new file mode 100644 index 000000000..50086015b --- /dev/null +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -0,0 +1,204 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/foundation.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; +import 'package:timezone/timezone.dart' as tz; +import 'package:wger/features/routines/notifications/workout_notification_content.dart'; + +const WORKOUT_NOTIFICATION_ACTION_LOG_SET = 'log_set'; +const WORKOUT_NOTIFICATION_ACTION_SKIP_REST = 'skip_rest'; + +/// Shows the workout notifications on the platform. +/// +/// The controls and the rest alarm share one notification, so the alarm +/// replaces the controls in place when it fires. +abstract class WorkoutNotificationService { + /// Whether the platform has the ongoing controls notification + bool get supportsControls; + + Future requestPermissions(WorkoutNotificationLabels labels); + + Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels); + + Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels); + + /// Removes the shown notification and a pending rest alarm + Future cancelAll(); +} + +/// For platforms without workout notifications +class NoopWorkoutNotificationService implements WorkoutNotificationService { + @override + bool get supportsControls => false; + + @override + Future requestPermissions(WorkoutNotificationLabels labels) async {} + + @override + Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async {} + + @override + Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels) async {} + + @override + Future cancelAll() async {} +} + +/// Android and iOS, via flutter_local_notifications +class LocalWorkoutNotificationService implements WorkoutNotificationService { + static const _notificationId = 1; + static const _controlsChannelId = 'workout_controls'; + static const _alarmChannelId = 'rest_alarm'; + static const _restEndCategory = 'workout_rest_end'; + + final _logger = Logger('LocalWorkoutNotificationService'); + final _plugin = FlutterLocalNotificationsPlugin(); + Future? _initialized; + + @override + bool get supportsControls => defaultTargetPlatform == TargetPlatform.android; + + /// The iOS action labels are registered once, with the first labels seen + Future _ensureInitialized(WorkoutNotificationLabels labels) { + return _initialized ??= _plugin + .initialize( + settings: InitializationSettings( + android: const AndroidInitializationSettings('@mipmap/ic_launcher'), + iOS: DarwinInitializationSettings( + requestAlertPermission: false, + requestBadgePermission: false, + requestSoundPermission: false, + notificationCategories: [ + DarwinNotificationCategory( + _restEndCategory, + actions: [ + DarwinNotificationAction.plain( + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + labels.logSet, + ), + ], + ), + ], + ), + ), + ) + .then((_) {}); + } + + @override + Future requestPermissions(WorkoutNotificationLabels labels) async { + await _ensureInitialized(labels); + final android = _plugin + .resolvePlatformSpecificImplementation(); + final ios = _plugin.resolvePlatformSpecificImplementation(); + final granted = + await android?.requestNotificationsPermission() ?? + await ios?.requestPermissions(alert: true, sound: true); + _logger.fine('Notification permission granted: $granted'); + } + + @override + Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async { + await _ensureInitialized(labels); + await _plugin.zonedSchedule( + id: _notificationId, + scheduledDate: tz.TZDateTime.from(alarm.at, tz.UTC), + title: alarm.title, + body: alarm.body, + payload: alarm.payload.encode(), + androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle, + notificationDetails: NotificationDetails( + android: AndroidNotificationDetails( + _alarmChannelId, + labels.alarmChannel, + importance: Importance.high, + priority: Priority.high, + category: AndroidNotificationCategory.alarm, + visibility: NotificationVisibility.public, + actions: [ + if (alarm.canLogSet) + AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, labels.logSet), + ], + ), + iOS: DarwinNotificationDetails( + categoryIdentifier: alarm.canLogSet ? _restEndCategory : null, + ), + ), + ); + } + + @override + Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels) async { + await _ensureInitialized(labels); + final chronometerAt = controls.chronometerAt; + await _plugin.show( + id: _notificationId, + title: controls.title, + body: controls.body, + payload: controls.payload.encode(), + notificationDetails: NotificationDetails( + android: AndroidNotificationDetails( + _controlsChannelId, + labels.controlsChannel, + importance: Importance.low, + priority: Priority.low, + ongoing: true, + autoCancel: false, + onlyAlertOnce: true, + playSound: false, + enableVibration: false, + category: AndroidNotificationCategory.workout, + visibility: NotificationVisibility.public, + showWhen: chronometerAt != null, + when: chronometerAt?.millisecondsSinceEpoch, + usesChronometer: chronometerAt != null, + chronometerCountDown: controls.chronometerCountsDown, + actions: [ + if (controls.canSkipRest) + AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_SKIP_REST, labels.skipRest), + if (controls.canLogSet) + AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, labels.logSet), + ], + ), + ), + ); + } + + @override + Future cancelAll() async { + // This process has shown nothing yet, leftovers of an earlier one are + // cleaned up at startup + if (_initialized == null) { + return; + } + await _initialized; + await _plugin.cancel(id: _notificationId); + } +} + +final workoutNotificationServiceProvider = Provider((ref) { + if (!kIsWeb && + (defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS)) { + return LocalWorkoutNotificationService(); + } + return NoopWorkoutNotificationService(); +}); diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index a15b977e0..00a15dda1 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -28,10 +28,14 @@ import 'package:wger/core/errors.dart'; import 'package:wger/core/network/network_provider.dart'; import 'package:wger/core/widgets/error.dart'; import 'package:wger/core/widgets/progress_indicator.dart'; +import 'package:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; import 'package:wger/features/routines/screens/gym_mode.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'exercise_overview.dart'; import 'log_page.dart'; @@ -54,17 +58,22 @@ class _GymModeState extends ConsumerState { late Future _initData; bool _initialPageJumped = false; late final PageController _controller; + late final GymModeVisibleNotifier _visibility; @override void initState() { super.initState(); _controller = PageController(initialPage: 0); + _visibility = ref.read(gymModeVisibleProvider.notifier); _initData = _loadGymState(); } @override void dispose() { _controller.dispose(); + // Providers can't change while the tree is being finalized + final visibility = _visibility; + scheduleMicrotask(() => visibility.set(false)); super.dispose(); } @@ -75,6 +84,7 @@ class _GymModeState extends ConsumerState { // gym-state mutations with no await in between, and modifying a provider // during a life-cycle is not allowed. await yieldPastBuild(); + _visibility.set(true); final notifier = ref.read(routinesRiverpodProvider.notifier); final routineId = widget._args.routineId; @@ -107,10 +117,24 @@ class _GymModeState extends ConsumerState { ); await gymViewModel.loadPrefs(); gymViewModel.calculatePages(); + _requestNotificationPermissions(); return initialPage; } + /// Asked here rather than at app start, and only if a notification is wanted + void _requestNotificationPermissions() { + final gymState = ref.read(gymStateProvider); + final service = ref.read(workoutNotificationServiceProvider); + final wanted = + gymState.restAlarmEnabled || (service.supportsControls && gymState.showWorkoutNotification); + if (wanted && mounted) { + unawaited( + service.requestPermissions(WorkoutNotificationLabels.of(AppLocalizations.of(context))), + ); + } + } + List _getContent(GymModeState state) { final gymState = ref.watch(gymStateProvider); final List out = []; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index a33003716..e98c22ccb 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -380,6 +380,37 @@ "gymModeRestAlarmHelp": "System notification when the rest is over, also with the screen locked", "gymModeWorkoutNotification": "Workout notification", "gymModeWorkoutNotificationHelp": "Shows the rest and the next set, with buttons to log it or skip the rest", + "workoutNotificationRestOver": "Rest is over", + "workoutNotificationNext": "Next: {set}", + "@workoutNotificationNext": { + "description": "Notification text with the next planned set, e.g. 'Next: Bench press 3 × 100 kg'", + "placeholders": { + "set": { + "type": "String" + } + } + }, + "workoutNotificationSetOf": "Set {current} of {total}", + "@workoutNotificationSetOf": { + "placeholders": { + "current": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "workoutNotificationInProgress": "Workout in progress", + "workoutNotificationLogSet": "Log set", + "@workoutNotificationLogSet": { + "description": "Notification button that logs the next set with its planned values" + }, + "workoutNotificationSkipRest": "Skip rest", + "workoutNotificationChannel": "Workout", + "@workoutNotificationChannel": { + "description": "Name of the Android notification channel for the ongoing workout notification" + }, "duration": "Duration", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/main.dart b/lib/main.dart index 120a9dc34..6110c7d11 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -68,6 +68,7 @@ import 'package:wger/features/nutrition/screens/log_meals_screen.dart'; import 'package:wger/features/nutrition/screens/nutritional_diary_screen.dart'; import 'package:wger/features/nutrition/screens/nutritional_plan_screen.dart'; import 'package:wger/features/nutrition/screens/nutritional_plans_screen.dart'; +import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; import 'package:wger/features/routines/screens/gym_mode.dart'; import 'package:wger/features/routines/screens/routine_edit_screen.dart'; import 'package:wger/features/routines/screens/routine_list_screen.dart'; @@ -207,6 +208,8 @@ class MainApp extends ConsumerWidget { // Instantiates the singleton on first build; the provider subscribes to // incoming deep links as a side effect of being read. ref.watch(appLinkRouterProvider); + // Keeps the workout notifications in line with the gym state + ref.watch(workoutNotificationControllerProvider); // Read before the builder below: its callback runs during the child's // build, where ref.watch would be out of phase. diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart new file mode 100644 index 000000000..567adfcf5 --- /dev/null +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -0,0 +1,217 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +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:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/features/routines/providers/gym_state.dart'; +import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../test_data/routines.dart'; + +void main() { + final now = DateTime.utc(2025, 3, 29, 14, 33); + final i18n = lookupAppLocalizations(const Locale('en')); + late GymStateNotifier notifier; + + setUp(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + final container = ProviderContainer.test(); + notifier = container.read(gymStateProvider.notifier); + final routine = getTestRoutine(); + notifier.initData(routine, routine.days.first.id!, 1); + }); + + // Fixture: start, then bench press (overview, 3x log/timer, 120 s rest), + // then side raises (overview, 3x log/timer, no rest time), session, summary + List slotPages() => notifier.state.pages.expand((p) => p.slotPages).toList(); + List logs() => slotPages().where((p) => p.type == SlotPageType.log).toList(); + List timers() => slotPages().where((p) => p.type == SlotPageType.timer).toList(); + + WorkoutNotificationTarget build({bool withControls = true}) => buildWorkoutNotification( + notifier.state, + now: now, + i18n: i18n, + languageCode: 'en', + withControls: withControls, + ); + + void onPage(SlotPageEntry page, {DateTime? restStartedAt, DateTime? restEndsAt}) { + notifier.state = notifier.state.copyWith( + currentPage: page.pageIndex, + clearRest: true, + restStartedAt: restStartedAt, + restEndsAt: restEndsAt, + ); + } + + test('Nothing without an initialized gym state', () { + notifier.clear(); + + expect(build(), WorkoutNotificationTarget.none); + }); + + group('Rest', () { + test('A running countdown gets an alarm at its end and counting down controls', () { + final endsAt = now.add(const Duration(seconds: 90)); + final timer = timers().first; + onPage(timer, restStartedAt: now, restEndsAt: endsAt); + + final target = build(); + + expect(target.alarm!.at, endsAt); + expect(target.alarm!.title, 'Rest is over'); + expect(target.alarm!.body, 'Next: Bench press 3x100kg'); + expect(target.alarm!.canLogSet, isTrue); + expect(target.alarm!.payload.logSlotUuid, logs()[1].uuid); + expect(target.controls!.chronometerAt, endsAt); + expect(target.controls!.chronometerCountsDown, isTrue); + expect(target.controls!.canSkipRest, isTrue); + expect(target.controls!.payload.restSlotUuid, timer.uuid); + }); + + test('No alarm when the setting is off', () { + notifier.state = notifier.state.copyWith(restAlarmEnabled: false); + onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + + final target = build(); + + expect(target.alarm, isNull); + expect(target.controls, isNotNull); + }); + + test('A rest that is already over has no alarm and no chronometer', () { + onPage( + timers().first, + restStartedAt: now.subtract(const Duration(seconds: 150)), + restEndsAt: now.subtract(const Duration(seconds: 30)), + ); + + final target = build(); + + expect(target.alarm, isNull); + expect(target.controls!.title, 'Rest is over'); + expect(target.controls!.chronometerAt, isNull); + }); + + test('A rest that counts up shows the time since its start', () { + final startedAt = now.subtract(const Duration(seconds: 20)); + onPage(timers().last, restStartedAt: startedAt); + + final target = build(); + + expect(target.alarm, isNull); + expect(target.controls!.title, 'Pause'); + expect(target.controls!.chronometerAt, startedAt); + expect(target.controls!.chronometerCountsDown, isFalse); + }); + + test('The last rest of an exercise names the next one but cannot log it', () { + // The overview page of the next exercise comes in between + onPage(timers()[2], restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + + final target = build(); + + expect(target.alarm!.body, 'Next: Side raises 12x10kg'); + expect(target.alarm!.canLogSet, isFalse); + expect(target.controls!.canLogSet, isFalse); + }); + + test('A next set without planned values cannot be logged', () { + logs()[1].setConfigData! + ..repetitions = null + ..weight = null; + onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + + expect(build().alarm!.canLogSet, isFalse); + }); + + test('Without controls only the alarm remains', () { + onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + + final target = build(withControls: false); + + expect(target.alarm, isNotNull); + expect(target.controls, isNull); + }); + }); + + group('Other pages', () { + test('A set page shows the exercise and the set number', () { + onPage(logs()[1]); + + final controls = build().controls!; + + expect(controls.title, 'Bench press'); + expect(controls.body, 'Set 2 of 3 · 3x100kg'); + expect(controls.canLogSet, isTrue); + expect(controls.canSkipRest, isFalse); + expect(controls.payload.logSlotUuid, logs()[1].uuid); + }); + + test('A logged set cannot be logged again', () { + notifier.markSlotPageAsDone(logs()[1].uuid, isDone: true); + onPage(logs()[1]); + + expect(build().controls!.canLogSet, isFalse); + }); + + test('Any other page shows the workout in progress', () { + notifier.state = notifier.state.copyWith(currentPage: 0); + + final target = build(); + + expect(target.alarm, isNull); + expect(target.controls!.title, 'Workout in progress'); + expect(target.controls!.chronometerAt, notifier.state.workoutStart); + expect(target.controls!.canLogSet, isFalse); + }); + + test('Without controls there is nothing outside a rest', () { + onPage(logs()[1]); + + expect(build(withControls: false), WorkoutNotificationTarget.none); + }); + }); + + group('WorkoutNotificationPayload', () { + test('Survives the round trip as a string', () { + final payload = WorkoutNotificationPayload( + routineId: 1, + dayId: 2, + iteration: 3, + workoutStart: DateTime.utc(2025, 3, 29, 14, 33), + logSlotUuid: 'log', + restSlotUuid: 'rest', + ); + + expect(WorkoutNotificationPayload.decode(payload.encode()), payload); + }); + + test('Foreign or missing payloads decode to null', () { + expect(WorkoutNotificationPayload.decode(null), isNull); + expect(WorkoutNotificationPayload.decode('not json'), isNull); + expect(WorkoutNotificationPayload.decode('{"other": 1}'), isNull); + }); + }); +} diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart new file mode 100644 index 000000000..b7f254b41 --- /dev/null +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -0,0 +1,166 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:clock/clock.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.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:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; +import 'package:wger/features/routines/providers/gym_state.dart'; +import 'package:wger/features/routines/providers/gym_state_notifier.dart'; + +import '../../../../test_data/routines.dart'; +import 'workout_notification_controller_test.mocks.dart'; + +@GenerateMocks([WorkoutNotificationService]) +void main() { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + final now = DateTime.utc(2025, 3, 29, 14, 33); + late MockWorkoutNotificationService service; + late ProviderContainer container; + late GymStateNotifier gymState; + + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + service = MockWorkoutNotificationService(); + when(service.supportsControls).thenReturn(true); + when(service.cancelAll()).thenAnswer((_) async {}); + when(service.scheduleRestAlarm(any, any)).thenAnswer((_) async {}); + when(service.showControls(any, any)).thenAnswer((_) async {}); + + container = ProviderContainer.test( + overrides: [workoutNotificationServiceProvider.overrideWithValue(service)], + ); + container.read(workoutNotificationControllerProvider); + gymState = container.read(gymStateProvider.notifier); + }); + + /// Lets the controller's queued platform calls run + Future settle() => pumpEventQueue(); + + void initGymMode() { + final routine = getTestRoutine(); + gymState.initData(routine, routine.days.first.id!, 1); + } + + /// Moves to the first rest of the fixture (120 s), initializing if needed + Future startRest() async { + if (!gymState.state.isInitialized) { + initGymMode(); + } + final timer = gymState.state.pages + .expand((p) => p.slotPages) + .firstWhere((p) => p.type == SlotPageType.timer); + withClock(Clock.fixed(now), () => gymState.setCurrentPage(timer.pageIndex - 1)); + await withClock(Clock.fixed(now), () async { + gymState.setCurrentPage(timer.pageIndex); + await settle(); + }); + } + + test('A rest away from gym mode schedules the alarm and shows the controls', () async { + await startRest(); + + verifyInOrder([ + service.cancelAll(), + service.scheduleRestAlarm(argThat(isA()), any), + service.showControls(argThat(isA()), any), + ]); + }); + + test('Unchanged notifications cause no platform calls', () async { + await startRest(); + clearInteractions(service); + + // A state change that does not touch the notification + await withClock(Clock.fixed(now), () async { + gymState.setShowDistinctLogs(false); + await settle(); + }); + + verifyNever(service.cancelAll()); + verifyNever(service.scheduleRestAlarm(any, any)); + verifyNever(service.showControls(any, any)); + }); + + test('Nothing while gym mode is on screen, back when the app goes to the background', () async { + await startRest(); + clearInteractions(service); + + container.read(gymModeVisibleProvider.notifier).set(true); + await settle(); + verify(service.cancelAll()).called(1); + verifyNever(service.scheduleRestAlarm(any, any)); + verifyNever(service.showControls(any, any)); + + await withClock(Clock.fixed(now), () async { + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + await settle(); + }); + verify(service.scheduleRestAlarm(any, any)).called(1); + verify(service.showControls(any, any)).called(1); + }); + + test('Ending gym mode removes everything', () async { + await startRest(); + clearInteractions(service); + + gymState.clear(); + await settle(); + + verify(service.cancelAll()).called(1); + verifyNever(service.scheduleRestAlarm(any, any)); + verifyNever(service.showControls(any, any)); + }); + + test('Each setting only switches off its own notification', () async { + initGymMode(); + gymState.state = gymState.state.copyWith(restAlarmEnabled: false); + await startRest(); + verifyNever(service.scheduleRestAlarm(any, any)); + verify(service.showControls(any, any)); + + clearInteractions(service); + await withClock(Clock.fixed(now), () async { + gymState.state = gymState.state.copyWith( + restAlarmEnabled: true, + showWorkoutNotification: false, + ); + await settle(); + }); + verify(service.scheduleRestAlarm(any, any)).called(1); + verifyNever(service.showControls(any, any)); + }); + + test('No controls on platforms without them', () async { + when(service.supportsControls).thenReturn(false); + + await startRest(); + + verify(service.scheduleRestAlarm(any, any)).called(1); + verifyNever(service.showControls(any, any)); + }); +} diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart new file mode 100644 index 000000000..8239ab060 --- /dev/null +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -0,0 +1,86 @@ +// Mocks generated by Mockito from annotations +// in wger/test/features/routines/notifications/workout_notification_controller_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes + +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/routines/notifications/workout_notification_content.dart' as _i4; +import 'package:wger/features/routines/notifications/workout_notification_service.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: experimental_member_use +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [WorkoutNotificationService]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNotificationService { + MockWorkoutNotificationService() { + _i1.throwOnMissingStub(this); + } + + @override + bool get supportsControls => + (super.noSuchMethod( + Invocation.getter(#supportsControls), + returnValue: false, + ) + as bool); + + @override + _i3.Future requestPermissions(_i4.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#requestPermissions, [labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future scheduleRestAlarm( + _i4.RestAlarm? alarm, + _i4.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#scheduleRestAlarm, [alarm, labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future showControls( + _i4.WorkoutControls? controls, + _i4.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#showControls, [controls, labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future cancelAll() => + (super.noSuchMethod( + Invocation.method(#cancelAll, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index e600e91d7..392ec6da5 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -522,9 +522,6 @@ void main() { }); group('GymStateNotifier notification settings', () { - // PreferenceHelper keeps the store of the first test, start from empty - setUp(() => PreferenceHelper.asyncPref.clear()); - test('Both are on without stored preferences', () async { await notifier.loadPrefs(); diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index 14bacae1d..885b814d3 100644 --- a/test/features/routines/screens/gym_mode_test.dart +++ b/test/features/routines/screens/gym_mode_test.dart @@ -36,6 +36,8 @@ import 'package:wger/features/exercises/providers/exercises_notifier.dart'; import 'package:wger/features/routines/models/repetition_unit.dart'; import 'package:wger/features/routines/models/session.dart'; import 'package:wger/features/routines/models/weight_unit.dart'; +import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; @@ -67,6 +69,7 @@ import 'gym_mode_test.mocks.dart'; TrophyRepository, WorkoutLogRepository, UserProfileRepository, + WorkoutNotificationService, ]) void main() { installFakeConnectivity(); @@ -81,9 +84,13 @@ void main() { final mockRoutinesRepo = MockRoutinesRepository(); final mockLogRepo = MockWorkoutLogRepository(); final mockUserProfileRepo = MockUserProfileRepository(); + late MockWorkoutNotificationService mockNotificationService; setUp(() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + mockNotificationService = MockWorkoutNotificationService(); + when(mockNotificationService.supportsControls).thenReturn(true); + when(mockNotificationService.requestPermissions(any)).thenAnswer((_) async {}); when(mockUserProfileRepo.watchDrift()).thenAnswer((_) => Stream.value(null)); when(mockSessionRepo.watchAllDrift()).thenAnswer( (_) => Stream>.multi((controller) { @@ -132,6 +139,7 @@ void main() { workoutSessionRepositoryProvider.overrideWithValue(mockSessionRepo), workoutLogRepositoryProvider.overrideWithValue(mockLogRepo), userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepo), + workoutNotificationServiceProvider.overrideWithValue(mockNotificationService), ...extraOverrides, // The repetition + weight unit catalogues are tiny direct-Drift // stream providers, overriding them inline is the established @@ -574,6 +582,51 @@ void main() { semanticsEnabled: false, ); + testWidgets( + 'opening gym mode asks for the notification permission and hides the notifications', + (WidgetTester tester) async { + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await tester.pumpWidget(renderGymMode()); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + final container = riverpod.ProviderScope.containerOf( + tester.element(find.byType(StartPage)), + ); + + verify(mockNotificationService.requestPermissions(any)).called(1); + expect(container.read(gymModeVisibleProvider), isTrue); + + key.currentState!.pop(); + await tester.pumpAndSettle(); + expect(container.read(gymModeVisibleProvider), isFalse); + }); + }, + semanticsEnabled: false, + ); + + testWidgets( + 'no permission request with both notification settings off', + (WidgetTester tester) async { + await PreferenceHelper.asyncPref.setBool(PREFS_REST_ALARM, false); + await PreferenceHelper.asyncPref.setBool(PREFS_WORKOUT_NOTIFICATION, false); + addTearDown(() async { + await PreferenceHelper.asyncPref.remove(PREFS_REST_ALARM); + await PreferenceHelper.asyncPref.remove(PREFS_WORKOUT_NOTIFICATION); + }); + + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await tester.pumpWidget(renderGymMode()); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + + verifyNever(mockNotificationService.requestPermissions(any)); + }); + }, + semanticsEnabled: false, + ); + testWidgets( 'resuming an interrupted session reopens the page it was left on', (WidgetTester tester) async { diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index bd57a091e..a01a75ffb 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i10; import 'package:mockito/mockito.dart' as _i1; @@ -27,6 +28,8 @@ import 'package:wger/features/routines/models/session.dart' as _i2; import 'package:wger/features/routines/models/slot.dart' as _i5; import 'package:wger/features/routines/models/slot_entry.dart' as _i6; import 'package:wger/features/routines/models/weight_unit.dart' as _i20; +import 'package:wger/features/routines/notifications/workout_notification_content.dart' as _i32; +import 'package:wger/features/routines/notifications/workout_notification_service.dart' as _i31; import 'package:wger/features/routines/providers/routines_repository.dart' as _i19; import 'package:wger/features/routines/providers/workout_logs_repository.dart' as _i27; import 'package:wger/features/routines/providers/workout_session_repository.dart' as _i9; @@ -614,3 +617,64 @@ class MockUserProfileRepository extends _i1.Mock implements _i29.UserProfileRepo ) as _i10.Future); } + +/// A class which mocks [WorkoutNotificationService]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNotificationService { + MockWorkoutNotificationService() { + _i1.throwOnMissingStub(this); + } + + @override + bool get supportsControls => + (super.noSuchMethod( + Invocation.getter(#supportsControls), + returnValue: false, + ) + as bool); + + @override + _i10.Future requestPermissions( + _i32.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#requestPermissions, [labels]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + + @override + _i10.Future scheduleRestAlarm( + _i32.RestAlarm? alarm, + _i32.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#scheduleRestAlarm, [alarm, labels]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + + @override + _i10.Future showControls( + _i32.WorkoutControls? controls, + _i32.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#showControls, [controls, labels]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + + @override + _i10.Future cancelAll() => + (super.noSuchMethod( + Invocation.method(#cancelAll, []), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); +} diff --git a/test/helpers/fake_auth_environment.dart b/test/helpers/fake_auth_environment.dart index 7ec8a5815..1e5fb4c92 100644 --- a/test/helpers/fake_auth_environment.dart +++ b/test/helpers/fake_auth_environment.dart @@ -27,9 +27,8 @@ import 'package:wger/core/shared_preferences.dart'; /// its eager `build()`. Any screen test that transitively subscribes /// to `authProvider` (most do, via `wgerBaseProvider`) must call this. /// -/// Call from the top of `main()` so the [SharedPreferencesAsyncPlatform] -/// instance is installed before [PreferenceHelper]'s static-final -/// singleton initialises on first read. +/// Call from the top of `main()`: it registers a `setUp` that empties the +/// [SharedPreferencesAsyncPlatform] store before every test. void installFakeAuthEnvironment() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); From 5668ce985e8999e298e7af48cef395f9092c1c43 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 11:12:53 +0100 Subject: [PATCH 08/28] Handle the workout notification actions and taps --- .../workout_notification_content.dart | 25 ++- .../workout_notification_controller.dart | 168 ++++++++++++---- .../workout_notification_service.dart | 90 ++++++++- lib/l10n/app_en.arb | 2 + .../workout_notification_controller_test.dart | 181 +++++++++++++++++- ...ut_notification_controller_test.mocks.dart | 75 ++++++++ .../routines/screens/gym_mode_test.mocks.dart | 21 ++ 7 files changed, 514 insertions(+), 48 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index 99b7730e2..15b403037 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -46,6 +46,14 @@ class WorkoutNotificationPayload extends Equatable { this.restSlotUuid, }); + /// Whether this belongs to the session [state] is running + bool matches(GymModeState state) => + state.isInitialized && + state.routine.id == routineId && + state.dayId == dayId && + state.iteration == iteration && + state.workoutStart.isAtSameMomentAs(workoutStart); + String encode() => jsonEncode({ 'routineId': routineId, 'dayId': dayId, @@ -140,22 +148,35 @@ class WorkoutNotificationLabels extends Equatable { final String skipRest; final String controlsChannel; final String alarmChannel; + final String notLoggedTitle; + final String notLoggedBody; const WorkoutNotificationLabels({ required this.logSet, required this.skipRest, required this.controlsChannel, required this.alarmChannel, + required this.notLoggedTitle, + required this.notLoggedBody, }); WorkoutNotificationLabels.of(AppLocalizations i18n) : logSet = i18n.workoutNotificationLogSet, skipRest = i18n.workoutNotificationSkipRest, controlsChannel = i18n.workoutNotificationChannel, - alarmChannel = i18n.gymModeRestAlarm; + alarmChannel = i18n.gymModeRestAlarm, + notLoggedTitle = i18n.workoutNotificationNotLoggedTitle, + notLoggedBody = i18n.workoutNotificationNotLoggedBody; @override - List get props => [logSet, skipRest, controlsChannel, alarmChannel]; + List get props => [ + logSet, + skipRest, + controlsChannel, + alarmChannel, + notLoggedTitle, + notLoggedBody, + ]; } /// What the OS should show for the workout, nothing if both are null diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index 55e27761f..3b8a6f6e4 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -17,6 +17,7 @@ */ import 'dart:async'; +import 'dart:isolate'; import 'dart:ui'; import 'package:clock/clock.dart'; @@ -24,9 +25,11 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/core/keys.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/features/routines/screens/gym_mode.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; /// Whether the gym mode screen is mounted @@ -46,23 +49,65 @@ class GymModeVisibleNotifier extends Notifier { } } -/// Keeps the platform notifications in line with the desired target +/// Keeps the platform notifications in line with the gym state and carries +/// out what the user does with them class WorkoutNotificationController { final _logger = Logger('WorkoutNotificationController'); + final Ref _ref; final WorkoutNotificationService _service; - var _shown = WorkoutNotificationTarget.none; + /// What the platform shows, null if unknown + WorkoutNotificationTarget? _shown = WorkoutNotificationTarget.none; Future _queue = Future.value(); - WorkoutNotificationController(this._service); + WorkoutNotificationController(this._ref, this._service); - /// Applies [target], in call order. Unchanged targets cause no platform calls. - Future apply(WorkoutNotificationTarget target, WorkoutNotificationLabels labels) { + /// The locale the app renders in, also without a BuildContext + Locale get _locale => + _ref.read(appSettingsProvider).value?.userLocale ?? + basicLocaleListResolution( + PlatformDispatcher.instance.locales, + AppLocalizations.supportedLocales, + ); + + WorkoutNotificationLabels get labels => + WorkoutNotificationLabels.of(lookupAppLocalizations(_locale)); + + /// Runs platform calls one after the other, in call order + Future _enqueue(Future Function() step) { return _queue = _queue - .then((_) => _apply(target, labels)) + .then((_) => step()) .catchError((Object e) => _logger.warning('Could not update the notification: $e')); } + /// Shows what the gym state calls for. Nothing while gym mode is on screen, + /// the screen itself shows the rest. + void update() { + final state = _ref.read(gymStateProvider); + final inForeground = !_backgroundStates.contains(WidgetsBinding.instance.lifecycleState); + final locale = _locale; + final i18n = lookupAppLocalizations(locale); + + final target = inForeground && _ref.read(gymModeVisibleProvider) + ? WorkoutNotificationTarget.none + : buildWorkoutNotification( + state, + now: clock.now(), + i18n: i18n, + languageCode: locale.languageCode, + withControls: _service.supportsControls && state.showWorkoutNotification, + ); + final labels = WorkoutNotificationLabels.of(i18n); + unawaited(_enqueue(() => _apply(target, labels))); + } + + /// Like [update], also when nothing seems to have changed: the platform may + /// have removed the notification on its own + void refresh() { + unawaited(_enqueue(() async => _shown = null)); + update(); + } + Future _apply(WorkoutNotificationTarget target, WorkoutNotificationLabels labels) async { if (target == _shown) { return; @@ -78,16 +123,54 @@ class WorkoutNotificationController { await _service.showControls(target.controls!, labels); } } -} -/// The locale the app renders in, also without a BuildContext -Locale _appLocale(Ref ref) { - final userLocale = ref.read(appSettingsProvider).value?.userLocale; - return userLocale ?? - basicLocaleListResolution( - PlatformDispatcher.instance.locales, - AppLocalizations.supportedLocales, - ); + /// Carries out a notification action. Stale actions only refresh the + /// notification, without a running session the user is sent to the app. + Future handleAction(String? actionId, String? encodedPayload) async { + final state = _ref.read(gymStateProvider); + if (!state.isInitialized) { + // E.g. iOS started the app in the background just for this action + await _enqueue(() => _service.showNotLogged(labels)); + return; + } + + final payload = WorkoutNotificationPayload.decode(encodedPayload); + final notifier = _ref.read(gymStateProvider.notifier); + if (payload != null && payload.matches(state)) { + try { + switch (actionId) { + case WORKOUT_NOTIFICATION_ACTION_LOG_SET: + final uuid = payload.logSlotUuid; + if (uuid != null) { + await notifier.logPlannedSet(uuid); + } + case WORKOUT_NOTIFICATION_ACTION_SKIP_REST: + if (state.getSlotEntryPageByIndex()?.uuid == payload.restSlotUuid) { + notifier.skipRest(); + } + } + } catch (e) { + _logger.warning('Notification action $actionId failed: $e'); + } + } + + // The platform removes the notification on an action + refresh(); + } + + /// Opens the running gym mode when the notification itself is tapped + void handleTap(String? encodedPayload) { + final payload = WorkoutNotificationPayload.decode(encodedPayload); + if (payload == null || + !payload.matches(_ref.read(gymStateProvider)) || + _ref.read(gymModeVisibleProvider)) { + return; + } + navigatorKey.currentState?.pushNamed( + GymModeScreen.routeName, + arguments: GymModeArguments(payload.routineId, payload.dayId, payload.iteration), + ); + } } const _backgroundStates = { @@ -96,34 +179,45 @@ const _backgroundStates = { AppLifecycleState.detached, }; -/// Derives the workout notifications from the gym state. While gym mode is on -/// screen there are none, the screen itself shows the rest. +/// Bootstraps the workout notifications, read once at app start final workoutNotificationControllerProvider = Provider((ref) { final service = ref.read(workoutNotificationServiceProvider); - final controller = WorkoutNotificationController(service); + final controller = WorkoutNotificationController(ref, service); + unawaited(service.initialize(controller.labels, onTap: controller.handleTap)); - void update() { - final state = ref.read(gymStateProvider); - final inForeground = !_backgroundStates.contains(WidgetsBinding.instance.lifecycleState); - final locale = _appLocale(ref); - final i18n = lookupAppLocalizations(locale); + // Actions arrive from the background isolate + final port = ReceivePort(); + IsolateNameServer.removePortNameMapping(WORKOUT_NOTIFICATION_PORT); + IsolateNameServer.registerPortWithName(port.sendPort, WORKOUT_NOTIFICATION_PORT); + port.listen((message) { + final [actionId, payload] = message as List; + unawaited(controller.handleAction(actionId as String?, payload as String?)); + }); - final target = inForeground && ref.read(gymModeVisibleProvider) - ? WorkoutNotificationTarget.none - : buildWorkoutNotification( - state, - now: clock.now(), - i18n: i18n, - languageCode: locale.languageCode, - withControls: service.supportsControls && state.showWorkoutNotification, - ); - unawaited(controller.apply(target, WorkoutNotificationLabels.of(i18n))); + // Notifications of an earlier process outlive it. Only cleaned up once the + // app is really opened: iOS also starts it in the background for an action. + void cleanUpWhenIdle() { + if (!ref.read(gymStateProvider).isInitialized) { + controller.refresh(); + } } - ref.listen(gymStateProvider, (_, _) => update()); - ref.listen(gymModeVisibleProvider, (_, _) => update()); - final lifecycle = AppLifecycleListener(onStateChange: (_) => update()); - ref.onDispose(lifecycle.dispose); + if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed) { + cleanUpWhenIdle(); + } + + ref.listen(gymStateProvider, (_, _) => controller.update()); + ref.listen(gymModeVisibleProvider, (_, _) => controller.update()); + final lifecycle = AppLifecycleListener( + onStateChange: (_) => controller.update(), + onResume: cleanUpWhenIdle, + ); + + ref.onDispose(() { + lifecycle.dispose(); + IsolateNameServer.removePortNameMapping(WORKOUT_NOTIFICATION_PORT); + port.close(); + }); return controller; }); diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 50086015b..2d0f7f7d5 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -16,16 +16,46 @@ * along with this program. If not, see . */ +import 'dart:ui'; + import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:timezone/timezone.dart' as tz; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; const WORKOUT_NOTIFICATION_ACTION_LOG_SET = 'log_set'; const WORKOUT_NOTIFICATION_ACTION_SKIP_REST = 'skip_rest'; +/// The main isolate receives notification actions on this port +const WORKOUT_NOTIFICATION_PORT = 'wger_workout_actions'; + +/// Called with the payload when the user taps the notification itself +typedef WorkoutNotificationTapHandler = void Function(String? payload); + +/// Runs in a separate isolate without the gym state, so it only forwards the +/// action. Without a running app nothing is logged, the user is sent there. +@pragma('vm:entry-point') +Future workoutNotificationBackgroundHandler(NotificationResponse response) async { + final port = IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT); + if (port != null) { + port.send([response.actionId, response.payload]); + return; + } + + final locale = basicLocaleListResolution( + PlatformDispatcher.instance.locales, + AppLocalizations.supportedLocales, + ); + final labels = WorkoutNotificationLabels.of(lookupAppLocalizations(locale)); + final service = LocalWorkoutNotificationService(); + await service.initialize(labels); + await service.showNotLogged(labels); +} + /// Shows the workout notifications on the platform. /// /// The controls and the rest alarm share one notification, so the alarm @@ -34,12 +64,18 @@ abstract class WorkoutNotificationService { /// Whether the platform has the ongoing controls notification bool get supportsControls; + /// Registers the actions and [onTap], before anything else is shown + Future initialize(WorkoutNotificationLabels labels, {WorkoutNotificationTapHandler? onTap}); + Future requestPermissions(WorkoutNotificationLabels labels); Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels); Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels); + /// Tells the user that an action was not carried out and the app is needed + Future showNotLogged(WorkoutNotificationLabels labels); + /// Removes the shown notification and a pending rest alarm Future cancelAll(); } @@ -49,6 +85,12 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { @override bool get supportsControls => false; + @override + Future initialize( + WorkoutNotificationLabels labels, { + WorkoutNotificationTapHandler? onTap, + }) async {} + @override Future requestPermissions(WorkoutNotificationLabels labels) async {} @@ -58,6 +100,9 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { @override Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels) async {} + @override + Future showNotLogged(WorkoutNotificationLabels labels) async {} + @override Future cancelAll() async {} } @@ -76,8 +121,12 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { @override bool get supportsControls => defaultTargetPlatform == TargetPlatform.android; - /// The iOS action labels are registered once, with the first labels seen - Future _ensureInitialized(WorkoutNotificationLabels labels) { + @override + Future initialize( + WorkoutNotificationLabels labels, { + WorkoutNotificationTapHandler? onTap, + }) { + // The iOS action labels are registered once, with the first labels seen return _initialized ??= _plugin .initialize( settings: InitializationSettings( @@ -99,10 +148,21 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ], ), ), + onDidReceiveNotificationResponse: (response) { + // Actions go to the background handler, this is a tap on the body + if (response.notificationResponseType == + NotificationResponseType.selectedNotification) { + onTap?.call(response.payload); + } + }, + onDidReceiveBackgroundNotificationResponse: workoutNotificationBackgroundHandler, ) .then((_) {}); } + Future _ensureInitialized(WorkoutNotificationLabels labels) => + _initialized ?? initialize(labels); + @override Future requestPermissions(WorkoutNotificationLabels labels) async { await _ensureInitialized(labels); @@ -182,13 +242,29 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ); } + @override + Future showNotLogged(WorkoutNotificationLabels labels) async { + await _ensureInitialized(labels); + await _plugin.show( + id: _notificationId, + title: labels.notLoggedTitle, + body: labels.notLoggedBody, + notificationDetails: NotificationDetails( + android: AndroidNotificationDetails( + _alarmChannelId, + labels.alarmChannel, + importance: Importance.high, + priority: Priority.high, + ), + iOS: const DarwinNotificationDetails(), + ), + ); + } + @override Future cancelAll() async { - // This process has shown nothing yet, leftovers of an earlier one are - // cleaned up at startup - if (_initialized == null) { - return; - } + // The app initializes the service at startup, so this also reaches + // notifications left behind by an earlier process await _initialized; await _plugin.cancel(id: _notificationId); } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8c0a14e47..7c8418d6a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -407,6 +407,8 @@ "description": "Notification button that logs the next set with its planned values" }, "workoutNotificationSkipRest": "Skip rest", + "workoutNotificationNotLoggedTitle": "Set not logged", + "workoutNotificationNotLoggedBody": "Open gym mode to continue the workout", "workoutNotificationChannel": "Workout", "@workoutNotificationChannel": { "description": "Name of the Android notification channel for the ongoing workout notification" diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index b7f254b41..92b572131 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +import 'dart:ui'; + import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -24,20 +26,24 @@ import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.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:wger/core/keys.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_repository.dart'; +import 'package:wger/features/routines/screens/gym_mode.dart'; import '../../../../test_data/routines.dart'; import 'workout_notification_controller_test.mocks.dart'; -@GenerateMocks([WorkoutNotificationService]) +@GenerateMocks([WorkoutNotificationService, WorkoutLogRepository]) void main() { final binding = TestWidgetsFlutterBinding.ensureInitialized(); final now = DateTime.utc(2025, 3, 29, 14, 33); late MockWorkoutNotificationService service; + late MockWorkoutLogRepository logRepo; late ProviderContainer container; late GymStateNotifier gymState; @@ -49,9 +55,16 @@ void main() { when(service.cancelAll()).thenAnswer((_) async {}); when(service.scheduleRestAlarm(any, any)).thenAnswer((_) async {}); when(service.showControls(any, any)).thenAnswer((_) async {}); + when(service.showNotLogged(any)).thenAnswer((_) async {}); + when(service.initialize(any, onTap: anyNamed('onTap'))).thenAnswer((_) async {}); + logRepo = MockWorkoutLogRepository(); + when(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); container = ProviderContainer.test( - overrides: [workoutNotificationServiceProvider.overrideWithValue(service)], + overrides: [ + workoutNotificationServiceProvider.overrideWithValue(service), + workoutLogRepositoryProvider.overrideWithValue(logRepo), + ], ); container.read(workoutNotificationControllerProvider); gymState = container.read(gymStateProvider.notifier); @@ -163,4 +176,168 @@ void main() { verify(service.scheduleRestAlarm(any, any)).called(1); verifyNever(service.showControls(any, any)); }); + + group('Startup', () { + test('Initializes the service with the tap handler', () { + verify(service.initialize(any, onTap: argThat(isNotNull, named: 'onTap'))).called(1); + }); + + test('Leftovers of an earlier run are removed when the app comes to the front', () async { + await settle(); + clearInteractions(service); + + // The listener only accepts single steps + [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ].forEach(binding.handleAppLifecycleStateChanged); + await settle(); + + verify(service.cancelAll()).called(1); + }); + }); + + group('Actions', () { + SlotPageEntry slotPage(int index) => gymState.state.getSlotEntryPageByIndex(index)!; + + /// The payload the notification on the current page carries + String payloadFor({String? logSlotUuid, String? restSlotUuid, DateTime? workoutStart}) => + WorkoutNotificationPayload( + routineId: gymState.state.routine.id!, + dayId: gymState.state.dayId, + iteration: gymState.state.iteration, + workoutStart: workoutStart ?? gymState.state.workoutStart, + logSlotUuid: logSlotUuid, + restSlotUuid: restSlotUuid, + ).encode(); + + test('"Log set" from the rest logs the next set and shows the next rest', () async { + await startRest(); + final rest = gymState.state.currentPage; + clearInteractions(service); + + await withClock(Clock.fixed(now), () async { + await container + .read(workoutNotificationControllerProvider) + .handleAction( + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + payloadFor(logSlotUuid: slotPage(rest + 1).uuid), + ); + await settle(); + }); + + verify(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1); + expect(gymState.state.currentPage, rest + 2); + final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; + expect((alarms.last as RestAlarm).payload.restSlotUuid, slotPage(rest + 2).uuid); + }); + + test('Actions arrive through the port from the background isolate', () async { + await startRest(); + final rest = gymState.state.currentPage; + + IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT)!.send([ + WORKOUT_NOTIFICATION_ACTION_SKIP_REST, + payloadFor(restSlotUuid: slotPage(rest).uuid), + ]); + await settle(); + + expect(gymState.state.currentPage, rest + 1); + }); + + test('A stale action changes nothing but shows the notification again', () async { + await startRest(); + final rest = gymState.state.currentPage; + clearInteractions(service); + + await withClock(Clock.fixed(now), () async { + final controller = container.read(workoutNotificationControllerProvider); + // From another session + await controller.handleAction( + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + payloadFor( + logSlotUuid: slotPage(rest + 1).uuid, + workoutStart: DateTime.utc(2020), + ), + ); + // For a rest the user already left + await controller.handleAction( + WORKOUT_NOTIFICATION_ACTION_SKIP_REST, + payloadFor(restSlotUuid: slotPage(rest - 2).uuid), + ); + await settle(); + }); + + verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + expect(gymState.state.currentPage, rest); + verify(service.cancelAll()).called(2); + verify(service.showControls(any, any)).called(2); + }); + + test('Without a running session the user is sent to the app', () async { + await container + .read(workoutNotificationControllerProvider) + .handleAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, null); + await settle(); + + verify(service.showNotLogged(any)).called(1); + verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + }); + }); + + group('Tap on the notification', () { + Future pumpApp(WidgetTester tester) async { + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + navigatorKey: navigatorKey, + home: const Text('home'), + routes: {GymModeScreen.routeName: (_) => const Text('gym mode')}, + ), + ), + ); + } + + String currentPayload() => WorkoutNotificationPayload( + routineId: gymState.state.routine.id!, + dayId: gymState.state.dayId, + iteration: gymState.state.iteration, + workoutStart: gymState.state.workoutStart, + ).encode(); + + testWidgets('Opens the running gym mode', (tester) async { + initGymMode(); + await pumpApp(tester); + + container.read(workoutNotificationControllerProvider).handleTap(currentPayload()); + await tester.pumpAndSettle(); + + expect(find.text('gym mode'), findsOneWidget); + }); + + testWidgets('Stays put for another session or with gym mode on screen', (tester) async { + initGymMode(); + await pumpApp(tester); + final controller = container.read(workoutNotificationControllerProvider); + + controller.handleTap( + WorkoutNotificationPayload( + routineId: gymState.state.routine.id!, + dayId: gymState.state.dayId, + iteration: gymState.state.iteration, + workoutStart: DateTime.utc(2020), + ).encode(), + ); + container.read(gymModeVisibleProvider.notifier).set(true); + controller.handleTap(currentPayload()); + await tester.pumpAndSettle(); + + expect(find.text('gym mode'), findsNothing); + }); + }); } diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index 8239ab060..7bf6d21b4 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -7,8 +7,10 @@ import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/routines/models/log.dart' as _i6; import 'package:wger/features/routines/notifications/workout_notification_content.dart' as _i4; import 'package:wger/features/routines/notifications/workout_notification_service.dart' as _i2; +import 'package:wger/features/routines/providers/workout_logs_repository.dart' as _i5; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -42,6 +44,18 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti ) as bool); + @override + _i3.Future initialize( + _i4.WorkoutNotificationLabels? labels, { + _i2.WorkoutNotificationTapHandler? onTap, + }) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels], {#onTap: onTap}), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future requestPermissions(_i4.WorkoutNotificationLabels? labels) => (super.noSuchMethod( @@ -75,6 +89,15 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti ) as _i3.Future); + @override + _i3.Future showNotLogged(_i4.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#showNotLogged, [labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future cancelAll() => (super.noSuchMethod( @@ -84,3 +107,55 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti ) as _i3.Future); } + +/// A class which mocks [WorkoutLogRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutLogRepository extends _i1.Mock implements _i5.WorkoutLogRepository { + MockWorkoutLogRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchLogsByExerciseDrift({ + int? routineId, + required int? exerciseId, + DateTime? since, + }) => + (super.noSuchMethod( + Invocation.method(#watchLogsByExerciseDrift, [], { + #routineId: routineId, + #exerciseId: exerciseId, + #since: since, + }), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i6.Log? log) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [log]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i6.Log? log, {int? dayId}) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [log], {#dayId: dayId}), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index a01a75ffb..8142901c2 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -634,6 +634,18 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot ) as bool); + @override + _i10.Future initialize( + _i32.WorkoutNotificationLabels? labels, { + _i31.WorkoutNotificationTapHandler? onTap, + }) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels], {#onTap: onTap}), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + @override _i10.Future requestPermissions( _i32.WorkoutNotificationLabels? labels, @@ -669,6 +681,15 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot ) as _i10.Future); + @override + _i10.Future showNotLogged(_i32.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#showNotLogged, [labels]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + @override _i10.Future cancelAll() => (super.noSuchMethod( From 6ce9f4bb0db6d27889879a8d41fbb25b0532cb09 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 11:28:45 +0100 Subject: [PATCH 09/28] Schedule exact rest alarms on Android and add a status bar icon --- android/app/src/main/AndroidManifest.xml | 2 + .../src/main/res/drawable/ic_stat_wger.xml | 11 ++ android/app/src/main/res/raw/keep.xml | 4 + .../workout_notification_service.dart | 36 ++++- .../routines/widgets/gym_mode/start_page.dart | 23 +++- lib/l10n/app_en.arb | 2 + ...ut_notification_controller_test.mocks.dart | 17 +++ .../workout_notification_service_test.dart | 111 ++++++++++++++++ .../routines/screens/gym_mode_test.mocks.dart | 17 +++ .../widgets/gym_mode/start_page_test.dart | 46 +++++++ .../gym_mode/start_page_test.mocks.dart | 124 ++++++++++++++++++ 11 files changed, 390 insertions(+), 3 deletions(-) create mode 100644 android/app/src/main/res/drawable/ic_stat_wger.xml create mode 100644 android/app/src/main/res/raw/keep.xml create mode 100644 test/features/routines/notifications/workout_notification_service_test.dart create mode 100644 test/features/routines/widgets/gym_mode/start_page_test.mocks.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 9e65ff240..c394fde5b 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -8,6 +8,8 @@ + + + + + diff --git a/android/app/src/main/res/raw/keep.xml b/android/app/src/main/res/raw/keep.xml new file mode 100644 index 000000000..2a8d6c080 --- /dev/null +++ b/android/app/src/main/res/raw/keep.xml @@ -0,0 +1,4 @@ + + + diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 2d0f7f7d5..074cc0949 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -69,6 +69,12 @@ abstract class WorkoutNotificationService { Future requestPermissions(WorkoutNotificationLabels labels); + /// Whether rest alarms fire on time. Without, Android may delay them. + Future canScheduleExactAlarms(); + + /// Sends the user to the system setting for exact alarms + Future requestExactAlarms(); + Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels); Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels); @@ -94,6 +100,12 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { @override Future requestPermissions(WorkoutNotificationLabels labels) async {} + @override + Future canScheduleExactAlarms() async => true; + + @override + Future requestExactAlarms() async {} + @override Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async {} @@ -130,7 +142,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { return _initialized ??= _plugin .initialize( settings: InitializationSettings( - android: const AndroidInitializationSettings('@mipmap/ic_launcher'), + android: const AndroidInitializationSettings('ic_stat_wger'), iOS: DarwinInitializationSettings( requestAlertPermission: false, requestBadgePermission: false, @@ -175,16 +187,31 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { _logger.fine('Notification permission granted: $granted'); } + AndroidFlutterLocalNotificationsPlugin? get _android => + _plugin.resolvePlatformSpecificImplementation(); + + @override + Future canScheduleExactAlarms() async => + await _android?.canScheduleExactNotifications() ?? true; + + @override + Future requestExactAlarms() async { + await _android?.requestExactAlarmsPermission(); + } + @override Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async { await _ensureInitialized(labels); + final exact = await canScheduleExactAlarms(); await _plugin.zonedSchedule( id: _notificationId, scheduledDate: tz.TZDateTime.from(alarm.at, tz.UTC), title: alarm.title, body: alarm.body, payload: alarm.payload.encode(), - androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle, + androidScheduleMode: exact + ? AndroidScheduleMode.exactAllowWhileIdle + : AndroidScheduleMode.inexactAllowWhileIdle, notificationDetails: NotificationDetails( android: AndroidNotificationDetails( _alarmChannelId, @@ -270,6 +297,11 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { } } +/// Whether rest alarms fire on time, rechecked whenever it is shown again +final exactAlarmsAllowedProvider = FutureProvider.autoDispose( + (ref) => ref.read(workoutNotificationServiceProvider).canScheduleExactAlarms(), +); + final workoutNotificationServiceProvider = Provider((ref) { if (!kIsWeb && (defaultTargetPlatform == TargetPlatform.android || diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index db541fc63..046ef90b0 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -22,6 +22,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/exercises/widgets/images.dart'; import 'package:wger/features/routines/models/day.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/navigation.dart'; @@ -55,6 +56,7 @@ class _GymModeOptionsState extends ConsumerState { Widget build(BuildContext context) { final gymState = ref.watch(gymStateProvider); final gymNotifier = ref.watch(gymStateProvider.notifier); + final isAndroid = !kIsWeb && defaultTargetPlatform == TargetPlatform.android; final i18n = AppLocalizations.of(context); // If the value in the provider changed, update the controller text @@ -176,8 +178,27 @@ class _GymModeOptionsState extends ConsumerState { ? (value) => gymNotifier.setRestAlarmEnabled(value) : null, ), + // Android delays alarms without the exact alarm permission + if (isAndroid && + gymState.showTimerPages && + gymState.restAlarmEnabled && + ref.watch(exactAlarmsAllowedProvider).value == false) + ListTile( + key: const ValueKey('gym-mode-exact-alarm-hint'), + leading: const Icon(Icons.alarm_off), + title: Text(i18n.gymModeExactAlarmMissing), + trailing: TextButton( + onPressed: () async { + await ref + .read(workoutNotificationServiceProvider) + .requestExactAlarms(); + ref.invalidate(exactAlarmsAllowedProvider); + }, + child: Text(i18n.gymModeExactAlarmAllow), + ), + ), // The ongoing notification only exists on Android - if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) + if (isAndroid) SwitchListTile( key: const ValueKey('gym-mode-workout-notification'), title: Text(i18n.gymModeWorkoutNotification), diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7c8418d6a..0c0d62230 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -379,6 +379,8 @@ "gymModeRestAlarm": "Rest alarm", "gymModeRestAlarmHelp": "System notification when the rest is over, also with the screen locked", "gymModeWorkoutNotification": "Workout notification", + "gymModeExactAlarmMissing": "Without the exact alarm permission, the rest alarm can be a few minutes late", + "gymModeExactAlarmAllow": "Allow", "gymModeWorkoutNotificationHelp": "Shows the rest and the next set, with buttons to log it or skip the rest", "workoutNotificationRestOver": "Rest is over", "workoutNotificationNext": "Next: {set}", diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index 7bf6d21b4..ba7369fa4 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -65,6 +65,23 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti ) as _i3.Future); + @override + _i3.Future canScheduleExactAlarms() => + (super.noSuchMethod( + Invocation.method(#canScheduleExactAlarms, []), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); + + @override + _i3.Future requestExactAlarms() => + (super.noSuchMethod( + Invocation.method(#requestExactAlarms, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future scheduleRestAlarm( _i4.RestAlarm? alarm, diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart new file mode 100644 index 000000000..5eb31deec --- /dev/null +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -0,0 +1,111 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/services.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:timezone/data/latest.dart' as tzdata; +import 'package:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; + +void main() { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('dexterous.com/flutter/local_notifications'); + late List calls; + late bool exactAllowed; + + const labels = WorkoutNotificationLabels( + logSet: 'Log set', + skipRest: 'Skip rest', + controlsChannel: 'Workout', + alarmChannel: 'Rest alarm', + notLoggedTitle: 'Set not logged', + notLoggedBody: 'Open gym mode', + ); + final payload = WorkoutNotificationPayload( + routineId: 1, + dayId: 1, + iteration: 1, + workoutStart: DateTime.utc(2025, 3, 29, 14, 33), + ); + + setUpAll(tzdata.initializeTimeZones); + + setUp(() { + // The Android side of the plugin, talking to a fake platform channel + FlutterLocalNotificationsPlatform.instance = AndroidFlutterLocalNotificationsPlugin(); + calls = []; + exactAllowed = true; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return switch (call.method) { + 'canScheduleExactNotifications' => exactAllowed, + 'initialize' => true, + _ => null, + }; + }); + addTearDown(() => binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null)); + }); + + Map scheduled() => + (calls.singleWhere((c) => c.method == 'zonedSchedule').arguments as Map)['platformSpecifics'] + as Map; + + RestAlarm alarm({bool canLogSet = true}) => RestAlarm( + at: DateTime.now().add(const Duration(minutes: 2)), + title: 'Rest is over', + body: 'Next: Bench press', + canLogSet: canLogSet, + payload: payload, + ); + + test('Initializes with the monochrome status bar icon', () async { + await LocalWorkoutNotificationService().initialize(labels); + + final init = calls.singleWhere((c) => c.method == 'initialize').arguments as Map; + expect(init['defaultIcon'], 'ic_stat_wger'); + }); + + test('The rest alarm is exact when allowed', () async { + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(), labels); + + expect(scheduled()['scheduleMode'], AndroidScheduleMode.exactAllowWhileIdle.name); + }); + + test('Without the exact alarm permission it falls back to an inexact alarm', () async { + exactAllowed = false; + + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(), labels); + + expect(scheduled()['scheduleMode'], AndroidScheduleMode.inexactAllowWhileIdle.name); + }); + + test('The alarm only offers "Log set" when the set can be logged', () async { + final service = LocalWorkoutNotificationService(); + + await service.scheduleRestAlarm(alarm(), labels); + expect( + (scheduled()['actions'] as List).map((a) => (a as Map)['id']), + [WORKOUT_NOTIFICATION_ACTION_LOG_SET], + ); + + calls.clear(); + await service.scheduleRestAlarm(alarm(canLogSet: false), labels); + expect(scheduled()['actions'], anyOf(isNull, isEmpty)); + }); +} diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index 8142901c2..ba8bbf2db 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -657,6 +657,23 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot ) as _i10.Future); + @override + _i10.Future canScheduleExactAlarms() => + (super.noSuchMethod( + Invocation.method(#canScheduleExactAlarms, []), + returnValue: _i10.Future.value(false), + ) + as _i10.Future); + + @override + _i10.Future requestExactAlarms() => + (super.noSuchMethod( + Invocation.method(#requestExactAlarms, []), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + @override _i10.Future scheduleRestAlarm( _i32.RestAlarm? alarm, diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index a290f0244..1e480bc6d 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -20,8 +20,11 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.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:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/start_page.dart'; @@ -29,19 +32,27 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/l10n/localizations_delegates.dart'; import '../../../../../test_data/routines.dart'; +import 'start_page_test.mocks.dart'; +@GenerateMocks([WorkoutNotificationService]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); late ProviderContainer container; + late MockWorkoutNotificationService notificationService; setUp(() { // Use in-memory shared preferences to avoid platform channels during tests SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + notificationService = MockWorkoutNotificationService(); + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => true); + when(notificationService.requestExactAlarms()).thenAnswer((_) async {}); + container = ProviderContainer( overrides: [ gymStateProvider.overrideWith(() => GymStateNotifier()), + workoutNotificationServiceProvider.overrideWithValue(notificationService), ], ); @@ -248,4 +259,39 @@ void main() { expect(notifier.state.showDistinctLogs, isFalse); }); + + group('Exact alarm hint', () { + Future openOptions(WidgetTester tester) async { + await pumpGymModeOptions(tester); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + } + + final hint = find.byKey(const ValueKey('gym-mode-exact-alarm-hint')); + + testWidgets('Shown without the permission, the button asks for it', (tester) async { + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); + await openOptions(tester); + expect(hint, findsOneWidget); + + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => true); + await tester.ensureVisible(find.descendant(of: hint, matching: find.byType(TextButton))); + await tester.tap(find.descendant(of: hint, matching: find.byType(TextButton))); + await tester.pumpAndSettle(); + + verify(notificationService.requestExactAlarms()).called(1); + expect(hint, findsNothing, reason: 'rechecked after returning from the setting'); + }); + + testWidgets('Not shown with the permission or with the rest alarm off', (tester) async { + await openOptions(tester); + expect(hint, findsNothing); + + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); + container.invalidate(exactAlarmsAllowedProvider); + container.read(gymStateProvider.notifier).setRestAlarmEnabled(false); + await tester.pumpAndSettle(); + expect(hint, findsNothing); + }); + }); } diff --git a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart new file mode 100644 index 000000000..3b91bfbcd --- /dev/null +++ b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart @@ -0,0 +1,124 @@ +// Mocks generated by Mockito from annotations +// in wger/test/features/routines/widgets/gym_mode/start_page_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes + +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/routines/notifications/workout_notification_content.dart' as _i4; +import 'package:wger/features/routines/notifications/workout_notification_service.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: experimental_member_use +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [WorkoutNotificationService]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNotificationService { + MockWorkoutNotificationService() { + _i1.throwOnMissingStub(this); + } + + @override + bool get supportsControls => + (super.noSuchMethod( + Invocation.getter(#supportsControls), + returnValue: false, + ) + as bool); + + @override + _i3.Future initialize( + _i4.WorkoutNotificationLabels? labels, { + _i2.WorkoutNotificationTapHandler? onTap, + }) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels], {#onTap: onTap}), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future requestPermissions(_i4.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#requestPermissions, [labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future canScheduleExactAlarms() => + (super.noSuchMethod( + Invocation.method(#canScheduleExactAlarms, []), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); + + @override + _i3.Future requestExactAlarms() => + (super.noSuchMethod( + Invocation.method(#requestExactAlarms, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future scheduleRestAlarm( + _i4.RestAlarm? alarm, + _i4.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#scheduleRestAlarm, [alarm, labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future showControls( + _i4.WorkoutControls? controls, + _i4.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#showControls, [controls, labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future showNotLogged(_i4.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#showNotLogged, [labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future cancelAll() => + (super.noSuchMethod( + Invocation.method(#cancelAll, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} From 3312a0a334e699072bbc1183fcb7adddc1c7814d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 11:48:04 +0100 Subject: [PATCH 10/28] End the iOS background task once a notification action is handled --- ios/Runner/AppDelegate.swift | 63 +++++++++++++++---- .../workout_notification_controller.dart | 10 +++ .../workout_notification_service.dart | 22 +++++++ .../workout_notification_controller_test.dart | 5 +- ...ut_notification_controller_test.mocks.dart | 9 +++ .../workout_notification_service_test.dart | 32 ++++++++++ .../routines/screens/gym_mode_test.mocks.dart | 9 +++ .../gym_mode/start_page_test.mocks.dart | 9 +++ 8 files changed, 145 insertions(+), 14 deletions(-) diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index b594b24e5..758e0a42a 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -50,6 +50,47 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin { } } +/// Keeps the app running while the main isolate handles a notification +/// action, until Dart reports it as handled +private final class NotificationActionTasks: NSObject, FlutterPlugin { + static let pluginName = "NotificationActionTasks" + private static let channelName = "de.wger.flutter/notification_actions" + /// Upper bound if Dart never reports back, e.g. without a running workout + private static let timeout: TimeInterval = 20 + private static var tasks: [UIBackgroundTaskIdentifier] = [] + + static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(NotificationActionTasks(), channel: channel) + } + + static func begin() { + var task: UIBackgroundTaskIdentifier = .invalid + task = UIApplication.shared.beginBackgroundTask { end(task) } + tasks.append(task) + DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { end(task) } + } + + private static func end(_ task: UIBackgroundTaskIdentifier) { + guard let index = tasks.firstIndex(of: task) else { + return + } + tasks.remove(at: index) + UIApplication.shared.endBackgroundTask(task) + } + + func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + guard call.method == "actionHandled" else { + result(FlutterMethodNotImplemented) + return + } + for task in Self.tasks { + Self.end(task) + } + result(nil) + } +} + @main @objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { override func application( @@ -62,24 +103,13 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin { } // A notification action is handled by the main isolate, but the plugin - // completes the response right away and iOS suspends the app again. - // Keep it running briefly so the action is processed now. + // completes the response right away and iOS suspends the app again override func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { - var task: UIBackgroundTaskIdentifier = .invalid - task = UIApplication.shared.beginBackgroundTask { - UIApplication.shared.endBackgroundTask(task) - task = .invalid - } - DispatchQueue.main.asyncAfter(deadline: .now() + 10) { - if task != .invalid { - UIApplication.shared.endBackgroundTask(task) - task = .invalid - } - } + NotificationActionTasks.begin() super.userNotificationCenter( center, didReceive: response, withCompletionHandler: completionHandler) } @@ -90,6 +120,13 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin { GeneratedPluginRegistrant.register(with: registry) } GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + if let registrar = engineBridge.pluginRegistry.registrar( + forPlugin: NotificationActionTasks.pluginName + ) { + NotificationActionTasks.register(with: registrar) + } else { + NSLog("NotificationActionTasks registrar unavailable") + } guard let registrar = engineBridge.pluginRegistry.registrar( forPlugin: StorageExclusionPlugin.pluginName diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index 3b8a6f6e4..f2b254e07 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -127,6 +127,16 @@ class WorkoutNotificationController { /// Carries out a notification action. Stale actions only refresh the /// notification, without a running session the user is sent to the app. Future handleAction(String? actionId, String? encodedPayload) async { + try { + await _handleAction(actionId, encodedPayload); + } finally { + // Lets iOS suspend the app again once the notification is up to date + await _queue; + await _service.actionHandled(); + } + } + + Future _handleAction(String? actionId, String? encodedPayload) async { final state = _ref.read(gymStateProvider); if (!state.isInitialized) { // E.g. iOS started the app in the background just for this action diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 074cc0949..90dd70259 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -19,6 +19,7 @@ import 'dart:ui'; import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -84,6 +85,9 @@ abstract class WorkoutNotificationService { /// Removes the shown notification and a pending rest alarm Future cancelAll(); + + /// Lets the platform suspend the app again after an action + Future actionHandled(); } /// For platforms without workout notifications @@ -117,6 +121,9 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { @override Future cancelAll() async {} + + @override + Future actionHandled() async {} } /// Android and iOS, via flutter_local_notifications @@ -125,6 +132,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { static const _controlsChannelId = 'workout_controls'; static const _alarmChannelId = 'rest_alarm'; static const _restEndCategory = 'workout_rest_end'; + static const _actionTasksChannel = MethodChannel('de.wger.flutter/notification_actions'); final _logger = Logger('LocalWorkoutNotificationService'); final _plugin = FlutterLocalNotificationsPlugin(); @@ -226,6 +234,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ], ), iOS: DarwinNotificationDetails( + presentSound: true, categoryIdentifier: alarm.canLogSet ? _restEndCategory : null, ), ), @@ -295,6 +304,19 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { await _initialized; await _plugin.cancel(id: _notificationId); } + + @override + Future actionHandled() async { + // Only iOS holds the app awake for an action, see AppDelegate.swift + if (defaultTargetPlatform != TargetPlatform.iOS) { + return; + } + try { + await _actionTasksChannel.invokeMethod('actionHandled'); + } on PlatformException catch (e) { + _logger.warning('Could not end the background task: $e'); + } + } } /// Whether rest alarms fire on time, rechecked whenever it is shown again diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index 92b572131..4924148a8 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -56,6 +56,7 @@ void main() { when(service.scheduleRestAlarm(any, any)).thenAnswer((_) async {}); when(service.showControls(any, any)).thenAnswer((_) async {}); when(service.showNotLogged(any)).thenAnswer((_) async {}); + when(service.actionHandled()).thenAnswer((_) async {}); when(service.initialize(any, onTap: anyNamed('onTap'))).thenAnswer((_) async {}); logRepo = MockWorkoutLogRepository(); when(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); @@ -232,6 +233,8 @@ void main() { verify(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1); expect(gymState.state.currentPage, rest + 2); + // Only once the notification shows the new rest may iOS suspend the app + verifyInOrder([service.showControls(any, any), service.actionHandled()]); final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; expect((alarms.last as RestAlarm).payload.restSlotUuid, slotPage(rest + 2).uuid); }); @@ -284,7 +287,7 @@ void main() { .handleAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, null); await settle(); - verify(service.showNotLogged(any)).called(1); + verifyInOrder([service.showNotLogged(any), service.actionHandled()]); verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); }); diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index ba7369fa4..6eeb9542a 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -123,6 +123,15 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } /// A class which mocks [WorkoutLogRepository]. diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart index 5eb31deec..6318b0929 100644 --- a/test/features/routines/notifications/workout_notification_service_test.dart +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -46,6 +47,37 @@ void main() { setUpAll(tzdata.initializeTimeZones); + group('actionHandled', () { + const tasksChannel = MethodChannel('de.wger.flutter/notification_actions'); + late List taskCalls; + + setUp(() { + taskCalls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(tasksChannel, (call) async { + taskCalls.add(call.method); + return null; + }); + addTearDown( + () => binding.defaultBinaryMessenger.setMockMethodCallHandler(tasksChannel, null), + ); + }); + + test('Ends the background task on iOS', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + + await LocalWorkoutNotificationService().actionHandled(); + + expect(taskCalls, ['actionHandled']); + }); + + test('Does nothing on Android, which keeps no task', () async { + await LocalWorkoutNotificationService().actionHandled(); + + expect(taskCalls, isEmpty); + }); + }); + setUp(() { // The Android side of the plugin, talking to a fake platform channel FlutterLocalNotificationsPlatform.instance = AndroidFlutterLocalNotificationsPlugin(); diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index ba8bbf2db..4fda3ae2c 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -715,4 +715,13 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); + + @override + _i10.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); } diff --git a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart index 3b91bfbcd..6bd72f272 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart @@ -121,4 +121,13 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); + + @override + _i3.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); } From 0ecc92cdace2bee6e1ae46f6dc21302ca830e6df Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 14:06:31 +0100 Subject: [PATCH 11/28] Update shared_preferences_android to fix release builds --- pubspec.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 017ce5b2a..61eaa8a0a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1353,10 +1353,10 @@ packages: dependency: transitive description: name: shared_preferences_android - sha256: a67a1a6a62b241ad4ddd8a97f5a12bb547c445190930233b63cd28cc0a104a76 + sha256: "593034a16e82953ca31145db6c85174286262715f9c5e6a9d8c65ffd9fcdce09" url: "https://pub.dev" source: hosted - version: "2.5.1" + version: "2.5.3" shared_preferences_foundation: dependency: transitive description: From e1ad69afb1e4c60cbfb4f4cfa2b2aa914cc3cad8 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 14:23:35 +0100 Subject: [PATCH 12/28] Default debug builds to the test server on a fresh install --- lib/core/network/auth_notifier.dart | 7 ++++--- .../auth/screens/auth_screen_test.dart | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/lib/core/network/auth_notifier.dart b/lib/core/network/auth_notifier.dart index 136d6bad3..fcce86727 100644 --- a/lib/core/network/auth_notifier.dart +++ b/lib/core/network/auth_notifier.dart @@ -20,7 +20,7 @@ import 'dart:async'; import 'dart:convert'; import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:flutter/foundation.dart' show visibleForTesting; +import 'package:flutter/foundation.dart' show kDebugMode, visibleForTesting; import 'package:flutter/widgets.dart' show AppLifecycleListener; import 'package:http/http.dart' as http; import 'package:logging/logging.dart'; @@ -874,11 +874,12 @@ class AuthNotifier extends _$AuthNotifier { state = AsyncData(current.copyWith(serverVersion: v)); } - /// Loads the last server URL the user successfully logged in with. + /// Loads the last server URL the user successfully logged in with, or the + /// default server of this build (the test server in debug builds). static Future getServerUrlFromPrefs() async { final prefs = PreferenceHelper.asyncPref; if (!(await prefs.containsKey(PREFS_LAST_SERVER))) { - return DEFAULT_SERVER_PROD; + return kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD; } final userData = json.decode((await prefs.getString(PREFS_LAST_SERVER))!); diff --git a/test/features/auth/screens/auth_screen_test.dart b/test/features/auth/screens/auth_screen_test.dart index 1d17aba8f..f1b170e1a 100644 --- a/test/features/auth/screens/auth_screen_test.dart +++ b/test/features/auth/screens/auth_screen_test.dart @@ -121,6 +121,11 @@ void main() { } setUp(() async { + // wger.de was used last; a fresh debug install defaults to the test server + await PreferenceHelper.asyncPref.setString( + PREFS_LAST_SERVER, + json.encode({'serverUrl': DEFAULT_SERVER_PROD}), + ); mockClient = MockClient(); mockSecureStorage = MockSecureTokenStorage(); when(mockSecureStorage.deleteRefreshToken()).thenAnswer((_) async {}); @@ -685,6 +690,22 @@ void main() { expect(find.text('http://localhost:8000'), findsOneWidget); }); + testWidgets('A fresh debug install points at the test server', ( + WidgetTester tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await PreferenceHelper.asyncPref.remove(PREFS_LAST_SERVER); + + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('inputServer')), findsOneWidget); + expect(find.text(DEFAULT_SERVER_TEST), findsOneWidget); + }); + testWidgets('Sheet round-trip: Refresh token → Username & password', ( WidgetTester tester, ) async { From d7439e7049e02537de698607478ed6923b7b40d0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 14:23:52 +0100 Subject: [PATCH 13/28] Show workout notifications only while gym mode runs in the background --- .../workout_notification_controller.dart | 22 +---- .../workout_notification_service.dart | 35 +++---- .../workout_notification_controller_test.dart | 96 +++++++------------ ...ut_notification_controller_test.mocks.dart | 7 +- .../routines/screens/gym_mode_test.mocks.dart | 7 +- .../widgets/gym_mode/start_page_test.dart | 20 ++++ .../gym_mode/start_page_test.mocks.dart | 7 +- 7 files changed, 74 insertions(+), 120 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index f2b254e07..e6f66bb64 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -25,11 +25,9 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/app_settings_notifier.dart'; -import 'package:wger/core/keys.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; -import 'package:wger/features/routines/screens/gym_mode.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; /// Whether the gym mode screen is mounted @@ -88,7 +86,9 @@ class WorkoutNotificationController { final locale = _locale; final i18n = lookupAppLocalizations(locale); - final target = inForeground && _ref.read(gymModeVisibleProvider) + // Only while gym mode is open in the background: on screen it shows the + // rest itself, and leaving it (X, back) ends the notifications + final target = inForeground || !_ref.read(gymModeVisibleProvider) ? WorkoutNotificationTarget.none : buildWorkoutNotification( state, @@ -167,20 +167,6 @@ class WorkoutNotificationController { // The platform removes the notification on an action refresh(); } - - /// Opens the running gym mode when the notification itself is tapped - void handleTap(String? encodedPayload) { - final payload = WorkoutNotificationPayload.decode(encodedPayload); - if (payload == null || - !payload.matches(_ref.read(gymStateProvider)) || - _ref.read(gymModeVisibleProvider)) { - return; - } - navigatorKey.currentState?.pushNamed( - GymModeScreen.routeName, - arguments: GymModeArguments(payload.routineId, payload.dayId, payload.iteration), - ); - } } const _backgroundStates = { @@ -193,7 +179,7 @@ const _backgroundStates = { final workoutNotificationControllerProvider = Provider((ref) { final service = ref.read(workoutNotificationServiceProvider); final controller = WorkoutNotificationController(ref, service); - unawaited(service.initialize(controller.labels, onTap: controller.handleTap)); + unawaited(service.initialize(controller.labels)); // Actions arrive from the background isolate final port = ReceivePort(); diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 90dd70259..74dfb57e1 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -34,9 +34,6 @@ const WORKOUT_NOTIFICATION_ACTION_SKIP_REST = 'skip_rest'; /// The main isolate receives notification actions on this port const WORKOUT_NOTIFICATION_PORT = 'wger_workout_actions'; -/// Called with the payload when the user taps the notification itself -typedef WorkoutNotificationTapHandler = void Function(String? payload); - /// Runs in a separate isolate without the gym state, so it only forwards the /// action. Without a running app nothing is logged, the user is sent there. @pragma('vm:entry-point') @@ -65,8 +62,8 @@ abstract class WorkoutNotificationService { /// Whether the platform has the ongoing controls notification bool get supportsControls; - /// Registers the actions and [onTap], before anything else is shown - Future initialize(WorkoutNotificationLabels labels, {WorkoutNotificationTapHandler? onTap}); + /// Registers the actions, before anything else is shown + Future initialize(WorkoutNotificationLabels labels); Future requestPermissions(WorkoutNotificationLabels labels); @@ -96,10 +93,7 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { bool get supportsControls => false; @override - Future initialize( - WorkoutNotificationLabels labels, { - WorkoutNotificationTapHandler? onTap, - }) async {} + Future initialize(WorkoutNotificationLabels labels) async {} @override Future requestPermissions(WorkoutNotificationLabels labels) async {} @@ -142,10 +136,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { bool get supportsControls => defaultTargetPlatform == TargetPlatform.android; @override - Future initialize( - WorkoutNotificationLabels labels, { - WorkoutNotificationTapHandler? onTap, - }) { + Future initialize(WorkoutNotificationLabels labels) { // The iOS action labels are registered once, with the first labels seen return _initialized ??= _plugin .initialize( @@ -168,13 +159,6 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ], ), ), - onDidReceiveNotificationResponse: (response) { - // Actions go to the background handler, this is a tap on the body - if (response.notificationResponseType == - NotificationResponseType.selectedNotification) { - onTap?.call(response.payload); - } - }, onDidReceiveBackgroundNotificationResponse: workoutNotificationBackgroundHandler, ) .then((_) {}); @@ -319,10 +303,13 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { } } -/// Whether rest alarms fire on time, rechecked whenever it is shown again -final exactAlarmsAllowedProvider = FutureProvider.autoDispose( - (ref) => ref.read(workoutNotificationServiceProvider).canScheduleExactAlarms(), -); +/// Whether rest alarms fire on time. Rechecked when the app comes back to the +/// front, the user may have granted it in the system settings meanwhile. +final exactAlarmsAllowedProvider = FutureProvider.autoDispose((ref) { + final lifecycle = AppLifecycleListener(onResume: ref.invalidateSelf); + ref.onDispose(lifecycle.dispose); + return ref.read(workoutNotificationServiceProvider).canScheduleExactAlarms(); +}); final workoutNotificationServiceProvider = Provider((ref) { if (!kIsWeb && diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index 4924148a8..c320c2ae2 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -21,19 +21,16 @@ import 'dart:ui'; import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:material_ui/material_ui.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.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:wger/core/keys.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/workout_logs_repository.dart'; -import 'package:wger/features/routines/screens/gym_mode.dart'; import '../../../../test_data/routines.dart'; import 'workout_notification_controller_test.mocks.dart'; @@ -57,7 +54,7 @@ void main() { when(service.showControls(any, any)).thenAnswer((_) async {}); when(service.showNotLogged(any)).thenAnswer((_) async {}); when(service.actionHandled()).thenAnswer((_) async {}); - when(service.initialize(any, onTap: anyNamed('onTap'))).thenAnswer((_) async {}); + when(service.initialize(any)).thenAnswer((_) async {}); logRepo = MockWorkoutLogRepository(); when(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); @@ -79,11 +76,23 @@ void main() { gymState.initData(routine, routine.days.first.id!, 1); } - /// Moves to the first rest of the fixture (120 s), initializing if needed + /// The listener only accepts single steps between lifecycle states + void stepLifecycle(List states) => + states.forEach(binding.handleAppLifecycleStateChanged); + + void toBackground() => stepLifecycle([AppLifecycleState.inactive, AppLifecycleState.hidden]); + + void toForeground() => stepLifecycle([AppLifecycleState.inactive, AppLifecycleState.resumed]); + + /// Gym mode open in the background, on the first rest of the fixture (120 s) Future startRest() async { if (!gymState.state.isInitialized) { initGymMode(); } + container.read(gymModeVisibleProvider.notifier).set(true); + if (binding.lifecycleState == AppLifecycleState.resumed) { + toBackground(); + } final timer = gymState.state.pages .expand((p) => p.slotPages) .firstWhere((p) => p.type == SlotPageType.timer); @@ -94,7 +103,7 @@ void main() { }); } - test('A rest away from gym mode schedules the alarm and shows the controls', () async { + test('A rest in the background schedules the alarm and shows the controls', () async { await startRest(); verifyInOrder([ @@ -123,21 +132,34 @@ void main() { await startRest(); clearInteractions(service); - container.read(gymModeVisibleProvider.notifier).set(true); + toForeground(); await settle(); verify(service.cancelAll()).called(1); verifyNever(service.scheduleRestAlarm(any, any)); verifyNever(service.showControls(any, any)); await withClock(Clock.fixed(now), () async { - binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); - binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + toBackground(); await settle(); }); verify(service.scheduleRestAlarm(any, any)).called(1); verify(service.showControls(any, any)).called(1); }); + test('Leaving gym mode removes everything, the session stays resumable', () async { + await startRest(); + clearInteractions(service); + + // X or back closes the screen, also with the app on its way to the background + container.read(gymModeVisibleProvider.notifier).set(false); + await settle(); + + verify(service.cancelAll()).called(1); + verifyNever(service.scheduleRestAlarm(any, any)); + verifyNever(service.showControls(any, any)); + expect(gymState.state.isInitialized, isTrue); + }); + test('Ending gym mode removes everything', () async { await startRest(); clearInteractions(service); @@ -179,8 +201,8 @@ void main() { }); group('Startup', () { - test('Initializes the service with the tap handler', () { - verify(service.initialize(any, onTap: argThat(isNotNull, named: 'onTap'))).called(1); + test('Initializes the service at startup', () { + verify(service.initialize(any)).called(1); }); test('Leftovers of an earlier run are removed when the app comes to the front', () async { @@ -291,56 +313,4 @@ void main() { verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); }); - - group('Tap on the notification', () { - Future pumpApp(WidgetTester tester) async { - await tester.pumpWidget( - UncontrolledProviderScope( - container: container, - child: MaterialApp( - navigatorKey: navigatorKey, - home: const Text('home'), - routes: {GymModeScreen.routeName: (_) => const Text('gym mode')}, - ), - ), - ); - } - - String currentPayload() => WorkoutNotificationPayload( - routineId: gymState.state.routine.id!, - dayId: gymState.state.dayId, - iteration: gymState.state.iteration, - workoutStart: gymState.state.workoutStart, - ).encode(); - - testWidgets('Opens the running gym mode', (tester) async { - initGymMode(); - await pumpApp(tester); - - container.read(workoutNotificationControllerProvider).handleTap(currentPayload()); - await tester.pumpAndSettle(); - - expect(find.text('gym mode'), findsOneWidget); - }); - - testWidgets('Stays put for another session or with gym mode on screen', (tester) async { - initGymMode(); - await pumpApp(tester); - final controller = container.read(workoutNotificationControllerProvider); - - controller.handleTap( - WorkoutNotificationPayload( - routineId: gymState.state.routine.id!, - dayId: gymState.state.dayId, - iteration: gymState.state.iteration, - workoutStart: DateTime.utc(2020), - ).encode(), - ); - container.read(gymModeVisibleProvider.notifier).set(true); - controller.handleTap(currentPayload()); - await tester.pumpAndSettle(); - - expect(find.text('gym mode'), findsNothing); - }); - }); } diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index 6eeb9542a..9deba8fe8 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -45,12 +45,9 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti as bool); @override - _i3.Future initialize( - _i4.WorkoutNotificationLabels? labels, { - _i2.WorkoutNotificationTapHandler? onTap, - }) => + _i3.Future initialize(_i4.WorkoutNotificationLabels? labels) => (super.noSuchMethod( - Invocation.method(#initialize, [labels], {#onTap: onTap}), + Invocation.method(#initialize, [labels]), returnValue: _i3.Future.value(), returnValueForMissingStub: _i3.Future.value(), ) diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index 4fda3ae2c..8e4d85fb1 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -635,12 +635,9 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot as bool); @override - _i10.Future initialize( - _i32.WorkoutNotificationLabels? labels, { - _i31.WorkoutNotificationTapHandler? onTap, - }) => + _i10.Future initialize(_i32.WorkoutNotificationLabels? labels) => (super.noSuchMethod( - Invocation.method(#initialize, [labels], {#onTap: onTap}), + Invocation.method(#initialize, [labels]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index 1e480bc6d..17c0fe930 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -283,6 +283,26 @@ void main() { expect(hint, findsNothing, reason: 'rechecked after returning from the setting'); }); + testWidgets('Rechecked when the app comes back from the system settings', (tester) async { + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); + await openOptions(tester); + expect(hint, findsOneWidget); + + // Granted outside the app, e.g. in the system settings + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => true); + [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ].forEach(tester.binding.handleAppLifecycleStateChanged); + await tester.pumpAndSettle(); + + expect(hint, findsNothing); + }); + testWidgets('Not shown with the permission or with the rest alarm off', (tester) async { await openOptions(tester); expect(hint, findsNothing); diff --git a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart index 6bd72f272..8d27c80b0 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart @@ -43,12 +43,9 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti as bool); @override - _i3.Future initialize( - _i4.WorkoutNotificationLabels? labels, { - _i2.WorkoutNotificationTapHandler? onTap, - }) => + _i3.Future initialize(_i4.WorkoutNotificationLabels? labels) => (super.noSuchMethod( - Invocation.method(#initialize, [labels], {#onTap: onTap}), + Invocation.method(#initialize, [labels]), returnValue: _i3.Future.value(), returnValueForMissingStub: _i3.Future.value(), ) From 608f5de4c6a0aaac3d9d3aa789fc2759f62dce44 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 16:00:19 +0100 Subject: [PATCH 14/28] Retry the workout notification after a failed platform call --- .../workout_notification_controller.dart | 18 ++++++++++++------ .../workout_notification_controller_test.dart | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index e6f66bb64..614666087 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -115,12 +115,18 @@ class WorkoutNotificationController { _shown = target; // Alarm and controls share one notification, so every change starts over - await _service.cancelAll(); - if (target.alarm != null) { - await _service.scheduleRestAlarm(target.alarm!, labels); - } - if (target.controls != null) { - await _service.showControls(target.controls!, labels); + try { + await _service.cancelAll(); + if (target.alarm != null) { + await _service.scheduleRestAlarm(target.alarm!, labels); + } + if (target.controls != null) { + await _service.showControls(target.controls!, labels); + } + } catch (_) { + // Unknown what the platform shows now, the next update tries again + _shown = null; + rethrow; } } diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index c320c2ae2..7665e3718 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -128,6 +128,22 @@ void main() { verifyNever(service.showControls(any, any)); }); + test('A failed platform call is retried on the next update', () async { + // E.g. the rest ended between building and scheduling the alarm + when(service.scheduleRestAlarm(any, any)).thenThrow(ArgumentError('in the past')); + await startRest(); + + when(service.scheduleRestAlarm(any, any)).thenAnswer((_) async {}); + clearInteractions(service); + await withClock(Clock.fixed(now), () async { + gymState.setShowDistinctLogs(false); + await settle(); + }); + + verify(service.scheduleRestAlarm(any, any)).called(1); + verify(service.showControls(any, any)).called(1); + }); + test('Nothing while gym mode is on screen, back when the app goes to the background', () async { await startRest(); clearInteractions(service); From f0075b096a6e8e76fbe37e1c6aac980db260f59f Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 16:06:07 +0100 Subject: [PATCH 15/28] Bump package versions --- pubspec.lock | 20 ++++++++++---------- pubspec.yaml | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 61eaa8a0a..3291be28b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -277,10 +277,10 @@ packages: dependency: "direct main" description: name: connectivity_plus - sha256: "762c99f890ca8bf87f7337236f99edd42793843bc6c3631da294a76653a54bd0" + sha256: d7749fd36d8b404a4935612b94eca7c3ce3705377ab678e24ff2a4301436f741 url: "https://pub.dev" source: hosted - version: "7.3.1" + version: "7.3.2" connectivity_plus_platform_interface: dependency: "direct dev" description: @@ -349,10 +349,10 @@ packages: dependency: transitive description: name: dbus - sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383 + sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 url: "https://pub.dev" source: hosted - version: "0.7.15" + version: "0.8.0" device_info_plus: dependency: transitive description: @@ -551,18 +551,18 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "357be7ff996dc272e2037c69c1bdd5d1bd21172219d55f8bd2e11aeea602e6d3" + sha256: fd5fc8966a8b34337ac182dc394f3506139b69d8138d4e9e174a13d6468adcd4 url: "https://pub.dev" source: hosted - version: "22.3.1" + version: "22.3.3" flutter_local_notifications_linux: dependency: transitive description: name: flutter_local_notifications_linux - sha256: "9ca97e63776f29ab1b955725c09999fc2c150523269db150c39274f2a43c5a8b" + sha256: "3b89a4bf095fa5f8a99beeabf982c5bd506c3ad25e7b9e61da945e994dc5b615" url: "https://pub.dev" source: hosted - version: "8.0.1" + version: "8.0.2" flutter_local_notifications_platform_interface: dependency: transitive description: @@ -1105,10 +1105,10 @@ packages: dependency: transitive description: name: nm - sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" + sha256: "2ae480aa3379716b8bb58dfebb168e2919394c92b629efaaa0baaa5d140786e6" url: "https://pub.dev" source: hosted - version: "0.5.0" + version: "0.6.0" objective_c: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 40b62cde6..760f87e7d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -78,12 +78,12 @@ dependencies: drift_sqlite_async: ^0.3.1 stream_transform: ^2.1.2 state_notifier: ^1.0.0 - connectivity_plus: ^7.3.1 + connectivity_plus: ^7.3.2 powersync: ^2.4.0 flutter_timezone: ^5.1.0 timezone: ^0.11.1 material_ui: ^1.6.0 - flutter_local_notifications: ^22.3.1 + flutter_local_notifications: ^22.3.3 dev_dependencies: flutter_test: From fc237bca154a097b506cc34eece3ff07234c4e41 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 16:19:42 +0100 Subject: [PATCH 16/28] Keep the gym mode options within the start page --- .../routines/widgets/gym_mode/start_page.dart | 447 +++++++++--------- .../routines/widgets/gym_mode/timer.dart | 4 +- .../widgets/gym_mode/start_page_test.dart | 22 + 3 files changed, 258 insertions(+), 215 deletions(-) diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 046ef90b0..160634a63 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -29,7 +29,10 @@ import 'package:wger/features/routines/widgets/gym_mode/navigation.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; class GymModeOptions extends ConsumerStatefulWidget { - const GymModeOptions({super.key}); + /// Height the options take at most, the opened card shrinks and scrolls + final double maxHeight; + + const GymModeOptions({super.key, this.maxHeight = double.infinity}); @override ConsumerState createState() => _GymModeOptionsState(); @@ -65,194 +68,201 @@ class _GymModeOptionsState extends ConsumerState { _countdownController.text = currentText; } - return Column( - children: [ - AnimatedCrossFade( - firstChild: const SizedBox.shrink(), - secondChild: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), - child: ConstrainedBox( - constraints: const BoxConstraints(maxHeight: 400), - child: Card( - child: SingleChildScrollView( - child: Column( - children: [ - SwitchListTile( - key: const ValueKey('gym-mode-option-show-exercises'), - title: Text(i18n.gymModeShowExercises), - value: gymState.showExercisePages, - onChanged: (value) => gymNotifier.setShowExercisePages(value), - ), - SwitchListTile( - key: const ValueKey('gym-mode-option-show-workout-duration'), - title: Text(i18n.gymModeShowWorkoutDuration), - value: gymState.showWorkoutDuration, - onChanged: (value) => gymNotifier.setShowWorkoutDuration(value), - ), + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: widget.maxHeight), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: AnimatedCrossFade( + firstChild: const SizedBox.shrink(), + secondChild: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 400), + child: Card( + child: SingleChildScrollView( + child: Column( + children: [ + SwitchListTile( + key: const ValueKey('gym-mode-option-show-exercises'), + title: Text(i18n.gymModeShowExercises), + value: gymState.showExercisePages, + onChanged: (value) => gymNotifier.setShowExercisePages(value), + ), + SwitchListTile( + key: const ValueKey('gym-mode-option-show-workout-duration'), + title: Text(i18n.gymModeShowWorkoutDuration), + value: gymState.showWorkoutDuration, + onChanged: (value) => gymNotifier.setShowWorkoutDuration(value), + ), - const Divider(), - SwitchListTile( - key: const ValueKey('gym-mode-option-show-timer'), - title: Text(i18n.gymModeShowTimer), - value: gymState.showTimerPages, - onChanged: (value) => gymNotifier.setShowTimerPages(value), - ), - ListTile( - key: const ValueKey('gym-mode-timer-type'), - enabled: gymState.showTimerPages, - title: Text(i18n.gymModeTimerType), - trailing: DropdownButton( - key: const ValueKey('countdown-type-dropdown'), - value: gymState.useCountdownBetweenSets, - onChanged: gymState.showTimerPages - ? (bool? newValue) { - if (newValue != null) { - gymNotifier.setUseCountdownBetweenSets(newValue); - } - } - : null, - items: [false, true].map>((bool value) { - final label = value ? i18n.countdown : i18n.stopwatch; - - return DropdownMenuItem(value: value, child: Text(label)); - }).toList(), - ), - subtitle: Text(i18n.gymModeTimerTypeHelText), - ), - ListTile( - key: const ValueKey('gym-mode-default-countdown-time'), - enabled: gymState.showTimerPages, - title: TextFormField( - controller: _countdownController, - keyboardType: TextInputType.number, - decoration: InputDecoration( - labelText: i18n.gymModeDefaultCountdownTime, - suffix: IconButton( - onPressed: gymState.showTimerPages && gymState.useCountdownBetweenSets - ? () => gymNotifier.setCountdownDuration( - DEFAULT_COUNTDOWN_DURATION, - ) + const Divider(), + SwitchListTile( + key: const ValueKey('gym-mode-option-show-timer'), + title: Text(i18n.gymModeShowTimer), + value: gymState.showTimerPages, + onChanged: (value) => gymNotifier.setShowTimerPages(value), + ), + ListTile( + key: const ValueKey('gym-mode-timer-type'), + enabled: gymState.showTimerPages, + title: Text(i18n.gymModeTimerType), + trailing: DropdownButton( + key: const ValueKey('countdown-type-dropdown'), + value: gymState.useCountdownBetweenSets, + onChanged: gymState.showTimerPages + ? (bool? newValue) { + if (newValue != null) { + gymNotifier.setUseCountdownBetweenSets(newValue); + } + } : null, - icon: const Icon(Icons.refresh), + items: [false, true].map>((bool value) { + final label = value ? i18n.countdown : i18n.stopwatch; + + return DropdownMenuItem(value: value, child: Text(label)); + }).toList(), + ), + subtitle: Text(i18n.gymModeTimerTypeHelText), + ), + ListTile( + key: const ValueKey('gym-mode-default-countdown-time'), + enabled: gymState.showTimerPages, + title: TextFormField( + controller: _countdownController, + keyboardType: TextInputType.number, + decoration: InputDecoration( + labelText: i18n.gymModeDefaultCountdownTime, + suffix: IconButton( + onPressed: + gymState.showTimerPages && gymState.useCountdownBetweenSets + ? () => gymNotifier.setCountdownDuration( + DEFAULT_COUNTDOWN_DURATION, + ) + : null, + icon: const Icon(Icons.refresh), + ), + ), + onChanged: (value) { + final intValue = int.tryParse(value); + if (intValue != null && + intValue > 0 && + intValue < MAX_COUNTDOWN_DURATION) { + gymNotifier.setCountdownDuration(intValue); + } + }, + autovalidateMode: AutovalidateMode.onUserInteraction, + validator: (String? value) { + final intValue = int.tryParse(value!); + if (intValue == null || + intValue < MIN_COUNTDOWN_DURATION || + intValue > MAX_COUNTDOWN_DURATION) { + return i18n.formMinMaxValues( + MIN_COUNTDOWN_DURATION, + MAX_COUNTDOWN_DURATION, + ); + } + return null; + }, + enabled: gymState.showTimerPages && gymState.useCountdownBetweenSets, ), ), - onChanged: (value) { - final intValue = int.tryParse(value); - if (intValue != null && - intValue > 0 && - intValue < MAX_COUNTDOWN_DURATION) { - gymNotifier.setCountdownDuration(intValue); - } - }, - autovalidateMode: AutovalidateMode.onUserInteraction, - validator: (String? value) { - final intValue = int.tryParse(value!); - if (intValue == null || - intValue < MIN_COUNTDOWN_DURATION || - intValue > MAX_COUNTDOWN_DURATION) { - return i18n.formMinMaxValues( - MIN_COUNTDOWN_DURATION, - MAX_COUNTDOWN_DURATION, - ); - } - return null; - }, - enabled: gymState.showTimerPages && gymState.useCountdownBetweenSets, - ), - ), - SwitchListTile( - key: const ValueKey('gym-mode-notify-countdown'), - title: Text(i18n.gymModeNotifyOnCountdownFinish), - value: gymState.alertOnCountdownEnd, - onChanged: (gymState.showTimerPages && gymState.useCountdownBetweenSets) - ? (value) => gymNotifier.setAlertOnCountdownEnd(value) - : null, - ), - SwitchListTile( - key: const ValueKey('gym-mode-rest-alarm'), - title: Text(i18n.gymModeRestAlarm), - subtitle: Text(i18n.gymModeRestAlarmHelp), - value: gymState.restAlarmEnabled, - onChanged: gymState.showTimerPages - ? (value) => gymNotifier.setRestAlarmEnabled(value) - : null, - ), - // Android delays alarms without the exact alarm permission - if (isAndroid && - gymState.showTimerPages && - gymState.restAlarmEnabled && - ref.watch(exactAlarmsAllowedProvider).value == false) - ListTile( - key: const ValueKey('gym-mode-exact-alarm-hint'), - leading: const Icon(Icons.alarm_off), - title: Text(i18n.gymModeExactAlarmMissing), - trailing: TextButton( - onPressed: () async { - await ref - .read(workoutNotificationServiceProvider) - .requestExactAlarms(); - ref.invalidate(exactAlarmsAllowedProvider); - }, - child: Text(i18n.gymModeExactAlarmAllow), + SwitchListTile( + key: const ValueKey('gym-mode-notify-countdown'), + title: Text(i18n.gymModeNotifyOnCountdownFinish), + value: gymState.alertOnCountdownEnd, + onChanged: (gymState.showTimerPages && gymState.useCountdownBetweenSets) + ? (value) => gymNotifier.setAlertOnCountdownEnd(value) + : null, ), - ), - // The ongoing notification only exists on Android - if (isAndroid) - SwitchListTile( - key: const ValueKey('gym-mode-workout-notification'), - title: Text(i18n.gymModeWorkoutNotification), - subtitle: Text(i18n.gymModeWorkoutNotificationHelp), - value: gymState.showWorkoutNotification, - onChanged: (value) => gymNotifier.setShowWorkoutNotification(value), - ), - - const Divider(), - ListTile( - key: const ValueKey('gym-mode-log-scope'), - title: Text(i18n.gymModeLogScope), - subtitle: Text(i18n.gymModeLogScopeHelp), - trailing: DropdownButton( - key: const ValueKey('log-scope-dropdown'), - value: gymState.logScopeWeeks, - onChanged: (value) => gymNotifier.setLogScopeWeeks(value), - items: [ - DropdownMenuItem( - value: null, - child: Text(i18n.gymModeLogScopeCurrentRoutine), - ), - ...[8, 12, 25, 50].map( - (weeks) => DropdownMenuItem( - value: weeks, - child: Text(i18n.gymModeLogScopeWeeks(weeks)), + SwitchListTile( + key: const ValueKey('gym-mode-rest-alarm'), + title: Text(i18n.gymModeRestAlarm), + subtitle: Text(i18n.gymModeRestAlarmHelp), + value: gymState.restAlarmEnabled, + onChanged: gymState.showTimerPages + ? (value) => gymNotifier.setRestAlarmEnabled(value) + : null, + ), + // Android delays alarms without the exact alarm permission + if (isAndroid && + gymState.showTimerPages && + gymState.restAlarmEnabled && + ref.watch(exactAlarmsAllowedProvider).value == false) + ListTile( + key: const ValueKey('gym-mode-exact-alarm-hint'), + leading: const Icon(Icons.alarm_off), + title: Text(i18n.gymModeExactAlarmMissing), + trailing: TextButton( + onPressed: () async { + await ref + .read(workoutNotificationServiceProvider) + .requestExactAlarms(); + ref.invalidate(exactAlarmsAllowedProvider); + }, + child: Text(i18n.gymModeExactAlarmAllow), ), ), - ], - ), + // The ongoing notification only exists on Android + if (isAndroid) + SwitchListTile( + key: const ValueKey('gym-mode-workout-notification'), + title: Text(i18n.gymModeWorkoutNotification), + subtitle: Text(i18n.gymModeWorkoutNotificationHelp), + value: gymState.showWorkoutNotification, + onChanged: (value) => gymNotifier.setShowWorkoutNotification(value), + ), + + const Divider(), + ListTile( + key: const ValueKey('gym-mode-log-scope'), + title: Text(i18n.gymModeLogScope), + subtitle: Text(i18n.gymModeLogScopeHelp), + trailing: DropdownButton( + key: const ValueKey('log-scope-dropdown'), + value: gymState.logScopeWeeks, + onChanged: (value) => gymNotifier.setLogScopeWeeks(value), + items: [ + DropdownMenuItem( + value: null, + child: Text(i18n.gymModeLogScopeCurrentRoutine), + ), + ...[8, 12, 25, 50].map( + (weeks) => DropdownMenuItem( + value: weeks, + child: Text(i18n.gymModeLogScopeWeeks(weeks)), + ), + ), + ], + ), + ), + SwitchListTile( + key: const ValueKey('gym-mode-distinct-logs'), + title: Text(i18n.gymModeDistinctLogs), + value: gymState.showDistinctLogs, + onChanged: (value) => gymNotifier.setShowDistinctLogs(value), + ), + ], ), - SwitchListTile( - key: const ValueKey('gym-mode-distinct-logs'), - title: Text(i18n.gymModeDistinctLogs), - value: gymState.showDistinctLogs, - onChanged: (value) => gymNotifier.setShowDistinctLogs(value), - ), - ], + ), ), ), ), + crossFadeState: _showOptions ? CrossFadeState.showSecond : CrossFadeState.showFirst, + duration: const Duration(milliseconds: 200), ), ), - crossFadeState: _showOptions ? CrossFadeState.showSecond : CrossFadeState.showFirst, - duration: const Duration(milliseconds: 200), - ), - ListTile( - key: const ValueKey('gym-mode-options-tile'), - title: Text(i18n.settingsTitle), - leading: const Icon(Icons.settings), - onTap: () => setState(() => _showOptions = !_showOptions), - ), - ], + ListTile( + key: const ValueKey('gym-mode-options-tile'), + title: Text(i18n.settingsTitle), + leading: const Icon(Icons.settings), + onTap: () => setState(() => _showOptions = !_showOptions), + ), + ], + ), ); } } @@ -274,50 +284,61 @@ class StartPage extends ConsumerWidget { showEndWorkoutButton: false, ), + // The opened options may take all of the room, e.g. with the keyboard up Expanded( - child: ListView( - children: [ - if (dayDataDisplay.day!.isSpecialType) - Center( - child: Padding( - padding: const EdgeInsets.all(15), - child: Text( - '${dayDataDisplay.day!.type.name.toUpperCase()}\n${dayDataDisplay.day!.type.i18Label(AppLocalizations.of(context))}', - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.headlineSmall, - ), + child: LayoutBuilder( + builder: (context, constraints) => Column( + children: [ + Expanded( + child: ListView( + children: [ + if (dayDataDisplay.day!.isSpecialType) + Center( + child: Padding( + padding: const EdgeInsets.all(15), + child: Text( + '${dayDataDisplay.day!.type.name.toUpperCase()}\n${dayDataDisplay.day!.type.i18Label(AppLocalizations.of(context))}', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineSmall, + ), + ), + ), + ...dayDataDisplay.slots + .expand((slot) => slot.setConfigs) + .fold>>({}, (acc, entry) { + acc.putIfAbsent(entry.exercise, () => []).add(entry.textReprWithType); + return acc; + }) + .entries + .map((entry) { + final exercise = entry.key; + return Column( + children: [ + ListTile( + leading: SizedBox( + width: 45, + child: ExerciseImageWidget(image: exercise.getMainImage), + ), + title: Text( + exercise + .getTranslation( + Localizations.localeOf(context).languageCode, + ) + .name, + ), + subtitle: Text(entry.value.toList().join('\n')), + ), + ], + ); + }), + ], ), ), - ...dayDataDisplay.slots - .expand((slot) => slot.setConfigs) - .fold>>({}, (acc, entry) { - acc.putIfAbsent(entry.exercise, () => []).add(entry.textReprWithType); - return acc; - }) - .entries - .map((entry) { - final exercise = entry.key; - return Column( - children: [ - ListTile( - leading: SizedBox( - width: 45, - child: ExerciseImageWidget(image: exercise.getMainImage), - ), - title: Text( - exercise - .getTranslation(Localizations.localeOf(context).languageCode) - .name, - ), - subtitle: Text(entry.value.toList().join('\n')), - ), - ], - ); - }), - ], + GymModeOptions(maxHeight: constraints.maxHeight), + ], + ), ), ), - const GymModeOptions(), FilledButton( child: Text(AppLocalizations.of(context).start), onPressed: () { diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index c76ef3ed4..0aefed621 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index 17c0fe930..baa94d185 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -314,4 +314,26 @@ void main() { expect(hint, findsNothing); }); }); + testWidgets('The opened options fit a short screen, e.g. with the keyboard up', (tester) async { + tester.view.physicalSize = const Size(400, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: appLocalizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: StartPage(PageController())), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + }); } From fb3d6092d7ecfb5894d3e41d68373dfa8d578eef Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 16:33:46 +0100 Subject: [PATCH 17/28] Merge the rest alarm into the rest end alert setting --- .../workout_notification_content.dart | 4 +- .../routines/providers/gym_state.dart | 10 +- .../providers/gym_state_notifier.dart | 13 -- .../routines/widgets/gym_mode/gym_mode.dart | 3 +- .../routines/widgets/gym_mode/start_page.dart | 18 +- lib/l10n/app_ar.arb | 1 - lib/l10n/app_ca.arb | 1 - lib/l10n/app_cs.arb | 1 - lib/l10n/app_de.arb | 1 - lib/l10n/app_en.arb | 11 +- lib/l10n/app_es.arb | 1 - lib/l10n/app_fr.arb | 1 - lib/l10n/app_hr.arb | 1 - lib/l10n/app_hu.arb | 1 - lib/l10n/app_id.arb | 1 - lib/l10n/app_it.arb | 1 - lib/l10n/app_mk.arb | 1 - lib/l10n/app_nl.arb | 1 - lib/l10n/app_pl.arb | 1 - lib/l10n/app_pt.arb | 1 - lib/l10n/app_pt_BR.arb | 1 - lib/l10n/app_ro.arb | 1 - lib/l10n/app_ru.arb | 1 - lib/l10n/app_sl.arb | 1 - lib/l10n/app_uk.arb | 1 - lib/l10n/app_zh_Hant.arb | 1 - test/core/validators_test.mocks.dart | 182 +++++++++++++++++- .../workout_notification_content_test.dart | 2 +- .../workout_notification_controller_test.dart | 4 +- .../routines/providers/gym_state_test.dart | 14 +- .../routines/screens/gym_mode_test.dart | 4 +- .../widgets/gym_mode/start_page_test.dart | 35 ++-- 32 files changed, 233 insertions(+), 87 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index 15b403037..af2b121ca 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -164,7 +164,7 @@ class WorkoutNotificationLabels extends Equatable { : logSet = i18n.workoutNotificationLogSet, skipRest = i18n.workoutNotificationSkipRest, controlsChannel = i18n.workoutNotificationChannel, - alarmChannel = i18n.gymModeRestAlarm, + alarmChannel = i18n.workoutNotificationAlarmChannel, notLoggedTitle = i18n.workoutNotificationNotLoggedTitle, notLoggedBody = i18n.workoutNotificationNotLoggedBody; @@ -247,7 +247,7 @@ WorkoutNotificationTarget buildWorkoutNotification( final endsAt = state.restEndsAt; final restRunning = endsAt != null && endsAt.isAfter(now); - final alarm = state.restAlarmEnabled && restRunning + final alarm = state.alertOnCountdownEnd && restRunning ? RestAlarm( at: endsAt, title: i18n.workoutNotificationRestOver, diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index c2e22d32a..5b3dac3ce 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -34,7 +34,6 @@ const PREFS_COUNTDOWN_DURATION = 'countdownDurationSecondsPrefs'; const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs'; const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs'; const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs'; -const PREFS_REST_ALARM = 'restAlarmPrefs'; const PREFS_WORKOUT_NOTIFICATION = 'workoutNotificationPrefs'; /// In seconds @@ -187,6 +186,9 @@ class GymModeState { // User settings final bool showExercisePages; final bool showTimerPages; + + /// Alert at the end of a rest: a vibration in gym mode, an OS notification + /// with the app in the background final bool alertOnCountdownEnd; final bool useCountdownBetweenSets; final Duration countdownDuration; @@ -194,9 +196,6 @@ class GymModeState { final bool showDistinctLogs; final bool showWorkoutDuration; - /// OS notification when the rest is over, also with the app in the background - final bool restAlarmEnabled; - /// Ongoing notification with the rest and the next set (Android) final bool showWorkoutNotification; @@ -220,7 +219,6 @@ class GymModeState { this.logScopeWeeks, this.showDistinctLogs = true, this.showWorkoutDuration = true, - this.restAlarmEnabled = true, this.showWorkoutNotification = true, int? dayId, int? iteration, @@ -271,7 +269,6 @@ class GymModeState { bool clearLogScopeWeeks = false, bool? showDistinctLogs, bool? showWorkoutDuration, - bool? restAlarmEnabled, bool? showWorkoutNotification, }) { return GymModeState( @@ -297,7 +294,6 @@ class GymModeState { logScopeWeeks: clearLogScopeWeeks ? null : (logScopeWeeks ?? this.logScopeWeeks), showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, - restAlarmEnabled: restAlarmEnabled ?? this.restAlarmEnabled, showWorkoutNotification: showWorkoutNotification ?? this.showWorkoutNotification, ); } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index cef4f2245..8ba45c589 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -93,11 +93,6 @@ class GymStateNotifier extends _$GymStateNotifier { state = state.copyWith(showWorkoutDuration: showWorkoutDuration); } - final restAlarm = await prefs.getBool(PREFS_REST_ALARM); - if (restAlarm != null && restAlarm != state.restAlarmEnabled) { - state = state.copyWith(restAlarmEnabled: restAlarm); - } - final workoutNotification = await prefs.getBool(PREFS_WORKOUT_NOTIFICATION); if (workoutNotification != null && workoutNotification != state.showWorkoutNotification) { state = state.copyWith(showWorkoutNotification: workoutNotification); @@ -113,7 +108,6 @@ class GymStateNotifier extends _$GymStateNotifier { 'logScopeWeeks=$logScopeWeeks ' 'showDistinctLogs=$showDistinctLogs ' 'showWorkoutDuration=$showWorkoutDuration ' - 'restAlarm=$restAlarm ' 'workoutNotification=$workoutNotification ', ); } @@ -135,7 +129,6 @@ class GymStateNotifier extends _$GymStateNotifier { } await prefs.setBool(PREFS_SHOW_DISTINCT_LOGS, state.showDistinctLogs); await prefs.setBool(PREFS_SHOW_WORKOUT_DURATION, state.showWorkoutDuration); - await prefs.setBool(PREFS_REST_ALARM, state.restAlarmEnabled); await prefs.setBool(PREFS_WORKOUT_NOTIFICATION, state.showWorkoutNotification); _logger.finer( @@ -148,7 +141,6 @@ class GymStateNotifier extends _$GymStateNotifier { 'logScopeWeeks=${state.logScopeWeeks} ' 'showDistinctLogs=${state.showDistinctLogs} ' 'showWorkoutDuration=${state.showWorkoutDuration} ' - 'restAlarm=${state.restAlarmEnabled} ' 'workoutNotification=${state.showWorkoutNotification} ', ); } @@ -471,11 +463,6 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } - void setRestAlarmEnabled(bool value) { - state = state.copyWith(restAlarmEnabled: value); - _savePrefs(); - } - void setShowWorkoutNotification(bool value) { state = state.copyWith(showWorkoutNotification: value); _savePrefs(); diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 00a15dda1..3a9b60880 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -127,7 +127,8 @@ class _GymModeState extends ConsumerState { final gymState = ref.read(gymStateProvider); final service = ref.read(workoutNotificationServiceProvider); final wanted = - gymState.restAlarmEnabled || (service.supportsControls && gymState.showWorkoutNotification); + gymState.alertOnCountdownEnd || + (service.supportsControls && gymState.showWorkoutNotification); if (wanted && mounted) { unawaited( service.requestPermissions(WorkoutNotificationLabels.of(AppLocalizations.of(context))), diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 160634a63..988aa5e0d 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -169,27 +169,21 @@ class _GymModeOptionsState extends ConsumerState { ), ), + // Enabled without the default countdown too, a set's rest time + // is always counted down SwitchListTile( key: const ValueKey('gym-mode-notify-countdown'), - title: Text(i18n.gymModeNotifyOnCountdownFinish), + title: Text(i18n.gymModeAlertOnRestEnd), + subtitle: Text(i18n.gymModeAlertOnRestEndHelp), value: gymState.alertOnCountdownEnd, - onChanged: (gymState.showTimerPages && gymState.useCountdownBetweenSets) - ? (value) => gymNotifier.setAlertOnCountdownEnd(value) - : null, - ), - SwitchListTile( - key: const ValueKey('gym-mode-rest-alarm'), - title: Text(i18n.gymModeRestAlarm), - subtitle: Text(i18n.gymModeRestAlarmHelp), - value: gymState.restAlarmEnabled, onChanged: gymState.showTimerPages - ? (value) => gymNotifier.setRestAlarmEnabled(value) + ? (value) => gymNotifier.setAlertOnCountdownEnd(value) : null, ), // Android delays alarms without the exact alarm permission if (isAndroid && gymState.showTimerPages && - gymState.restAlarmEnabled && + gymState.alertOnCountdownEnd && ref.watch(exactAlarmsAllowedProvider).value == false) ListTile( key: const ValueKey('gym-mode-exact-alarm-hint'), diff --git a/lib/l10n/app_ar.arb b/lib/l10n/app_ar.arb index f22efe890..dd288fe0e 100644 --- a/lib/l10n/app_ar.arb +++ b/lib/l10n/app_ar.arb @@ -823,7 +823,6 @@ "countdown": "عد تنازلي", "stopwatch": "ساعة توقيت", "gymModeDefaultCountdownTime": "وقت العد التنازلي الافتراضي، بالثواني", - "gymModeNotifyOnCountdownFinish": "إشعار عند انتهاء العد التنازلي", "duration": "المدة", "durationHoursMinutes": "{hours}سا {minutes}د", "@durationHoursMinutes": { diff --git a/lib/l10n/app_ca.arb b/lib/l10n/app_ca.arb index a04c5b486..706bc7482 100644 --- a/lib/l10n/app_ca.arb +++ b/lib/l10n/app_ca.arb @@ -870,7 +870,6 @@ "countdown": "Compte enrere", "stopwatch": "Cronometre", "gymModeDefaultCountdownTime": "Temps de compte enrere per defecte, en segons", - "gymModeNotifyOnCountdownFinish": "Notifica en finalitzar el compte enrere", "duration": "Duració", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index 0a29ed607..a58291e18 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -873,7 +873,6 @@ "countdown": "Odpočet", "stopwatch": "Stopky", "gymModeDefaultCountdownTime": "Výchozí doba odpočítávání v sekundách", - "gymModeNotifyOnCountdownFinish": "Upozornit na konec odpočítávání", "duration": "Doba trvání", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 865a77e64..6ba3a11b0 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -848,7 +848,6 @@ "countdown": "Herunterzählen", "stopwatch": "Stoppuhr", "gymModeDefaultCountdownTime": "Standard-Countdown-Zeit in Sekunden", - "gymModeNotifyOnCountdownFinish": "Benachrichtigung bei Ende des Countdowns", "duration": "Dauer", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 0c0d62230..11f935b58 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -375,13 +375,12 @@ "countdown": "Countdown", "stopwatch": "Stopwatch", "gymModeDefaultCountdownTime": "Default countdown time, in seconds", - "gymModeNotifyOnCountdownFinish": "Notify on countdown end", - "gymModeRestAlarm": "Rest alarm", - "gymModeRestAlarmHelp": "System notification when the rest is over, also with the screen locked", + "gymModeAlertOnRestEnd": "Alert when rest ends", + "gymModeAlertOnRestEndHelp": "Vibrates in gym mode, or sends a notification when the app is in the background", "gymModeWorkoutNotification": "Workout notification", "gymModeExactAlarmMissing": "Without the exact alarm permission, the rest alarm can be a few minutes late", "gymModeExactAlarmAllow": "Allow", - "gymModeWorkoutNotificationHelp": "Shows the rest and the next set, with buttons to log it or skip the rest", + "gymModeWorkoutNotificationHelp": "While the app is in the background: rest countdown and next set, with buttons to log or skip", "workoutNotificationRestOver": "Rest is over", "workoutNotificationNext": "Next: {set}", "@workoutNotificationNext": { @@ -411,6 +410,10 @@ "workoutNotificationSkipRest": "Skip rest", "workoutNotificationNotLoggedTitle": "Set not logged", "workoutNotificationNotLoggedBody": "Open gym mode to continue the workout", + "workoutNotificationAlarmChannel": "Rest alarm", + "@workoutNotificationAlarmChannel": { + "description": "Name of the Android notification channel for the alert at the end of a rest" + }, "workoutNotificationChannel": "Workout", "@workoutNotificationChannel": { "description": "Name of the Android notification channel for the ongoing workout notification" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index eeb9974c7..4513855ae 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -838,7 +838,6 @@ "countdown": "Cuenta regresiva", "stopwatch": "Cronómetro", "gymModeDefaultCountdownTime": "Tiempo predeterminado de cuenta regresiva, en segundos", - "gymModeNotifyOnCountdownFinish": "Notificar al terminar cuenta regresiva", "duration": "Duración", "volume": "Volumen", "@volume": { diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 11f0a9372..a76b3559d 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -840,7 +840,6 @@ "countdown": "Compte à rebours", "stopwatch": "Chronomètre", "gymModeDefaultCountdownTime": "Temps de compte à rebours par défaut, en secondes", - "gymModeNotifyOnCountdownFinish": "Notifier à la fin du compte à rebours", "duration": "Durée", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_hr.arb b/lib/l10n/app_hr.arb index 898722460..2ef18eb77 100644 --- a/lib/l10n/app_hr.arb +++ b/lib/l10n/app_hr.arb @@ -992,7 +992,6 @@ "countdown": "Odbrojavanje", "stopwatch": "Štoperica", "gymModeDefaultCountdownTime": "Zadano vrijeme odbrojavanja, u sekundama", - "gymModeNotifyOnCountdownFinish": "Obavijesti pri kraju odbrojavanja", "duration": "Trajanje", "durationHoursMinutes": "{hours} h {minutes} min", "@durationHoursMinutes": { diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 412ddf210..201f95c3f 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -406,7 +406,6 @@ "countdown": "Visszaszámláló", "stopwatch": "Stopperóra", "gymModeDefaultCountdownTime": "Alapértelmezett visszaszámlálási idő másodpercben", - "gymModeNotifyOnCountdownFinish": "Értesítés a visszaszámlálás végén", "duration": "Időtartam", "durationHoursMinutes": "{hours} ó {minutes} p", "@durationHoursMinutes": { diff --git a/lib/l10n/app_id.arb b/lib/l10n/app_id.arb index ed4ea80a8..ed0296ba7 100644 --- a/lib/l10n/app_id.arb +++ b/lib/l10n/app_id.arb @@ -918,7 +918,6 @@ "gymModeTimerTypeHelText": "Jika set memiliki waktu jeda, hitung mundur akan selalu digunakan.", "countdown": "Hitung Mundur", "gymModeDefaultCountdownTime": "Waktu hitung mundur default, dalam detik", - "gymModeNotifyOnCountdownFinish": "Beri notifikasi saat hitung mundur selesai", "duration": "Durasi", "durationHoursMinutes": "{hours}j {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 063cee369..958b6ec52 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -943,7 +943,6 @@ "countdown": "Conto alla rovescia", "stopwatch": "Cronometro", "gymModeDefaultCountdownTime": "Conto alla rovescia di default, in secondi", - "gymModeNotifyOnCountdownFinish": "Notifica quando il conto alla rovescia finisce", "duration": "Durata", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_mk.arb b/lib/l10n/app_mk.arb index cc2f2e4f0..cf4fa5e66 100644 --- a/lib/l10n/app_mk.arb +++ b/lib/l10n/app_mk.arb @@ -550,7 +550,6 @@ "countdown": "Одбројување", "stopwatch": "Штоперица", "gymModeDefaultCountdownTime": "Стандардно време на одбројување, во секунди", - "gymModeNotifyOnCountdownFinish": "Извести на крајот од одбројувањето", "duration": "Времетраење", "durationHoursMinutes": "{hours}ч {minutes}м", "@durationHoursMinutes": { diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 3bf36afe3..7a95c7c10 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -254,7 +254,6 @@ "countdown": "Afteller", "stopwatch": "Stopwatch", "gymModeDefaultCountdownTime": "Standaard afteltijd, in secondes", - "gymModeNotifyOnCountdownFinish": "Notificeer op einde aftelling", "duration": "Duur", "durationHoursMinutes": "{hours}u {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index 45cbf48b9..25a8a38be 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -834,7 +834,6 @@ "countdown": "Odliczanie", "stopwatch": "Stoper", "gymModeDefaultCountdownTime": "Domyślny czas timera, w sekundach", - "gymModeNotifyOnCountdownFinish": "Powiadom na koniec odliczania", "duration": "Czas trwania", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 330b94703..6d849fb2e 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -850,7 +850,6 @@ "countdown": "Contagem regressiva", "stopwatch": "Cronômetro", "gymModeDefaultCountdownTime": "Tempo de contagem regressiva padrão, em segundos", - "gymModeNotifyOnCountdownFinish": "Notificar quando a contagem regressiva terminar", "duration": "Duração", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_pt_BR.arb b/lib/l10n/app_pt_BR.arb index da6fa0b07..cc3a14f61 100644 --- a/lib/l10n/app_pt_BR.arb +++ b/lib/l10n/app_pt_BR.arb @@ -902,7 +902,6 @@ "countdown": "Contagem regressiva", "stopwatch": "cronômetro", "gymModeDefaultCountdownTime": "Tempo de contagem regressiva padrão, em segundos", - "gymModeNotifyOnCountdownFinish": "Notificar no final da contagem regressiva", "duration": "Duração", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_ro.arb b/lib/l10n/app_ro.arb index a884c2c32..5b5d7b531 100644 --- a/lib/l10n/app_ro.arb +++ b/lib/l10n/app_ro.arb @@ -365,7 +365,6 @@ "countdown": "Numărătoare inversă", "stopwatch": "Cronometru", "gymModeDefaultCountdownTime": "Timp implicit pentru numărătoare inversă, în secunde", - "gymModeNotifyOnCountdownFinish": "Notifică la finalul numărătorii inverse", "duration": "Durată", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 77f91901d..cb0210a1a 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -884,7 +884,6 @@ "countdown": "Обратный отсчёт", "stopwatch": "Секундомер", "gymModeDefaultCountdownTime": "Время обратного отсчёта по умолчанию (в секундах)", - "gymModeNotifyOnCountdownFinish": "Уведомлять об окончании отсчёта", "duration": "Длительность", "durationHoursMinutes": "{hours} ч {minutes} мин", "@durationHoursMinutes": { diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 14a7debd4..c00745be7 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -328,7 +328,6 @@ "countdown": "Odštevanje", "stopwatch": "Štoparica", "gymModeDefaultCountdownTime": "Privzeti čas za odštevanje, v sekundah", - "gymModeNotifyOnCountdownFinish": "Opomnik ob koncu odštevanja", "duration": "Trajanje", "durationHoursMinutes": "{hours} h {minutes} min", "@durationHoursMinutes": { diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 4801908cf..5b81274f2 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -920,7 +920,6 @@ "countdown": "Зворотний відлік", "stopwatch": "Секундомір", "gymModeDefaultCountdownTime": "Час зворотного відліку за замовчуванням, у секундах", - "gymModeNotifyOnCountdownFinish": "Повідомити про закінчення зворотного відліку", "duration": "Тривалість", "durationHoursMinutes": "{hours}год {minutes}хв", "@durationHoursMinutes": { diff --git a/lib/l10n/app_zh_Hant.arb b/lib/l10n/app_zh_Hant.arb index 62a08ddd4..8ad6b1c6f 100644 --- a/lib/l10n/app_zh_Hant.arb +++ b/lib/l10n/app_zh_Hant.arb @@ -1021,7 +1021,6 @@ "countdown": "倒數計時", "stopwatch": "碼表", "gymModeDefaultCountdownTime": "預設倒數時間(秒)", - "gymModeNotifyOnCountdownFinish": "倒數結束時通知", "personalRecords": "個人紀錄", "errorViewDetails": "技術細節", "errorInfoDescription": "不好意思,目前出了點問題。你可以前往 GitHub 提交問題以幫助我們修復此問題。", diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index d81e0e6dd..a14405407 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -1472,12 +1472,155 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { as String); @override - String get gymModeNotifyOnCountdownFinish => + String get gymModeAlertOnRestEnd => (super.noSuchMethod( - Invocation.getter(#gymModeNotifyOnCountdownFinish), + Invocation.getter(#gymModeAlertOnRestEnd), returnValue: _i3.dummyValue( this, - Invocation.getter(#gymModeNotifyOnCountdownFinish), + Invocation.getter(#gymModeAlertOnRestEnd), + ), + ) + as String); + + @override + String get gymModeAlertOnRestEndHelp => + (super.noSuchMethod( + Invocation.getter(#gymModeAlertOnRestEndHelp), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeAlertOnRestEndHelp), + ), + ) + as String); + + @override + String get gymModeWorkoutNotification => + (super.noSuchMethod( + Invocation.getter(#gymModeWorkoutNotification), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeWorkoutNotification), + ), + ) + as String); + + @override + String get gymModeExactAlarmMissing => + (super.noSuchMethod( + Invocation.getter(#gymModeExactAlarmMissing), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeExactAlarmMissing), + ), + ) + as String); + + @override + String get gymModeExactAlarmAllow => + (super.noSuchMethod( + Invocation.getter(#gymModeExactAlarmAllow), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeExactAlarmAllow), + ), + ) + as String); + + @override + String get gymModeWorkoutNotificationHelp => + (super.noSuchMethod( + Invocation.getter(#gymModeWorkoutNotificationHelp), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeWorkoutNotificationHelp), + ), + ) + as String); + + @override + String get workoutNotificationRestOver => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationRestOver), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationRestOver), + ), + ) + as String); + + @override + String get workoutNotificationInProgress => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationInProgress), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationInProgress), + ), + ) + as String); + + @override + String get workoutNotificationLogSet => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationLogSet), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationLogSet), + ), + ) + as String); + + @override + String get workoutNotificationSkipRest => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationSkipRest), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationSkipRest), + ), + ) + as String); + + @override + String get workoutNotificationNotLoggedTitle => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationNotLoggedTitle), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationNotLoggedTitle), + ), + ) + as String); + + @override + String get workoutNotificationNotLoggedBody => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationNotLoggedBody), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationNotLoggedBody), + ), + ) + as String); + + @override + String get workoutNotificationAlarmChannel => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationAlarmChannel), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationAlarmChannel), + ), + ) + as String); + + @override + String get workoutNotificationChannel => + (super.noSuchMethod( + Invocation.getter(#workoutNotificationChannel), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#workoutNotificationChannel), ), ) as String); @@ -3687,6 +3830,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get authorHelpText => + (super.noSuchMethod( + Invocation.getter(#authorHelpText), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#authorHelpText), + ), + ) + as String); + @override String get imageDetailsAuthorLink => (super.noSuchMethod( @@ -5554,6 +5708,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String workoutNotificationNext(String? set) => + (super.noSuchMethod( + Invocation.method(#workoutNotificationNext, [set]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#workoutNotificationNext, [set]), + ), + ) + as String); + + @override + String workoutNotificationSetOf(int? current, int? total) => + (super.noSuchMethod( + Invocation.method(#workoutNotificationSetOf, [current, total]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#workoutNotificationSetOf, [current, total]), + ), + ) + as String); + @override String durationHoursMinutes(int? hours, int? minutes) => (super.noSuchMethod( diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index 567adfcf5..b825ceebe 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -91,7 +91,7 @@ void main() { }); test('No alarm when the setting is off', () { - notifier.state = notifier.state.copyWith(restAlarmEnabled: false); + notifier.state = notifier.state.copyWith(alertOnCountdownEnd: false); onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); final target = build(); diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index 7665e3718..a2823280d 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -190,7 +190,7 @@ void main() { test('Each setting only switches off its own notification', () async { initGymMode(); - gymState.state = gymState.state.copyWith(restAlarmEnabled: false); + gymState.state = gymState.state.copyWith(alertOnCountdownEnd: false); await startRest(); verifyNever(service.scheduleRestAlarm(any, any)); verify(service.showControls(any, any)); @@ -198,7 +198,7 @@ void main() { clearInteractions(service); await withClock(Clock.fixed(now), () async { gymState.state = gymState.state.copyWith( - restAlarmEnabled: true, + alertOnCountdownEnd: true, showWorkoutNotification: false, ); await settle(); diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 392ec6da5..29e8172ae 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -525,30 +525,30 @@ void main() { test('Both are on without stored preferences', () async { await notifier.loadPrefs(); - expect(notifier.state.restAlarmEnabled, isTrue); + expect(notifier.state.alertOnCountdownEnd, isTrue); expect(notifier.state.showWorkoutNotification, isTrue); }); test('Stored values are loaded', () async { - await PreferenceHelper.asyncPref.setBool(PREFS_REST_ALARM, false); + await PreferenceHelper.asyncPref.setBool(PREFS_ALERT_COUNTDOWN, false); await PreferenceHelper.asyncPref.setBool(PREFS_WORKOUT_NOTIFICATION, false); await notifier.loadPrefs(); - expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.alertOnCountdownEnd, isFalse); expect(notifier.state.showWorkoutNotification, isFalse); }); test('The setters change only their own flag and persist it', () async { - notifier.setRestAlarmEnabled(false); + notifier.setAlertOnCountdownEnd(false); await pumpEventQueue(); - expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.alertOnCountdownEnd, isFalse); expect(notifier.state.showWorkoutNotification, isTrue); - expect(await PreferenceHelper.asyncPref.getBool(PREFS_REST_ALARM), false); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_ALERT_COUNTDOWN), false); notifier.setShowWorkoutNotification(false); await pumpEventQueue(); - expect(notifier.state.restAlarmEnabled, isFalse); + expect(notifier.state.alertOnCountdownEnd, isFalse); expect(notifier.state.showWorkoutNotification, isFalse); expect(await PreferenceHelper.asyncPref.getBool(PREFS_WORKOUT_NOTIFICATION), false); }); diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index 885b814d3..c22d106cd 100644 --- a/test/features/routines/screens/gym_mode_test.dart +++ b/test/features/routines/screens/gym_mode_test.dart @@ -608,10 +608,10 @@ void main() { testWidgets( 'no permission request with both notification settings off', (WidgetTester tester) async { - await PreferenceHelper.asyncPref.setBool(PREFS_REST_ALARM, false); + await PreferenceHelper.asyncPref.setBool(PREFS_ALERT_COUNTDOWN, false); await PreferenceHelper.asyncPref.setBool(PREFS_WORKOUT_NOTIFICATION, false); addTearDown(() async { - await PreferenceHelper.asyncPref.remove(PREFS_REST_ALARM); + await PreferenceHelper.asyncPref.remove(PREFS_ALERT_COUNTDOWN); await PreferenceHelper.asyncPref.remove(PREFS_WORKOUT_NOTIFICATION); }); diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index baa94d185..d1b397ce9 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -63,7 +63,6 @@ void main() { showTimerPages: true, useCountdownBetweenSets: true, countdownDuration: const Duration(seconds: DEFAULT_COUNTDOWN_DURATION), - alertOnCountdownEnd: false, dayId: routine.days.first.id, iteration: 1, routine: routine, @@ -102,18 +101,13 @@ void main() { await tester.tap(optionsTile); await tester.pumpAndSettle(); - // Toggle notify countdown first (it is only enabled while timer/countdown are active) + // Toggle the rest end alert first (it is only enabled while timer pages are shown) final notifySwitch = find.byKey(const ValueKey('gym-mode-notify-countdown')); expect(notifySwitch, findsOneWidget); + await tester.ensureVisible(notifySwitch); await tester.tap(notifySwitch); await tester.pump(); - // The rest alarm is only enabled while timer pages are shown - final restAlarmSwitch = find.byKey(const ValueKey('gym-mode-rest-alarm')); - await tester.ensureVisible(restAlarmSwitch); - await tester.tap(restAlarmSwitch); - await tester.pump(); - final workoutNotificationSwitch = find.byKey(const ValueKey('gym-mode-workout-notification')); await tester.ensureVisible(workoutNotificationSwitch); await tester.tap(workoutNotificationSwitch); @@ -143,12 +137,27 @@ void main() { final notifier = container.read(gymStateProvider.notifier); expect(notifier.state.showExercisePages, isFalse); expect(notifier.state.showTimerPages, isFalse); - expect(notifier.state.alertOnCountdownEnd, isTrue); + expect(notifier.state.alertOnCountdownEnd, isFalse); expect(notifier.state.showWorkoutDuration, isFalse); - expect(notifier.state.restAlarmEnabled, isFalse); expect(notifier.state.showWorkoutNotification, isFalse); }); + testWidgets('The rest end alert works without the default countdown', (tester) async { + // A set's own rest time is counted down regardless of the setting + final notifier = container.read(gymStateProvider.notifier); + notifier.setUseCountdownBetweenSets(false); + await pumpGymModeOptions(tester); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + + final alertSwitch = find.byKey(const ValueKey('gym-mode-notify-countdown')); + await tester.ensureVisible(alertSwitch); + await tester.tap(alertSwitch); + await tester.pump(); + + expect(notifier.state.alertOnCountdownEnd, isFalse); + }); + testWidgets('The workout notification switch only shows on Android', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); @@ -157,7 +166,7 @@ void main() { await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); await tester.pumpAndSettle(); - expect(find.byKey(const ValueKey('gym-mode-rest-alarm')), findsOneWidget); + expect(find.byKey(const ValueKey('gym-mode-notify-countdown')), findsOneWidget); expect(find.byKey(const ValueKey('gym-mode-workout-notification')), findsNothing); debugDefaultTargetPlatformOverride = null; }); @@ -303,13 +312,13 @@ void main() { expect(hint, findsNothing); }); - testWidgets('Not shown with the permission or with the rest alarm off', (tester) async { + testWidgets('Not shown with the permission or with the rest end alert off', (tester) async { await openOptions(tester); expect(hint, findsNothing); when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); container.invalidate(exactAlarmsAllowedProvider); - container.read(gymStateProvider.notifier).setRestAlarmEnabled(false); + container.read(gymStateProvider.notifier).setAlertOnCountdownEnd(false); await tester.pumpAndSettle(); expect(hint, findsNothing); }); From a69cf99f82b9c6c00e4aa5442fc91bc84de9b5e2 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 16:37:40 +0100 Subject: [PATCH 18/28] Translate the gym mode notification strings --- lib/l10n/app_de.arb | 18 +++++++++++++++++- lib/l10n/app_es.arb | 19 ++++++++++++++++++- lib/l10n/app_fr.arb | 18 +++++++++++++++++- 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 6ba3a11b0..86b8da052 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1176,5 +1176,21 @@ "calculationHelpExercises": "Zwischen {min} und {max} Übungen, {count} ausgewählt.", "calculationHelpMaxReps": "{min} bis {max}. Sätze darüber werden ignoriert.", "calculationHelpWindowDays": "{min} bis {max}. Wie weit zurück ein bester Satz zählt.", - "useDynamicColor": "Dynamische Farben verwenden" + "useDynamicColor": "Dynamische Farben verwenden", + "gymModeAlertOnRestEnd": "Am Pausenende benachrichtigen", + "gymModeAlertOnRestEndHelp": "Vibriert im Studiomodus oder schickt eine Benachrichtigung, wenn die App im Hintergrund ist", + "gymModeWorkoutNotification": "Trainings-Benachrichtigung", + "gymModeWorkoutNotificationHelp": "Solange die App im Hintergrund ist: Pausen-Countdown und nächster Satz, mit Buttons zum Eintragen oder Überspringen", + "gymModeExactAlarmMissing": "Ohne die Berechtigung für exakte Wecker kann der Pausenalarm ein paar Minuten zu spät kommen", + "gymModeExactAlarmAllow": "Erlauben", + "workoutNotificationRestOver": "Pause vorbei", + "workoutNotificationNext": "Als Nächstes: {set}", + "workoutNotificationSetOf": "Satz {current} von {total}", + "workoutNotificationInProgress": "Training läuft", + "workoutNotificationLogSet": "Satz eintragen", + "workoutNotificationSkipRest": "Pause überspringen", + "workoutNotificationNotLoggedTitle": "Satz nicht eingetragen", + "workoutNotificationNotLoggedBody": "Öffne den Studiomodus, um das Training fortzusetzen", + "workoutNotificationAlarmChannel": "Pausenalarm", + "workoutNotificationChannel": "Training" } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 4513855ae..3f6fa7391 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1193,5 +1193,22 @@ "calculationHelpExercises": "Entre {min} y {max} ejercicios, {count} seleccionados.", "calculationHelpMaxReps": "De {min} a {max}. Las series por encima se ignoran.", "calculationHelpWindowDays": "De {min} a {max}. Hasta dónde cuenta la mejor serie.", - "useDynamicColor": "Usar color dinámico" + "useDynamicColor": "Usar color dinámico", + "gymModeAlertOnRestEnd": "Avisar al terminar el descanso", + "gymModeAlertOnRestEndHelp": "Vibra en el modo gimnasio o envía una notificación cuando la app está en segundo plano", + "gymModeWorkoutNotification": "Notificación de entrenamiento", + "gymModeWorkoutNotificationHelp": "Mientras la app está en segundo plano: cuenta regresiva del descanso y la siguiente serie, con botones para registrar u omitir", + "gymModeExactAlarmMissing": "Sin el permiso de alarmas exactas, la alarma de descanso puede llegar unos minutos tarde", + "gymModeExactAlarmAllow": "Permitir", + "workoutNotificationRestOver": "Descanso terminado", + "workoutNotificationNext": "Siguiente: {set}", + "workoutNotificationSetOf": "Serie {current} de {total}", + "workoutNotificationInProgress": "Entrenamiento en curso", + "workoutNotificationLogSet": "Registrar serie", + "workoutNotificationSkipRest": "Saltar descanso", + "workoutNotificationNotLoggedTitle": "Serie no registrada", + "workoutNotificationNotLoggedBody": "Abre el modo gimnasio para continuar el entrenamiento", + "workoutNotificationAlarmChannel": "Alarma de descanso", + "workoutNotificationChannel": "Entrenamiento", + "authorHelpText": "Se muestra como autor del ejercicio (CC BY-SA 4.0). Cámbialo solo si no eres el autor." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index a76b3559d..02416d6a9 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1185,5 +1185,21 @@ "calculationHelpExercises": "Entre {min} et {max} exercices, {count} sélectionnés.", "calculationHelpMaxReps": "De {min} à {max}. Les séries au-dessus sont ignorées.", "calculationHelpWindowDays": "De {min} à {max}. Jusqu’où remonte la meilleure série.", - "useDynamicColor": "Utiliser les couleurs dynamiques" + "useDynamicColor": "Utiliser les couleurs dynamiques", + "gymModeAlertOnRestEnd": "Alerte en fin de repos", + "gymModeAlertOnRestEndHelp": "Vibre en mode entraînement ou envoie une notification lorsque l'application est en arrière-plan", + "gymModeWorkoutNotification": "Notification d'entraînement", + "gymModeWorkoutNotificationHelp": "Lorsque l'application est en arrière-plan : compte à rebours du repos et série suivante, avec des boutons pour enregistrer ou passer", + "gymModeExactAlarmMissing": "Sans l'autorisation des alarmes exactes, l'alarme de repos peut avoir quelques minutes de retard", + "gymModeExactAlarmAllow": "Autoriser", + "workoutNotificationRestOver": "Fin du repos", + "workoutNotificationNext": "Ensuite : {set}", + "workoutNotificationSetOf": "Série {current} sur {total}", + "workoutNotificationInProgress": "Entraînement en cours", + "workoutNotificationLogSet": "Enregistrer la série", + "workoutNotificationSkipRest": "Passer le repos", + "workoutNotificationNotLoggedTitle": "Série non enregistrée", + "workoutNotificationNotLoggedBody": "Ouvrez le mode entraînement pour poursuivre la séance", + "workoutNotificationAlarmChannel": "Alarme de repos", + "workoutNotificationChannel": "Entraînement" } From 5d8ba32bb10587a2e8d36aace97318855e974f0a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 16:46:37 +0100 Subject: [PATCH 19/28] Update translations --- lib/l10n/app_de.arb | 2 +- lib/l10n/app_en.arb | 2 +- lib/l10n/app_es.arb | 2 +- lib/l10n/app_fr.arb | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 86b8da052..3e28f5c39 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1180,7 +1180,7 @@ "gymModeAlertOnRestEnd": "Am Pausenende benachrichtigen", "gymModeAlertOnRestEndHelp": "Vibriert im Studiomodus oder schickt eine Benachrichtigung, wenn die App im Hintergrund ist", "gymModeWorkoutNotification": "Trainings-Benachrichtigung", - "gymModeWorkoutNotificationHelp": "Solange die App im Hintergrund ist: Pausen-Countdown und nächster Satz, mit Buttons zum Eintragen oder Überspringen", + "gymModeWorkoutNotificationHelp": "Ermöglicht den Zugriff auf das laufende Training und dessen Steuerung über eine dauerhafte Benachrichtigung", "gymModeExactAlarmMissing": "Ohne die Berechtigung für exakte Wecker kann der Pausenalarm ein paar Minuten zu spät kommen", "gymModeExactAlarmAllow": "Erlauben", "workoutNotificationRestOver": "Pause vorbei", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 11f935b58..316e378ce 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -380,7 +380,7 @@ "gymModeWorkoutNotification": "Workout notification", "gymModeExactAlarmMissing": "Without the exact alarm permission, the rest alarm can be a few minutes late", "gymModeExactAlarmAllow": "Allow", - "gymModeWorkoutNotificationHelp": "While the app is in the background: rest countdown and next set, with buttons to log or skip", + "gymModeWorkoutNotificationHelp": "Allows accessing and controlling the current workout via a persistent notification", "workoutNotificationRestOver": "Rest is over", "workoutNotificationNext": "Next: {set}", "@workoutNotificationNext": { diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 3f6fa7391..306bea7ae 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1197,7 +1197,7 @@ "gymModeAlertOnRestEnd": "Avisar al terminar el descanso", "gymModeAlertOnRestEndHelp": "Vibra en el modo gimnasio o envía una notificación cuando la app está en segundo plano", "gymModeWorkoutNotification": "Notificación de entrenamiento", - "gymModeWorkoutNotificationHelp": "Mientras la app está en segundo plano: cuenta regresiva del descanso y la siguiente serie, con botones para registrar u omitir", + "gymModeWorkoutNotificationHelp": "Permite acceder al entrenamiento en curso y controlarlo mediante una notificación permanente", "gymModeExactAlarmMissing": "Sin el permiso de alarmas exactas, la alarma de descanso puede llegar unos minutos tarde", "gymModeExactAlarmAllow": "Permitir", "workoutNotificationRestOver": "Descanso terminado", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 02416d6a9..aff18c46f 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1189,7 +1189,7 @@ "gymModeAlertOnRestEnd": "Alerte en fin de repos", "gymModeAlertOnRestEndHelp": "Vibre en mode entraînement ou envoie une notification lorsque l'application est en arrière-plan", "gymModeWorkoutNotification": "Notification d'entraînement", - "gymModeWorkoutNotificationHelp": "Lorsque l'application est en arrière-plan : compte à rebours du repos et série suivante, avec des boutons pour enregistrer ou passer", + "gymModeWorkoutNotificationHelp": "Permet d'accéder à l'entraînement en cours et de le contrôler via une notification permanente", "gymModeExactAlarmMissing": "Sans l'autorisation des alarmes exactes, l'alarme de repos peut avoir quelques minutes de retard", "gymModeExactAlarmAllow": "Autoriser", "workoutNotificationRestOver": "Fin du repos", From c738ab54a845b66ef507142a0c8329c12479d8a7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 17:39:03 +0100 Subject: [PATCH 20/28] Offer recent logs as quick logs in the notification --- .../workout_notification_content.dart | 109 ++++++++++++++- .../workout_notification_controller.dart | 91 +++++++++++-- .../workout_notification_service.dart | 45 ++++++- .../providers/gym_state_notifier.dart | 21 ++- lib/l10n/app_en.arb | 11 +- .../workout_notification_content_test.dart | 127 +++++++++++++++++- .../workout_notification_controller_test.dart | 126 +++++++++++++++++ .../workout_notification_service_test.dart | 119 +++++++++++++++- .../routines/providers/gym_state_test.dart | 51 +++++++ 9 files changed, 667 insertions(+), 33 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index af2b121ca..b5775e694 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -20,10 +20,17 @@ import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:equatable/equatable.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/core/misc.dart'; +import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/validators.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +/// How much "+30 s" adds to a rest +const REST_EXTENSION = Duration(seconds: 30); + /// Identifies the gym session and the slot pages a notification action targets class WorkoutNotificationPayload extends Equatable { final int routineId; @@ -98,8 +105,15 @@ class WorkoutControls extends Equatable { final bool canLogSet; final bool canSkipRest; + final bool canExtendRest; final WorkoutNotificationPayload payload; + /// Values of earlier logs that "log set" offers besides the planned ones + final List quickLogs; + + /// Image of the exercise the notification is about + final Uri? image; + const WorkoutControls({ required this.title, required this.body, @@ -108,6 +122,9 @@ class WorkoutControls extends Equatable { this.chronometerCountsDown = false, this.canLogSet = false, this.canSkipRest = false, + this.canExtendRest = false, + this.quickLogs = const [], + this.image, }); @override @@ -118,7 +135,10 @@ class WorkoutControls extends Equatable { chronometerCountsDown, canLogSet, canSkipRest, + canExtendRest, payload, + quickLogs, + image, ]; } @@ -128,24 +148,42 @@ class RestAlarm extends Equatable { final String title; final String body; final bool canLogSet; + final bool canExtendRest; final WorkoutNotificationPayload payload; + /// See [WorkoutControls.quickLogs] + final List quickLogs; + final Uri? image; + const RestAlarm({ required this.at, required this.title, required this.body, required this.payload, this.canLogSet = false, + this.canExtendRest = false, + this.quickLogs = const [], + this.image, }); @override - List get props => [at, title, body, canLogSet, payload]; + List get props => [ + at, + title, + body, + canLogSet, + canExtendRest, + payload, + quickLogs, + image, + ]; } /// Localized texts the platform needs besides the notification content class WorkoutNotificationLabels extends Equatable { final String logSet; final String skipRest; + final String extendRest; final String controlsChannel; final String alarmChannel; final String notLoggedTitle; @@ -154,6 +192,7 @@ class WorkoutNotificationLabels extends Equatable { const WorkoutNotificationLabels({ required this.logSet, required this.skipRest, + required this.extendRest, required this.controlsChannel, required this.alarmChannel, required this.notLoggedTitle, @@ -163,6 +202,7 @@ class WorkoutNotificationLabels extends Equatable { WorkoutNotificationLabels.of(AppLocalizations i18n) : logSet = i18n.workoutNotificationLogSet, skipRest = i18n.workoutNotificationSkipRest, + extendRest = i18n.workoutNotificationExtendRest(REST_EXTENSION.inSeconds), controlsChannel = i18n.workoutNotificationChannel, alarmChannel = i18n.workoutNotificationAlarmChannel, notLoggedTitle = i18n.workoutNotificationNotLoggedTitle, @@ -172,6 +212,7 @@ class WorkoutNotificationLabels extends Equatable { List get props => [ logSet, skipRest, + extendRest, controlsChannel, alarmChannel, notLoggedTitle, @@ -194,15 +235,61 @@ class WorkoutNotificationTarget extends Equatable { List get props => [controls, alarm]; } +/// How many earlier logs "log set" offers at most +const _MAX_QUICK_LOGS = 3; + +/// The earlier logs of [planned]'s exercise that "log set" offers, by label. +/// +/// Newest first, one per label, without the planned values. Only plain +/// repetitions: other units have server names that need a BuildContext. +Map quickLogChoices(SetConfigData planned, List recentLogs) { + // What "log set" logs, with the units resolved + final plannedLog = Log.fromSetConfigData(planned); + final choices = {}; + for (final log in recentLogs) { + if (choices.length == _MAX_QUICK_LOGS) { + break; + } + final isPlanned = + log.repetitions == plannedLog.repetitions && + log.repetitionsUnitId == plannedLog.repetitionsUnitId && + log.weight == plannedLog.weight && + log.weightUnitId == plannedLog.weightUnitId; + if (log.exerciseId != planned.exerciseId || + log.repetitionsUnitId != REP_UNIT_REPETITIONS_ID || + log.repetitions == null || + isPlanned) { + continue; + } + choices.putIfAbsent(_quickLogLabel(log), () => log); + } + return choices; +} + +String _quickLogLabel(Log log) { + final weight = log.weight; + final unit = log.weightUnitObj?.name; + final rir = log.rir; + return [ + formatNum(log.repetitions!).toString(), + if (weight != null && weight != 0) ...['×', formatNum(weight).toString(), ?unit], + if (rir != null) '(${formatNum(rir)} RiR)', + ].join(' '); +} + /// Derives the workout notifications from [state] at [now]. /// /// [withControls] is whether the ongoing notification is supported and wanted. +/// [recentLogs] are earlier logs of the exercise of the set to log, see +/// [quickLogChoices], and [mediaUrl] turns an image path into its URL. WorkoutNotificationTarget buildWorkoutNotification( GymModeState state, { required DateTime now, required AppLocalizations i18n, required String languageCode, required bool withControls, + List recentLogs = const [], + Uri? Function(String? path)? mediaUrl, }) { if (!state.isInitialized) { return WorkoutNotificationTarget.none; @@ -221,6 +308,12 @@ WorkoutNotificationTarget buildWorkoutNotification( weight: page.setConfigData!.weight, ); + List quickLogs(SlotPageEntry page) => + quickLogChoices(page.setConfigData!, recentLogs).keys.toList(); + + Uri? image(SlotPageEntry? page) => + page == null ? null : mediaUrl?.call(page.setConfigData!.exercise.getMainImage?.image); + WorkoutNotificationPayload payload({String? logSlotUuid, String? restSlotUuid}) => WorkoutNotificationPayload( routineId: state.routine.id!, @@ -243,6 +336,8 @@ WorkoutNotificationTarget buildWorkoutNotification( !next.logDone && plannedComplete(next); final actionPayload = payload(logSlotUuid: next?.uuid, restSlotUuid: current!.uuid); + final nextQuickLogs = canLogSet ? quickLogs(next) : const []; + final nextImage = image(next); final endsAt = state.restEndsAt; final restRunning = endsAt != null && endsAt.isAfter(now); @@ -253,7 +348,11 @@ WorkoutNotificationTarget buildWorkoutNotification( title: i18n.workoutNotificationRestOver, body: body, canLogSet: canLogSet, + // Starts another short countdown once the rest is over + canExtendRest: true, payload: actionPayload, + quickLogs: nextQuickLogs, + image: nextImage, ) : null; @@ -265,7 +364,10 @@ WorkoutNotificationTarget buildWorkoutNotification( chronometerCountsDown: restRunning, canLogSet: canLogSet, canSkipRest: true, + canExtendRest: endsAt != null, payload: actionPayload, + quickLogs: nextQuickLogs, + image: nextImage, ) : null; @@ -286,6 +388,7 @@ WorkoutNotificationTarget buildWorkoutNotification( ) .toList(); final config = current.setConfigData!; + final canLogSet = !current.logDone && plannedComplete(current); return WorkoutNotificationTarget( controls: WorkoutControls( @@ -293,8 +396,10 @@ WorkoutNotificationTarget buildWorkoutNotification( body: '${i18n.workoutNotificationSetOf(sameExercise.indexOf(current) + 1, sameExercise.length)}' ' · ${config.textRepr}', - canLogSet: !current.logDone && plannedComplete(current), + canLogSet: canLogSet, payload: payload(logSlotUuid: current.uuid), + quickLogs: canLogSet ? quickLogs(current) : const [], + image: image(current), ), ); } diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index 614666087..4feac7af7 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -25,9 +25,13 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/core/network/wger_base.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; +import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_notifier.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; /// Whether the gym mode screen is mounted @@ -58,6 +62,11 @@ class WorkoutNotificationController { WorkoutNotificationTarget? _shown = WorkoutNotificationTarget.none; Future _queue = Future.value(); + /// Earlier logs of the exercise of the set "log set" logs + ProviderSubscription>>? _recentLogsSubscription; + int? _recentLogsExerciseId; + List _recentLogs = const []; + WorkoutNotificationController(this._ref, this._service); /// The locale the app renders in, also without a BuildContext @@ -88,17 +97,56 @@ class WorkoutNotificationController { // Only while gym mode is open in the background: on screen it shows the // rest itself, and leaving it (X, back) ends the notifications + WorkoutNotificationTarget build({required bool withControls}) => buildWorkoutNotification( + state, + now: clock.now(), + i18n: i18n, + languageCode: locale.languageCode, + withControls: withControls, + recentLogs: _recentLogs, + mediaUrl: _ref.read(mediaUrlBuilderProvider), + ); + final target = inForeground || !_ref.read(gymModeVisibleProvider) ? WorkoutNotificationTarget.none - : buildWorkoutNotification( - state, - now: clock.now(), - i18n: i18n, - languageCode: locale.languageCode, - withControls: _service.supportsControls && state.showWorkoutNotification, - ); + : build(withControls: _service.supportsControls && state.showWorkoutNotification); final labels = WorkoutNotificationLabels.of(i18n); unawaited(_enqueue(() => _apply(target, labels))); + + // Also while nothing is shown, so the logs are there once something is + _watchRecentLogs(state, build(withControls: true)); + } + + /// Follows the earlier logs of the set the notification can log + void _watchRecentLogs(GymModeState state, WorkoutNotificationTarget target) { + final uuid = target.controls?.payload.logSlotUuid; + final exerciseId = uuid == null + ? null + : state.getSlotPageByUUID(uuid)?.setConfigData?.exerciseId; + if (exerciseId == _recentLogsExerciseId) { + return; + } + + _recentLogsSubscription?.close(); + _recentLogsSubscription = null; + _recentLogsExerciseId = exerciseId; + _recentLogs = const []; + if (exerciseId == null) { + return; + } + _recentLogsSubscription = _ref.listen( + pastExerciseLogsProvider( + routineId: state.routine.id!, + exerciseId: exerciseId, + weeksBack: state.logScopeWeeks, + ), + (_, logs) { + _recentLogs = logs.value ?? const []; + update(); + }, + // The log page may have loaded them already + fireImmediately: true, + ); } /// Like [update], also when nothing seems to have changed: the platform may @@ -132,9 +180,10 @@ class WorkoutNotificationController { /// Carries out a notification action. Stale actions only refresh the /// notification, without a running session the user is sent to the app. - Future handleAction(String? actionId, String? encodedPayload) async { + /// [input] is the quick log the user picked, if any. + Future handleAction(String? actionId, String? encodedPayload, [String? input]) async { try { - await _handleAction(actionId, encodedPayload); + await _handleAction(actionId, encodedPayload, input); } finally { // Lets iOS suspend the app again once the notification is up to date await _queue; @@ -142,7 +191,7 @@ class WorkoutNotificationController { } } - Future _handleAction(String? actionId, String? encodedPayload) async { + Future _handleAction(String? actionId, String? encodedPayload, String? input) async { final state = _ref.read(gymStateProvider); if (!state.isInitialized) { // E.g. iOS started the app in the background just for this action @@ -157,13 +206,27 @@ class WorkoutNotificationController { switch (actionId) { case WORKOUT_NOTIFICATION_ACTION_LOG_SET: final uuid = payload.logSlotUuid; - if (uuid != null) { - await notifier.logPlannedSet(uuid); + final config = uuid == null ? null : state.getSlotPageByUUID(uuid)?.setConfigData; + if (config == null) { + break; + } + if (input == null) { + await notifier.logPlannedSet(uuid!); + } else { + // An unknown label is from an outdated notification + final valuesFrom = quickLogChoices(config, _recentLogs)[input]; + if (valuesFrom != null) { + await notifier.logPlannedSet(uuid!, valuesFrom: valuesFrom); + } } case WORKOUT_NOTIFICATION_ACTION_SKIP_REST: if (state.getSlotEntryPageByIndex()?.uuid == payload.restSlotUuid) { notifier.skipRest(); } + case WORKOUT_NOTIFICATION_ACTION_EXTEND_REST: + if (state.getSlotEntryPageByIndex()?.uuid == payload.restSlotUuid) { + notifier.extendRest(REST_EXTENSION); + } } } catch (e) { _logger.warning('Notification action $actionId failed: $e'); @@ -192,8 +255,8 @@ final workoutNotificationControllerProvider = Provider workoutNotificationBackgroundHandler(NotificationResponse response) async { final port = IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT); if (port != null) { - port.send([response.actionId, response.payload]); + port.send([response.actionId, response.payload, response.input]); return; } @@ -212,9 +214,11 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { priority: Priority.high, category: AndroidNotificationCategory.alarm, visibility: NotificationVisibility.public, + largeIcon: await _cachedImage(alarm.image), actions: [ - if (alarm.canLogSet) - AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, labels.logSet), + if (alarm.canExtendRest) + AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, labels.extendRest), + if (alarm.canLogSet) _logSetAction(alarm.quickLogs, labels), ], ), iOS: DarwinNotificationDetails( @@ -251,17 +255,48 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { when: chronometerAt?.millisecondsSinceEpoch, usesChronometer: chronometerAt != null, chronometerCountDown: controls.chronometerCountsDown, + largeIcon: await _cachedImage(controls.image), actions: [ if (controls.canSkipRest) AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_SKIP_REST, labels.skipRest), - if (controls.canLogSet) - AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, labels.logSet), + if (controls.canExtendRest) + AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, labels.extendRest), + if (controls.canLogSet) _logSetAction(controls.quickLogs, labels), ], ), ), ); } + /// "Log set" logs the planned values, Android offers the [quickLogs] next to + /// it. Without free text, tapping the button itself sends no input. + AndroidNotificationAction _logSetAction( + List quickLogs, + WorkoutNotificationLabels labels, + ) => AndroidNotificationAction( + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + labels.logSet, + inputs: [ + if (quickLogs.isNotEmpty) + AndroidNotificationActionInput(choices: quickLogs, allowFreeFormInput: false), + ], + ); + + /// The image if the app has it on disk already, the notification never waits + /// for a download + Future _cachedImage(Uri? image) async { + if (image == null) { + return null; + } + try { + final path = await getCachedImageFilePath(image.toString()); + return path == null ? null : FilePathAndroidBitmap(path); + } on Exception catch (e) { + _logger.fine('No cached image for the notification: $e'); + return null; + } + } + @override Future showNotLogged(WorkoutNotificationLabels labels) async { await _ensureInitialized(labels); diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 8ba45c589..f9b50112a 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -345,6 +345,17 @@ class GymStateNotifier extends _$GymStateNotifier { setCurrentPage(state.currentPage + 1); } + /// Adds [extra] to the running countdown, counted from now if the rest is + /// already over. No-op without a countdown (other pages, count-up rest). + void extendRest(Duration extra) { + final endsAt = state.restEndsAt; + if (endsAt == null) { + return; + } + final now = clock.now(); + state = state.copyWith(restEndsAt: (endsAt.isAfter(now) ? endsAt : now).add(extra)); + } + /// Saves the log draft of the current log page, marks the page as done and /// moves on to the next page. A failed write propagates to the caller. Future logCurrentSet() async { @@ -372,8 +383,9 @@ class GymStateNotifier extends _$GymStateNotifier { /// Logs the set of the log page [slotPageUuid] without the UI, e.g. from a /// notification. From the rest right before it the planned values are logged, - /// on the page itself the current draft. False if stale, done or incomplete. - Future logPlannedSet(String slotPageUuid) async { + /// on the page itself the current draft, in both cases the values of + /// [valuesFrom] if given. False if stale, done or incomplete. + Future logPlannedSet(String slotPageUuid, {Log? valuesFrom}) async { final target = state.getSlotPageByUUID(slotPageUuid); if (target == null || target.type != SlotPageType.log || target.logDone) { return false; @@ -387,7 +399,7 @@ class GymStateNotifier extends _$GymStateNotifier { return false; } - final log = onTarget ? ref.read(gymLogProvider) : _draftFor(target); + final log = valuesFrom ?? (onTarget ? ref.read(gymLogProvider) : _draftFor(target)); if (log == null || !isWorkoutLogComplete(repetitions: log.repetitions, weight: log.weight)) { return false; } @@ -395,6 +407,9 @@ class GymStateNotifier extends _$GymStateNotifier { if (onRestBefore) { setCurrentPage(target.pageIndex); } + if (valuesFrom != null) { + ref.read(gymLogProvider.notifier).copyValuesFrom(valuesFrom); + } await logCurrentSet(); return true; } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 316e378ce..a2e77a281 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -403,11 +403,20 @@ } }, "workoutNotificationInProgress": "Workout in progress", - "workoutNotificationLogSet": "Log set", + "workoutNotificationLogSet": "Log planned set", "@workoutNotificationLogSet": { "description": "Notification button that logs the next set with its planned values" }, "workoutNotificationSkipRest": "Skip rest", + "workoutNotificationExtendRest": "+{seconds} s", + "@workoutNotificationExtendRest": { + "description": "Notification button that makes the running rest longer", + "placeholders": { + "seconds": { + "type": "int" + } + } + }, "workoutNotificationNotLoggedTitle": "Set not logged", "workoutNotificationNotLoggedBody": "Open gym mode to continue the workout", "workoutNotificationAlarmChannel": "Rest alarm", diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index b825ceebe..b9c35a4f1 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -21,6 +21,9 @@ 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:wger/core/consts.dart'; +import 'package:wger/features/exercises/models/image.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; @@ -48,12 +51,18 @@ void main() { List logs() => slotPages().where((p) => p.type == SlotPageType.log).toList(); List timers() => slotPages().where((p) => p.type == SlotPageType.timer).toList(); - WorkoutNotificationTarget build({bool withControls = true}) => buildWorkoutNotification( + WorkoutNotificationTarget build({ + bool withControls = true, + List recentLogs = const [], + Uri? Function(String? path)? mediaUrl, + }) => buildWorkoutNotification( notifier.state, now: now, i18n: i18n, languageCode: 'en', withControls: withControls, + recentLogs: recentLogs, + mediaUrl: mediaUrl, ); void onPage(SlotPageEntry page, {DateTime? restStartedAt, DateTime? restEndsAt}) { @@ -187,6 +196,22 @@ void main() { expect(target.controls!.canLogSet, isFalse); }); + test('"+30 s" only for a countdown, also once it is over', () { + final timer = timers().first; + onPage(timer, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + expect(build().controls!.canExtendRest, isTrue); + expect(build().alarm!.canExtendRest, isTrue); + + onPage(timer, restStartedAt: now, restEndsAt: now.subtract(const Duration(seconds: 1))); + expect(build().controls!.canExtendRest, isTrue); + + onPage(timer, restStartedAt: now); + expect(build().controls!.canExtendRest, isFalse); + + onPage(logs()[1]); + expect(build().controls!.canExtendRest, isFalse); + }); + test('Without controls there is nothing outside a rest', () { onPage(logs()[1]); @@ -194,6 +219,106 @@ void main() { }); }); + group('Quick logs', () { + Log logOf({ + required num repetitions, + num? weight, + num? rir, + int repetitionsUnitId = REP_UNIT_REPETITIONS_ID, + int? exerciseId, + }) { + final planned = logs()[1].setConfigData!; + final log = Log( + exerciseId: exerciseId ?? planned.exerciseId, + repetitions: repetitions, + repetitionsUnitId: repetitionsUnitId, + weight: weight, + rir: rir, + ); + log.weightUnit = testWeightUnit1; + return log; + } + + test('Newest first, one per label, without the planned values', () { + final planned = logs()[1].setConfigData!; + final recent = [ + logOf(repetitions: 9, weight: 60), + logOf(repetitions: planned.repetitions!, weight: planned.weight), + logOf(repetitions: 9, weight: 60), + logOf(repetitions: 8, weight: 62.5, rir: 2), + logOf(repetitions: 12), + logOf(repetitions: 6, weight: 70), + ]; + + final choices = quickLogChoices(planned, recent); + + expect(choices.keys, ['9 × 60 kg', '8 × 62.5 kg (2 RiR)', '12']); + expect(choices['9 × 60 kg'], same(recent[0])); + }); + + test('Skips other exercises and units the label cannot name', () { + final planned = logs()[1].setConfigData!; + + final choices = quickLogChoices(planned, [ + logOf(repetitions: 9, weight: 60, exerciseId: planned.exerciseId + 1), + logOf(repetitions: 30, repetitionsUnitId: testRepetitionUnit2.id), + ]); + + expect(choices, isEmpty); + }); + + test('The rest before a set and the set page offer them with "log set"', () { + final recent = [logOf(repetitions: 9, weight: 60)]; + final endsAt = now.add(const Duration(seconds: 90)); + onPage(timers().first, restStartedAt: now, restEndsAt: endsAt); + + var target = build(recentLogs: recent); + expect(target.controls!.quickLogs, ['9 × 60 kg']); + expect(target.alarm!.quickLogs, ['9 × 60 kg']); + + onPage(logs()[1]); + target = build(recentLogs: recent); + expect(target.controls!.quickLogs, ['9 × 60 kg']); + + notifier.markSlotPageAsDone(logs()[1].uuid, isDone: true); + expect(build(recentLogs: recent).controls!.quickLogs, isEmpty); + }); + + test("The notification shows the main image of the set's exercise", () { + final config = logs()[1].setConfigData!; + config.exercise = config.exercise.copyWith( + images: [ + ExerciseImage( + id: 1, + uuid: 'image', + exerciseId: config.exerciseId, + image: '/media/bench.png', + isMain: true, + isAiGenerated: false, + style: ExerciseImageStyle.photo, + width: null, + height: null, + created: now, + lastUpdate: now, + licenseId: 1, + licenseTitle: '', + licenseObjectUrl: '', + licenseAuthor: null, + licenseAuthorUrl: '', + licenseDerivativeSourceUrl: '', + ), + ], + ); + Uri? mediaUrl(String? path) => path == null ? null : Uri.parse('https://wger.test$path'); + onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + + final target = build(mediaUrl: mediaUrl); + + expect(target.controls!.image, Uri.parse('https://wger.test/media/bench.png')); + expect(target.alarm!.image, Uri.parse('https://wger.test/media/bench.png')); + }); + }); + group('WorkoutNotificationPayload', () { test('Survives the round trip as a string', () { final payload = WorkoutNotificationPayload( diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index a2823280d..fcbf48605 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -25,11 +25,13 @@ import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.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:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_controller.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_notifier.dart'; import 'package:wger/features/routines/providers/workout_logs_repository.dart'; import '../../../../test_data/routines.dart'; @@ -284,12 +286,136 @@ void main() { IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT)!.send([ WORKOUT_NOTIFICATION_ACTION_SKIP_REST, payloadFor(restSlotUuid: slotPage(rest).uuid), + null, ]); await settle(); expect(gymState.state.currentPage, rest + 1); }); + group('Quick logs', () { + late Log earlier; + + setUp(() { + earlier = Log( + exerciseId: getTestRoutine().days.first.slots.first.entries.first.exerciseId, + repetitions: 9, + weight: 60, + ); + earlier.weightUnit = testWeightUnit1; + when( + logRepo.watchLogsByExerciseDrift( + routineId: anyNamed('routineId'), + exerciseId: anyNamed('exerciseId'), + since: anyNamed('since'), + ), + ).thenAnswer((_) => Stream.value([earlier])); + }); + + Log capturedLog() => + verify(logRepo.addLocalDrift(captureAny, dayId: anyNamed('dayId'))).captured.single + as Log; + + test('The notification offers earlier logs of the next set', () async { + await startRest(); + + final controls = verify(service.showControls(captureAny, any)).captured; + expect((controls.last as WorkoutControls).quickLogs, ['9 × 60 kg']); + }); + + test('Also when the log page already loaded the earlier logs', () async { + initGymMode(); + final next = gymState.state.pages + .expand((p) => p.slotPages) + .firstWhere((p) => p.type == SlotPageType.log); + final pastLogs = container.listen( + pastExerciseLogsProvider( + routineId: gymState.state.routine.id!, + exerciseId: next.setConfigData!.exerciseId, + weeksBack: gymState.state.logScopeWeeks, + ), + (_, _) {}, + ); + addTearDown(pastLogs.close); + await settle(); + + await startRest(); + + final controls = verify(service.showControls(captureAny, any)).captured; + expect((controls.last as WorkoutControls).quickLogs, ['9 × 60 kg']); + }); + + test('A picked quick log arrives through the port and logs its values', () async { + await startRest(); + final rest = gymState.state.currentPage; + + IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT)!.send([ + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + payloadFor(logSlotUuid: slotPage(rest + 1).uuid), + '9 × 60 kg', + ]); + await settle(); + + final saved = capturedLog(); + expect(saved.repetitions, 9); + expect(saved.weight, 60); + expect(gymState.state.currentPage, rest + 2); + }); + + test('A label the notification no longer offers logs nothing', () async { + await startRest(); + final rest = gymState.state.currentPage; + + await container + .read(workoutNotificationControllerProvider) + .handleAction( + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + payloadFor(logSlotUuid: slotPage(rest + 1).uuid), + '7 × 50 kg', + ); + await settle(); + + verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); + expect(gymState.state.currentPage, rest); + }); + }); + + test('"+30 s" makes the rest longer and moves the alarm', () async { + await startRest(); + final rest = gymState.state.currentPage; + final endsAt = gymState.state.restEndsAt!; + clearInteractions(service); + + await withClock(Clock.fixed(now), () async { + await container + .read(workoutNotificationControllerProvider) + .handleAction( + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + payloadFor(restSlotUuid: slotPage(rest).uuid), + ); + await settle(); + }); + + expect(gymState.state.restEndsAt, endsAt.add(REST_EXTENSION)); + final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; + expect((alarms.last as RestAlarm).at, endsAt.add(REST_EXTENSION)); + }); + + test('"+30 s" from an earlier rest changes nothing', () async { + await startRest(); + final endsAt = gymState.state.restEndsAt!; + + await container + .read(workoutNotificationControllerProvider) + .handleAction( + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + payloadFor(restSlotUuid: 'another rest'), + ); + await settle(); + + expect(gymState.state.restEndsAt, endsAt); + }); + test('A stale action changes nothing but shows the notification again', () async { await startRest(); final rest = gymState.state.currentPage; diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart index 6318b0929..a73a0b603 100644 --- a/test/features/routines/notifications/workout_notification_service_test.dart +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -16,10 +16,14 @@ * along with this program. If not, see . */ +import 'dart:io'; + +import 'package:extended_image/extended_image.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; import 'package:timezone/data/latest.dart' as tzdata; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; @@ -33,6 +37,7 @@ void main() { const labels = WorkoutNotificationLabels( logSet: 'Log set', skipRest: 'Skip rest', + extendRest: '+30 s', controlsChannel: 'Workout', alarmChannel: 'Rest alarm', notLoggedTitle: 'Set not logged', @@ -98,13 +103,19 @@ void main() { (calls.singleWhere((c) => c.method == 'zonedSchedule').arguments as Map)['platformSpecifics'] as Map; - RestAlarm alarm({bool canLogSet = true}) => RestAlarm( - at: DateTime.now().add(const Duration(minutes: 2)), - title: 'Rest is over', - body: 'Next: Bench press', - canLogSet: canLogSet, - payload: payload, - ); + RestAlarm alarm({bool canLogSet = true, List quickLogs = const [], Uri? image}) => + RestAlarm( + at: DateTime.now().add(const Duration(minutes: 2)), + title: 'Rest is over', + body: 'Next: Bench press', + canLogSet: canLogSet, + payload: payload, + quickLogs: quickLogs, + image: image, + ); + + Map shown() => + (calls.singleWhere((c) => c.method == 'show').arguments as Map)['platformSpecifics'] as Map; test('Initializes with the monochrome status bar icon', () async { await LocalWorkoutNotificationService().initialize(labels); @@ -140,4 +151,98 @@ void main() { await service.scheduleRestAlarm(alarm(canLogSet: false), labels); expect(scheduled()['actions'], anyOf(isNull, isEmpty)); }); + + test('Rest actions in Android order: skip, +30 s, log', () async { + await LocalWorkoutNotificationService().showControls( + WorkoutControls( + title: 'Pause', + body: 'Next: Bench press', + payload: payload, + canSkipRest: true, + canExtendRest: true, + canLogSet: true, + ), + labels, + ); + + expect((shown()['actions'] as List).map((a) => (a as Map)['id']), [ + WORKOUT_NOTIFICATION_ACTION_SKIP_REST, + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + ]); + }); + + group('Log set', () { + List inputsOfLogSet(Map details) => + ((details['actions'] as List).cast>().singleWhere( + (a) => a['id'] == WORKOUT_NOTIFICATION_ACTION_LOG_SET, + )['inputs'] + as List?) ?? + const []; + + test('Offers the quick logs as choices, without free text', () async { + await LocalWorkoutNotificationService().showControls( + WorkoutControls( + title: 'Pause', + body: 'Next: Bench press', + payload: payload, + canLogSet: true, + quickLogs: const ['9 × 60 kg', '8 × 62.5 kg'], + ), + labels, + ); + + final input = inputsOfLogSet(shown()).single! as Map; + expect(input['choices'], ['9 × 60 kg', '8 × 62.5 kg']); + expect(input['allowFreeFormInput'], isFalse); + }); + + test('Without quick logs the action takes no input', () async { + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(), labels); + + expect(inputsOfLogSet(scheduled()), isEmpty); + }); + + test('The alarm offers the quick logs too', () async { + await LocalWorkoutNotificationService().scheduleRestAlarm( + alarm(quickLogs: ['9 × 60 kg']), + labels, + ); + + expect((inputsOfLogSet(scheduled()).single! as Map)['choices'], ['9 × 60 kg']); + }); + }); + + group('Exercise image', () { + const pathProvider = MethodChannel('plugins.flutter.io/path_provider'); + final image = Uri.parse('https://wger.test/media/bench.png'); + late Directory temp; + + setUp(() { + temp = Directory.systemTemp.createTempSync('notification_image'); + addTearDown(() => temp.deleteSync(recursive: true)); + binding.defaultBinaryMessenger.setMockMethodCallHandler( + pathProvider, + (call) async => temp.path, + ); + addTearDown( + () => binding.defaultBinaryMessenger.setMockMethodCallHandler(pathProvider, null), + ); + }); + + test('Shows the image the app has cached', () async { + final file = File(p.join(temp.path, cacheImageFolderName, keyToMd5(image.toString()))) + ..createSync(recursive: true); + + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(image: image), labels); + + expect(scheduled()['largeIcon'], file.path); + }); + + test('Does not wait for an image that is not cached', () async { + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(image: image), labels); + + expect(scheduled()['largeIcon'], isNull); + }); + }); } diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 29e8172ae..b6eb6f4ed 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -736,6 +736,57 @@ void main() { expect(capturedLog().repetitions, 7); }); + test('extendRest adds to a running countdown, after its end from now', () async { + final timer = secondLog().pageIndex - 1; + withClock(Clock.fixed(start), () => notifier.setCurrentPage(timer)); + final endsAt = notifier.state.restEndsAt!; + + withClock(Clock.fixed(start), () => notifier.extendRest(const Duration(seconds: 30))); + expect(notifier.state.restEndsAt, endsAt.add(const Duration(seconds: 30))); + + final later = endsAt.add(const Duration(minutes: 5)); + withClock(Clock.fixed(later), () => notifier.extendRest(const Duration(seconds: 30))); + expect(notifier.state.restEndsAt, later.add(const Duration(seconds: 30))); + expect(notifier.state.restStartedAt, start); + }); + + test('extendRest does nothing outside a countdown', () { + notifier.setCurrentPage(secondLog().pageIndex); + + notifier.extendRest(const Duration(seconds: 30)); + + expect(notifier.state.restEndsAt, isNull); + }); + + test('logPlannedSet with the values of an earlier log logs those instead', () async { + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex - 1); + final earlier = Log(exerciseId: log.setConfigData!.exerciseId, repetitions: 8, weight: 62.5); + earlier.weightUnit = testWeightUnit2; + + expect(await notifier.logPlannedSet(log.uuid, valuesFrom: earlier), isTrue); + + final saved = capturedLog(); + expect(saved.repetitions, 8); + expect(saved.weight, 62.5); + expect(saved.weightUnitId, testWeightUnit2.id); + // The planned RiR is 1.5, the earlier log had none + expect(saved.rir, isNull); + expect(saved.slotEntryId, log.setConfigData!.slotEntryId); + expect(notifier.state.currentPage, log.pageIndex + 1); + }); + + test('logPlannedSet with an earlier log also replaces an edited draft', () async { + final log = secondLog(); + notifier.setCurrentPage(log.pageIndex); + container.read(gymLogProvider.notifier).setRepetitions(7); + final earlier = Log(exerciseId: log.setConfigData!.exerciseId, repetitions: 9, weight: 60); + + expect(await notifier.logPlannedSet(log.uuid, valuesFrom: earlier), isTrue); + + expect(capturedLog().repetitions, 9); + }); + test('logPlannedSet on the set page needs the draft', () async { // A restored state points at the page before onPageChanged seeds the draft final log = secondLog(); From 768499c015e2114161843ea963a5b95150491c0e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 17:41:50 +0100 Subject: [PATCH 21/28] Let the plate hint span the full width in gym mode --- lib/features/routines/widgets/gym_mode/log_page.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index f057a140a..9d691c089 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -185,6 +185,7 @@ class LogsPlatesWidget extends ConsumerWidget { final plateWeightsState = ref.watch(plateCalculatorProvider); return Container( + width: double.infinity, color: Theme.of(context).colorScheme.onInverseSurface, child: Column( children: [ From c908381d01468614a652b7487420c1fe2ae84818 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 18:30:57 +0100 Subject: [PATCH 22/28] Improve notification ux We now show the next set only once the rest is over, which makes more sense and is the way the app behaves. --- .../workout_notification_content.dart | 130 +++++++++++------- .../workout_notification_service.dart | 3 + lib/l10n/app_de.arb | 5 +- lib/l10n/app_en.arb | 9 +- lib/l10n/app_es.arb | 5 +- lib/l10n/app_fr.arb | 5 +- .../workout_notification_content_test.dart | 27 +++- .../workout_notification_controller_test.dart | 12 +- .../workout_notification_service_test.dart | 15 ++ 9 files changed, 139 insertions(+), 72 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index b5775e694..dfe87494f 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -99,6 +99,9 @@ class WorkoutControls extends Equatable { final String title; final String body; + /// Shown next to the app name, e.g. that the rest is over + final String? subtitle; + /// Reference time of the chronometer, none if null final DateTime? chronometerAt; final bool chronometerCountsDown; @@ -118,6 +121,7 @@ class WorkoutControls extends Equatable { required this.title, required this.body, required this.payload, + this.subtitle, this.chronometerAt, this.chronometerCountsDown = false, this.canLogSet = false, @@ -131,6 +135,7 @@ class WorkoutControls extends Equatable { List get props => [ title, body, + subtitle, chronometerAt, chronometerCountsDown, canLogSet, @@ -147,6 +152,7 @@ class RestAlarm extends Equatable { final DateTime at; final String title; final String body; + final String? subtitle; final bool canLogSet; final bool canExtendRest; final WorkoutNotificationPayload payload; @@ -160,6 +166,7 @@ class RestAlarm extends Equatable { required this.title, required this.body, required this.payload, + this.subtitle, this.canLogSet = false, this.canExtendRest = false, this.quickLogs = const [], @@ -171,6 +178,7 @@ class RestAlarm extends Equatable { at, title, body, + subtitle, canLogSet, canExtendRest, payload, @@ -303,13 +311,33 @@ WorkoutNotificationTarget buildWorkoutNotification( return '${config.exercise.getTranslation(languageCode).name} ${config.textRepr}'; } - bool plannedComplete(SlotPageEntry page) => isWorkoutLogComplete( - repetitions: page.setConfigData!.repetitions, - weight: page.setConfigData!.weight, - ); + String exerciseName(SlotPageEntry page) => + page.setConfigData!.exercise.getTranslation(languageCode).name; + + /// "Set 2 of 3 · 10 × 60 kg", counted within the exercise + String setOf(SlotPageEntry page) { + final sameExercise = state + .getPageByIndex(page.pageIndex)! + .slotPages + .where( + (p) => + p.type == SlotPageType.log && + p.setConfigData!.exerciseId == page.setConfigData!.exerciseId, + ) + .toList(); + return '${i18n.workoutNotificationSetOf(sameExercise.indexOf(page) + 1, sameExercise.length)}' + ' · ${page.setConfigData!.textRepr}'; + } + + bool canLog(SlotPageEntry page) => + !page.logDone && + isWorkoutLogComplete( + repetitions: page.setConfigData!.repetitions, + weight: page.setConfigData!.weight, + ); List quickLogs(SlotPageEntry page) => - quickLogChoices(page.setConfigData!, recentLogs).keys.toList(); + canLog(page) ? quickLogChoices(page.setConfigData!, recentLogs).keys.toList() : const []; Uri? image(SlotPageEntry? page) => page == null ? null : mediaUrl?.call(page.setConfigData!.exercise.getMainImage?.image); @@ -325,51 +353,60 @@ WorkoutNotificationTarget buildWorkoutNotification( ); if (current?.type == SlotPageType.timer) { - final next = slotPages.firstWhereOrNull( + final following = slotPages.firstWhereOrNull( (p) => p.type == SlotPageType.log && p.pageIndex > current!.pageIndex, ); - final body = next == null ? '' : i18n.workoutNotificationNext(setText(next)); - // "Log set" only works from the rest right before the set - final canLogSet = - next != null && - next.pageIndex == current!.pageIndex + 1 && - !next.logDone && - plannedComplete(next); - final actionPayload = payload(logSlotUuid: next?.uuid, restSlotUuid: current!.uuid); - final nextQuickLogs = canLogSet ? quickLogs(next) : const []; - final nextImage = image(next); + // The set right after the rest, the one the rest end is about + final next = following?.pageIndex == current!.pageIndex + 1 ? following : null; + final actionPayload = payload(logSlotUuid: next?.uuid, restSlotUuid: current.uuid); + final nextText = following == null ? '' : i18n.workoutNotificationNext(setText(following)); final endsAt = state.restEndsAt; final restRunning = endsAt != null && endsAt.isAfter(now); + // Once the rest is over the notification shows the set, like the page + // after the rest. Logging during the rest is left to the set itself. final alarm = state.alertOnCountdownEnd && restRunning ? RestAlarm( at: endsAt, - title: i18n.workoutNotificationRestOver, - body: body, - canLogSet: canLogSet, - // Starts another short countdown once the rest is over + title: next == null ? i18n.workoutNotificationRestOver : exerciseName(next), + body: next == null ? nextText : setOf(next), + subtitle: next == null ? null : i18n.workoutNotificationRestOver, + canLogSet: next != null && canLog(next), + // Starts another short countdown canExtendRest: true, payload: actionPayload, - quickLogs: nextQuickLogs, - image: nextImage, + quickLogs: next == null ? const [] : quickLogs(next), + image: image(next ?? following), ) : null; - final controls = withControls - ? WorkoutControls( - title: endsAt != null && !restRunning ? i18n.workoutNotificationRestOver : i18n.pause, - body: body, - chronometerAt: endsAt == null ? state.restStartedAt : (restRunning ? endsAt : null), - chronometerCountsDown: restRunning, - canLogSet: canLogSet, - canSkipRest: true, - canExtendRest: endsAt != null, - payload: actionPayload, - quickLogs: nextQuickLogs, - image: nextImage, - ) - : null; + final WorkoutControls? controls; + if (!withControls) { + controls = null; + } else if (endsAt != null && !restRunning && next != null) { + controls = WorkoutControls( + title: exerciseName(next), + body: setOf(next), + subtitle: i18n.workoutNotificationRestOver, + canLogSet: canLog(next), + canExtendRest: true, + payload: actionPayload, + quickLogs: quickLogs(next), + image: image(next), + ); + } else { + controls = WorkoutControls( + title: endsAt != null && !restRunning ? i18n.workoutNotificationRestOver : i18n.pause, + body: nextText, + chronometerAt: endsAt == null ? state.restStartedAt : (restRunning ? endsAt : null), + chronometerCountsDown: restRunning, + canSkipRest: true, + canExtendRest: endsAt != null, + payload: actionPayload, + image: image(following), + ); + } return WorkoutNotificationTarget(controls: controls, alarm: alarm); } @@ -379,26 +416,13 @@ WorkoutNotificationTarget buildWorkoutNotification( } if (current?.type == SlotPageType.log) { - final page = state.getPageByIndex(current!.pageIndex)!; - final sameExercise = page.slotPages - .where( - (p) => - p.type == SlotPageType.log && - p.setConfigData!.exerciseId == current.setConfigData!.exerciseId, - ) - .toList(); - final config = current.setConfigData!; - final canLogSet = !current.logDone && plannedComplete(current); - return WorkoutNotificationTarget( controls: WorkoutControls( - title: config.exercise.getTranslation(languageCode).name, - body: - '${i18n.workoutNotificationSetOf(sameExercise.indexOf(current) + 1, sameExercise.length)}' - ' · ${config.textRepr}', - canLogSet: canLogSet, + title: exerciseName(current!), + body: setOf(current), + canLogSet: canLog(current), payload: payload(logSlotUuid: current.uuid), - quickLogs: canLogSet ? quickLogs(current) : const [], + quickLogs: quickLogs(current), image: image(current), ), ); diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index def182fed..6b4efb006 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -214,6 +214,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { priority: Priority.high, category: AndroidNotificationCategory.alarm, visibility: NotificationVisibility.public, + subText: alarm.subtitle, largeIcon: await _cachedImage(alarm.image), actions: [ if (alarm.canExtendRest) @@ -222,6 +223,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ], ), iOS: DarwinNotificationDetails( + subtitle: alarm.subtitle, presentSound: true, categoryIdentifier: alarm.canLogSet ? _restEndCategory : null, ), @@ -251,6 +253,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { enableVibration: false, category: AndroidNotificationCategory.workout, visibility: NotificationVisibility.public, + subText: controls.subtitle, showWhen: chronometerAt != null, when: chronometerAt?.millisecondsSinceEpoch, usesChronometer: chronometerAt != null, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 3e28f5c39..98094dc07 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1187,8 +1187,9 @@ "workoutNotificationNext": "Als Nächstes: {set}", "workoutNotificationSetOf": "Satz {current} von {total}", "workoutNotificationInProgress": "Training läuft", - "workoutNotificationLogSet": "Satz eintragen", - "workoutNotificationSkipRest": "Pause überspringen", + "workoutNotificationLogSet": "Wie geplant eintragen", + "workoutNotificationSkipRest": "Überspringen", + "workoutNotificationExtendRest": "+{seconds} s", "workoutNotificationNotLoggedTitle": "Satz nicht eingetragen", "workoutNotificationNotLoggedBody": "Öffne den Studiomodus, um das Training fortzusetzen", "workoutNotificationAlarmChannel": "Pausenalarm", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index a2e77a281..7fbbcd337 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -405,12 +405,15 @@ "workoutNotificationInProgress": "Workout in progress", "workoutNotificationLogSet": "Log planned set", "@workoutNotificationLogSet": { - "description": "Notification button that logs the next set with its planned values" + "description": "Notification button that logs the next set with its planned values. Shown next to up to two other buttons in a single row, so keep it very short; translate the meaning, not word for word" + }, + "workoutNotificationSkipRest": "Skip", + "@workoutNotificationSkipRest": { + "description": "Notification button that ends the running rest. Shown next to up to two other buttons in a single row, so keep it very short; translate the meaning, not word for word" }, - "workoutNotificationSkipRest": "Skip rest", "workoutNotificationExtendRest": "+{seconds} s", "@workoutNotificationExtendRest": { - "description": "Notification button that makes the running rest longer", + "description": "Notification button that makes the running rest longer. Shown next to up to two other buttons in a single row, so keep it very short; translate the meaning, not word for word", "placeholders": { "seconds": { "type": "int" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 306bea7ae..800eb7074 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1204,8 +1204,9 @@ "workoutNotificationNext": "Siguiente: {set}", "workoutNotificationSetOf": "Serie {current} de {total}", "workoutNotificationInProgress": "Entrenamiento en curso", - "workoutNotificationLogSet": "Registrar serie", - "workoutNotificationSkipRest": "Saltar descanso", + "workoutNotificationLogSet": "Registrar según plan", + "workoutNotificationSkipRest": "Saltar", + "workoutNotificationExtendRest": "+{seconds} s", "workoutNotificationNotLoggedTitle": "Serie no registrada", "workoutNotificationNotLoggedBody": "Abre el modo gimnasio para continuar el entrenamiento", "workoutNotificationAlarmChannel": "Alarma de descanso", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index aff18c46f..52e8190f5 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1196,8 +1196,9 @@ "workoutNotificationNext": "Ensuite : {set}", "workoutNotificationSetOf": "Série {current} sur {total}", "workoutNotificationInProgress": "Entraînement en cours", - "workoutNotificationLogSet": "Enregistrer la série", - "workoutNotificationSkipRest": "Passer le repos", + "workoutNotificationLogSet": "Noter comme prévu", + "workoutNotificationSkipRest": "Passer", + "workoutNotificationExtendRest": "+{seconds} s", "workoutNotificationNotLoggedTitle": "Série non enregistrée", "workoutNotificationNotLoggedBody": "Ouvrez le mode entraînement pour poursuivre la séance", "workoutNotificationAlarmChannel": "Alarme de repos", diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index b9c35a4f1..2c3e30d25 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -88,11 +88,15 @@ void main() { final target = build(); + // The alarm already shows the set, like the page after the rest expect(target.alarm!.at, endsAt); - expect(target.alarm!.title, 'Rest is over'); - expect(target.alarm!.body, 'Next: Bench press 3x100kg'); + expect(target.alarm!.title, 'Bench press'); + expect(target.alarm!.subtitle, 'Rest is over'); + expect(target.alarm!.body, 'Set 2 of 3 · 3x100kg'); expect(target.alarm!.canLogSet, isTrue); expect(target.alarm!.payload.logSlotUuid, logs()[1].uuid); + expect(target.controls!.title, 'Pause'); + expect(target.controls!.body, 'Next: Bench press 3x100kg'); expect(target.controls!.chronometerAt, endsAt); expect(target.controls!.chronometerCountsDown, isTrue); expect(target.controls!.canSkipRest, isTrue); @@ -119,8 +123,12 @@ void main() { final target = build(); expect(target.alarm, isNull); - expect(target.controls!.title, 'Rest is over'); + expect(target.controls!.title, 'Bench press'); + expect(target.controls!.subtitle, 'Rest is over'); + expect(target.controls!.body, 'Set 2 of 3 · 3x100kg'); expect(target.controls!.chronometerAt, isNull); + expect(target.controls!.canLogSet, isTrue); + expect(target.controls!.canSkipRest, isFalse); }); test('A rest that counts up shows the time since its start', () { @@ -141,6 +149,7 @@ void main() { final target = build(); + expect(target.alarm!.title, 'Rest is over'); expect(target.alarm!.body, 'Next: Side raises 12x10kg'); expect(target.alarm!.canLogSet, isFalse); expect(target.controls!.canLogSet, isFalse); @@ -267,15 +276,23 @@ void main() { expect(choices, isEmpty); }); - test('The rest before a set and the set page offer them with "log set"', () { + test('The rest end and the set page offer them with "log set", the rest not', () { final recent = [logOf(repetitions: 9, weight: 60)]; final endsAt = now.add(const Duration(seconds: 90)); onPage(timers().first, restStartedAt: now, restEndsAt: endsAt); var target = build(recentLogs: recent); - expect(target.controls!.quickLogs, ['9 × 60 kg']); + expect(target.controls!.quickLogs, isEmpty); + expect(target.controls!.canLogSet, isFalse); expect(target.alarm!.quickLogs, ['9 × 60 kg']); + onPage( + timers().first, + restStartedAt: now, + restEndsAt: now.subtract(const Duration(seconds: 1)), + ); + expect(build(recentLogs: recent).controls!.quickLogs, ['9 × 60 kg']); + onPage(logs()[1]); target = build(recentLogs: recent); expect(target.controls!.quickLogs, ['9 × 60 kg']); diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index fcbf48605..c2ee5fe20 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -316,11 +316,12 @@ void main() { verify(logRepo.addLocalDrift(captureAny, dayId: anyNamed('dayId'))).captured.single as Log; - test('The notification offers earlier logs of the next set', () async { + test('The rest end offers earlier logs of the next set', () async { await startRest(); - final controls = verify(service.showControls(captureAny, any)).captured; - expect((controls.last as WorkoutControls).quickLogs, ['9 × 60 kg']); + // The rest end shows them, the running rest not + final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; + expect((alarms.last as RestAlarm).quickLogs, ['9 × 60 kg']); }); test('Also when the log page already loaded the earlier logs', () async { @@ -341,8 +342,9 @@ void main() { await startRest(); - final controls = verify(service.showControls(captureAny, any)).captured; - expect((controls.last as WorkoutControls).quickLogs, ['9 × 60 kg']); + // The rest end shows them, the running rest not + final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; + expect((alarms.last as RestAlarm).quickLogs, ['9 × 60 kg']); }); test('A picked quick log arrives through the port and logs its values', () async { diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart index a73a0b603..e5a87e085 100644 --- a/test/features/routines/notifications/workout_notification_service_test.dart +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -172,6 +172,21 @@ void main() { ]); }); + test('The alarm says next to the app name that the rest is over', () async { + await LocalWorkoutNotificationService().scheduleRestAlarm( + RestAlarm( + at: DateTime.now().add(const Duration(minutes: 2)), + title: 'Bench press', + body: 'Set 2 of 3 · 3x100kg', + subtitle: 'Rest is over', + payload: payload, + ), + labels, + ); + + expect(scheduled()['subText'], 'Rest is over'); + }); + group('Log set', () { List inputsOfLogSet(Map details) => ((details['actions'] as List).cast>().singleWhere( From f511d99a517f9c94ca0e1ab0a4ab2a20a1c391a7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 20:53:17 +0100 Subject: [PATCH 23/28] Build the set values in the notification locally These are shorter so they fit in the quick-actions buttons --- .../workout_notification_content.dart | 50 +++++++++++++++---- .../workout_notification_content_test.dart | 36 ++++++++++--- 2 files changed, 68 insertions(+), 18 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index dfe87494f..6adb2b10b 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -249,7 +249,8 @@ const _MAX_QUICK_LOGS = 3; /// The earlier logs of [planned]'s exercise that "log set" offers, by label. /// /// Newest first, one per label, without the planned values. Only plain -/// repetitions: other units have server names that need a BuildContext. +/// repetitions: other units have server names that need a BuildContext. The +/// label leaves out the RiR, so a choice keeps the planned one. Map quickLogChoices(SetConfigData planned, List recentLogs) { // What "log set" logs, with the units resolved final plannedLog = Log.fromSetConfigData(planned); @@ -269,19 +270,29 @@ Map quickLogChoices(SetConfigData planned, List recentLogs) { isPlanned) { continue; } - choices.putIfAbsent(_quickLogLabel(log), () => log); + final label = _valuesLabel( + repetitions: log.repetitions!, + weight: log.weight, + unit: log.weightUnitObj?.name, + ); + choices.putIfAbsent(label, () => log.copyWith()..rir = plannedLog.rir); } return choices; } -String _quickLogLabel(Log log) { - final weight = log.weight; - final unit = log.weightUnitObj?.name; - final rir = log.rir; +/// "8-12 × 60 kg", the upper bounds and the unit if given +String _valuesLabel({ + required num repetitions, + num? maxRepetitions, + num? weight, + num? maxWeight, + String? unit, +}) { + String range(num value, num? max) => + [formatNum(value), if (max != null) formatNum(max)].join('-'); return [ - formatNum(log.repetitions!).toString(), - if (weight != null && weight != 0) ...['×', formatNum(weight).toString(), ?unit], - if (rir != null) '(${formatNum(rir)} RiR)', + range(repetitions, maxRepetitions), + if (weight != null && weight != 0) ...['×', range(weight, maxWeight), ?unit], ].join(' '); } @@ -306,9 +317,26 @@ WorkoutNotificationTarget buildWorkoutNotification( final slotPages = state.pages.expand((p) => p.slotPages).toList(); final current = state.getSlotEntryPageByIndex(); + /// The planned values without RiR and rest, the server text for other units + String values(SetConfigData config) { + final repetitions = config.repetitions; + if (repetitions == null || config.repetitionsUnitId != REP_UNIT_REPETITIONS_ID) { + return config.textRepr; + } + final weight = config.weight; + final label = _valuesLabel( + repetitions: repetitions, + maxRepetitions: config.maxRepetitions, + weight: weight, + maxWeight: config.maxWeight, + unit: config.weightUnit?.name, + ); + return weight == null || weight == 0 ? '$label ${i18n.reps}' : label; + } + String setText(SlotPageEntry page) { final config = page.setConfigData!; - return '${config.exercise.getTranslation(languageCode).name} ${config.textRepr}'; + return '${config.exercise.getTranslation(languageCode).name} ${values(config)}'; } String exerciseName(SlotPageEntry page) => @@ -326,7 +354,7 @@ WorkoutNotificationTarget buildWorkoutNotification( ) .toList(); return '${i18n.workoutNotificationSetOf(sameExercise.indexOf(page) + 1, sameExercise.length)}' - ' · ${page.setConfigData!.textRepr}'; + ' · ${values(page.setConfigData!)}'; } bool canLog(SlotPageEntry page) => diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index 2c3e30d25..283cff805 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -92,11 +92,11 @@ void main() { expect(target.alarm!.at, endsAt); expect(target.alarm!.title, 'Bench press'); expect(target.alarm!.subtitle, 'Rest is over'); - expect(target.alarm!.body, 'Set 2 of 3 · 3x100kg'); + expect(target.alarm!.body, 'Set 2 of 3 · 3 × 100 kg'); expect(target.alarm!.canLogSet, isTrue); expect(target.alarm!.payload.logSlotUuid, logs()[1].uuid); expect(target.controls!.title, 'Pause'); - expect(target.controls!.body, 'Next: Bench press 3x100kg'); + expect(target.controls!.body, 'Next: Bench press 3 × 100 kg'); expect(target.controls!.chronometerAt, endsAt); expect(target.controls!.chronometerCountsDown, isTrue); expect(target.controls!.canSkipRest, isTrue); @@ -125,7 +125,7 @@ void main() { expect(target.alarm, isNull); expect(target.controls!.title, 'Bench press'); expect(target.controls!.subtitle, 'Rest is over'); - expect(target.controls!.body, 'Set 2 of 3 · 3x100kg'); + expect(target.controls!.body, 'Set 2 of 3 · 3 × 100 kg'); expect(target.controls!.chronometerAt, isNull); expect(target.controls!.canLogSet, isTrue); expect(target.controls!.canSkipRest, isFalse); @@ -150,7 +150,7 @@ void main() { final target = build(); expect(target.alarm!.title, 'Rest is over'); - expect(target.alarm!.body, 'Next: Side raises 12x10kg'); + expect(target.alarm!.body, 'Next: Side raises 12 × 10 kg'); expect(target.alarm!.canLogSet, isFalse); expect(target.controls!.canLogSet, isFalse); }); @@ -181,12 +181,29 @@ void main() { final controls = build().controls!; expect(controls.title, 'Bench press'); - expect(controls.body, 'Set 2 of 3 · 3x100kg'); + expect(controls.body, 'Set 2 of 3 · 3 × 100 kg'); expect(controls.canLogSet, isTrue); expect(controls.canSkipRest, isFalse); expect(controls.payload.logSlotUuid, logs()[1].uuid); }); + test('The set shows the planned values without RiR and rest', () { + final config = logs()[1].setConfigData! + ..textRepr = '8-12 × 100-110 kg @ 1.5 RiR 120s rest' + ..maxRepetitions = 12 + ..repetitions = 8 + ..maxWeight = 110; + onPage(logs()[1]); + expect(build().controls!.body, 'Set 2 of 3 · 8-12 × 100-110 kg'); + + config.weight = null; + expect(build().controls!.body, 'Set 2 of 3 · 8-12 Reps'); + + // Other units keep the server text, it has their translated name + config.repetitionsUnitId = testRepetitionUnit2.id; + expect(build().controls!.body, 'Set 2 of 3 · 8-12 × 100-110 kg @ 1.5 RiR 120s rest'); + }); + test('A logged set cannot be logged again', () { notifier.markSlotPageAsDone(logs()[1].uuid, isDone: true); onPage(logs()[1]); @@ -255,14 +272,19 @@ void main() { logOf(repetitions: planned.repetitions!, weight: planned.weight), logOf(repetitions: 9, weight: 60), logOf(repetitions: 8, weight: 62.5, rir: 2), + logOf(repetitions: 8, weight: 62.5, rir: 3), logOf(repetitions: 12), logOf(repetitions: 6, weight: 70), ]; final choices = quickLogChoices(planned, recent); - expect(choices.keys, ['9 × 60 kg', '8 × 62.5 kg (2 RiR)', '12']); - expect(choices['9 × 60 kg'], same(recent[0])); + expect(choices.keys, ['9 × 60 kg', '8 × 62.5 kg', '12']); + expect(choices['8 × 62.5 kg']!.repetitions, 8); + expect(choices['8 × 62.5 kg']!.weight, 62.5); + // The label shows no RiR, so the planned one is logged + expect(choices['8 × 62.5 kg']!.rir, planned.rir); + expect(choices['12']!.rir, planned.rir); }); test('Skips other exercises and units the label cannot name', () { From 9796370600eb4409750f9513d8d90713e72568b8 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 16:43:05 +0100 Subject: [PATCH 24/28] Offer "+30 s" in the iOS rest alarm --- .../workout_notification_service.dart | 19 +++++- .../workout_notification_service_test.dart | 59 +++++++++++++++---- 2 files changed, 67 insertions(+), 11 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 6b4efb006..3b1601d59 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -128,6 +128,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { static const _controlsChannelId = 'workout_controls'; static const _alarmChannelId = 'rest_alarm'; static const _restEndCategory = 'workout_rest_end'; + static const _restEndNoLogCategory = 'workout_rest_end_no_log'; static const _actionTasksChannel = MethodChannel('de.wger.flutter/notification_actions'); final _logger = Logger('LocalWorkoutNotificationService'); @@ -156,6 +157,19 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { WORKOUT_NOTIFICATION_ACTION_LOG_SET, labels.logSet, ), + DarwinNotificationAction.plain( + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + labels.extendRest, + ), + ], + ), + DarwinNotificationCategory( + _restEndNoLogCategory, + actions: [ + DarwinNotificationAction.plain( + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + labels.extendRest, + ), ], ), ], @@ -225,7 +239,10 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { iOS: DarwinNotificationDetails( subtitle: alarm.subtitle, presentSound: true, - categoryIdentifier: alarm.canLogSet ? _restEndCategory : null, + // iOS fixes the actions per category, these are the combinations used + categoryIdentifier: alarm.canLogSet + ? _restEndCategory + : (alarm.canExtendRest ? _restEndNoLogCategory : null), ), ), ); diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart index e5a87e085..1b5b3da55 100644 --- a/test/features/routines/notifications/workout_notification_service_test.dart +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -103,16 +103,21 @@ void main() { (calls.singleWhere((c) => c.method == 'zonedSchedule').arguments as Map)['platformSpecifics'] as Map; - RestAlarm alarm({bool canLogSet = true, List quickLogs = const [], Uri? image}) => - RestAlarm( - at: DateTime.now().add(const Duration(minutes: 2)), - title: 'Rest is over', - body: 'Next: Bench press', - canLogSet: canLogSet, - payload: payload, - quickLogs: quickLogs, - image: image, - ); + RestAlarm alarm({ + bool canLogSet = true, + bool canExtendRest = false, + List quickLogs = const [], + Uri? image, + }) => RestAlarm( + at: DateTime.now().add(const Duration(minutes: 2)), + title: 'Rest is over', + body: 'Next: Bench press', + canLogSet: canLogSet, + canExtendRest: canExtendRest, + payload: payload, + quickLogs: quickLogs, + image: image, + ); Map shown() => (calls.singleWhere((c) => c.method == 'show').arguments as Map)['platformSpecifics'] as Map; @@ -260,4 +265,38 @@ void main() { expect(scheduled()['largeIcon'], isNull); }); }); + + group('iOS', () { + setUp(() { + FlutterLocalNotificationsPlatform.instance = IOSFlutterLocalNotificationsPlugin(); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + }); + + test('The alarm offers "+30 s" next to "Log set", or alone', () async { + final service = LocalWorkoutNotificationService(); + await service.initialize(labels); + final categories = { + for (final c in (calls.single.arguments as Map)['notificationCategories'] as List) + (c as Map)['identifier']: [ + for (final a in c['actions'] as List) (a as Map)['identifier'], + ], + }; + + Future categoryOf(RestAlarm alarm) async { + calls.clear(); + await service.scheduleRestAlarm(alarm, labels); + return scheduled()['categoryIdentifier']; + } + + expect(categories[await categoryOf(alarm(canExtendRest: true))], [ + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + ]); + expect(categories[await categoryOf(alarm(canLogSet: false, canExtendRest: true))], [ + WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, + ]); + expect(await categoryOf(alarm(canLogSet: false)), isNull); + }); + }); } From 6fb1615da14b78258c5972bf9290ef755783826a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 20:28:40 +0100 Subject: [PATCH 25/28] Use the server's short set text in notification If the field is not available, fall back to the regular one, which is a bit longer and includes RiRs, etc. --- .../routines/models/set_config_data.dart | 7 +++ .../routines/models/set_config_data.g.dart | 2 + .../workout_notification_content.dart | 48 +++++-------------- .../routines/models/set_config_data_test.dart | 39 +++++++++++++++ .../workout_notification_content_test.dart | 28 ++++------- 5 files changed, 69 insertions(+), 55 deletions(-) create mode 100644 test/features/routines/models/set_config_data_test.dart diff --git a/lib/features/routines/models/set_config_data.dart b/lib/features/routines/models/set_config_data.dart index ff3696078..5fc175300 100644 --- a/lib/features/routines/models/set_config_data.dart +++ b/lib/features/routines/models/set_config_data.dart @@ -45,6 +45,10 @@ class SetConfigData { String get textReprWithType => '$textRepr${type.typeLabel}'; + /// [textRepr] without sets, RiR and rest, null from older servers + @JsonKey(name: 'text_repr_short') + String? textReprShort; + @JsonKey(required: true, name: 'sets') num? nrOfSets; @@ -120,6 +124,7 @@ class SetConfigData { this.maxRestTime, this.comment = '', this.textRepr = '', + this.textReprShort, Exercise? exercise, WeightUnit? weightUnit, RepetitionUnit? repetitionsUnit, @@ -140,6 +145,7 @@ class SetConfigData { int? slotEntryId, SlotEntryType? type, String? textRepr, + String? textReprShort, num? nrOfSets, num? maxNrOfSets, num? weight, @@ -165,6 +171,7 @@ class SetConfigData { slotEntryId: slotEntryId ?? this.slotEntryId, type: type ?? this.type, textRepr: textRepr ?? this.textRepr, + textReprShort: textReprShort ?? this.textReprShort, nrOfSets: nrOfSets ?? this.nrOfSets, maxNrOfSets: maxNrOfSets ?? this.maxNrOfSets, weight: weight ?? this.weight, diff --git a/lib/features/routines/models/set_config_data.g.dart b/lib/features/routines/models/set_config_data.g.dart index eba87c76a..d02616fc4 100644 --- a/lib/features/routines/models/set_config_data.g.dart +++ b/lib/features/routines/models/set_config_data.g.dart @@ -55,6 +55,7 @@ SetConfigData _$SetConfigDataFromJson(Map json) { maxRestTime: stringToNumNull(json['max_rest'] as String?), comment: json['comment'] as String? ?? '', textRepr: json['text_repr'] as String? ?? '', + textReprShort: json['text_repr_short'] as String?, ); } @@ -63,6 +64,7 @@ Map _$SetConfigDataToJson(SetConfigData instance) => quickLogChoices(SetConfigData planned, List recentLogs) { isPlanned) { continue; } - final label = _valuesLabel( - repetitions: log.repetitions!, - weight: log.weight, - unit: log.weightUnitObj?.name, - ); + final weight = log.weight; + final label = [ + formatNum(log.repetitions!).toString(), + if (weight != null && weight != 0) ...[ + '×', + formatNum(weight).toString(), + ?log.weightUnitObj?.name, + ], + ].join(' '); choices.putIfAbsent(label, () => log.copyWith()..rir = plannedLog.rir); } return choices; } -/// "8-12 × 60 kg", the upper bounds and the unit if given -String _valuesLabel({ - required num repetitions, - num? maxRepetitions, - num? weight, - num? maxWeight, - String? unit, -}) { - String range(num value, num? max) => - [formatNum(value), if (max != null) formatNum(max)].join('-'); - return [ - range(repetitions, maxRepetitions), - if (weight != null && weight != 0) ...['×', range(weight, maxWeight), ?unit], - ].join(' '); -} - /// Derives the workout notifications from [state] at [now]. /// /// [withControls] is whether the ongoing notification is supported and wanted. @@ -317,22 +305,8 @@ WorkoutNotificationTarget buildWorkoutNotification( final slotPages = state.pages.expand((p) => p.slotPages).toList(); final current = state.getSlotEntryPageByIndex(); - /// The planned values without RiR and rest, the server text for other units - String values(SetConfigData config) { - final repetitions = config.repetitions; - if (repetitions == null || config.repetitionsUnitId != REP_UNIT_REPETITIONS_ID) { - return config.textRepr; - } - final weight = config.weight; - final label = _valuesLabel( - repetitions: repetitions, - maxRepetitions: config.maxRepetitions, - weight: weight, - maxWeight: config.maxWeight, - unit: config.weightUnit?.name, - ); - return weight == null || weight == 0 ? '$label ${i18n.reps}' : label; - } + // The rest and RiR in the full text don't fit a notification + String values(SetConfigData config) => config.textReprShort ?? config.textRepr; String setText(SlotPageEntry page) { final config = page.setConfigData!; diff --git a/test/features/routines/models/set_config_data_test.dart b/test/features/routines/models/set_config_data_test.dart new file mode 100644 index 000000000..0954247b2 --- /dev/null +++ b/test/features/routines/models/set_config_data_test.dart @@ -0,0 +1,39 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/features/routines/models/set_config_data.dart'; + +import '../../../fixtures/fixture_reader.dart'; + +void main() { + Map firstSet() { + final days = jsonDecode(fixture('routines/routine_date_sequence_gym.json')) as List; + return Map.from(days.first['slots'][0]['sets'][0] as Map); + } + + test('Reads the short text, older servers send none', () { + final json = firstSet(); + expect(SetConfigData.fromJson(json).textReprShort, isNull); + + json['text_repr_short'] = '10 × 100 kg'; + expect(SetConfigData.fromJson(json).textReprShort, '10 × 100 kg'); + }); +} diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index 283cff805..3453860fb 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -92,11 +92,11 @@ void main() { expect(target.alarm!.at, endsAt); expect(target.alarm!.title, 'Bench press'); expect(target.alarm!.subtitle, 'Rest is over'); - expect(target.alarm!.body, 'Set 2 of 3 · 3 × 100 kg'); + expect(target.alarm!.body, 'Set 2 of 3 · 3x100kg'); expect(target.alarm!.canLogSet, isTrue); expect(target.alarm!.payload.logSlotUuid, logs()[1].uuid); expect(target.controls!.title, 'Pause'); - expect(target.controls!.body, 'Next: Bench press 3 × 100 kg'); + expect(target.controls!.body, 'Next: Bench press 3x100kg'); expect(target.controls!.chronometerAt, endsAt); expect(target.controls!.chronometerCountsDown, isTrue); expect(target.controls!.canSkipRest, isTrue); @@ -125,7 +125,7 @@ void main() { expect(target.alarm, isNull); expect(target.controls!.title, 'Bench press'); expect(target.controls!.subtitle, 'Rest is over'); - expect(target.controls!.body, 'Set 2 of 3 · 3 × 100 kg'); + expect(target.controls!.body, 'Set 2 of 3 · 3x100kg'); expect(target.controls!.chronometerAt, isNull); expect(target.controls!.canLogSet, isTrue); expect(target.controls!.canSkipRest, isFalse); @@ -150,7 +150,7 @@ void main() { final target = build(); expect(target.alarm!.title, 'Rest is over'); - expect(target.alarm!.body, 'Next: Side raises 12 × 10 kg'); + expect(target.alarm!.body, 'Next: Side raises 12x10kg'); expect(target.alarm!.canLogSet, isFalse); expect(target.controls!.canLogSet, isFalse); }); @@ -181,27 +181,19 @@ void main() { final controls = build().controls!; expect(controls.title, 'Bench press'); - expect(controls.body, 'Set 2 of 3 · 3 × 100 kg'); + expect(controls.body, 'Set 2 of 3 · 3x100kg'); expect(controls.canLogSet, isTrue); expect(controls.canSkipRest, isFalse); expect(controls.payload.logSlotUuid, logs()[1].uuid); }); - test('The set shows the planned values without RiR and rest', () { - final config = logs()[1].setConfigData! - ..textRepr = '8-12 × 100-110 kg @ 1.5 RiR 120s rest' - ..maxRepetitions = 12 - ..repetitions = 8 - ..maxWeight = 110; + test('The short server text when there is one, without the rest time', () { + logs()[1].setConfigData!.textReprShort = '3 × 100 kg'; onPage(logs()[1]); - expect(build().controls!.body, 'Set 2 of 3 · 8-12 × 100-110 kg'); + expect(build().controls!.body, 'Set 2 of 3 · 3 × 100 kg'); - config.weight = null; - expect(build().controls!.body, 'Set 2 of 3 · 8-12 Reps'); - - // Other units keep the server text, it has their translated name - config.repetitionsUnitId = testRepetitionUnit2.id; - expect(build().controls!.body, 'Set 2 of 3 · 8-12 × 100-110 kg @ 1.5 RiR 120s rest'); + onPage(timers()[0], restStartedAt: now, restEndsAt: now.add(const Duration(minutes: 2))); + expect(build().controls!.body, 'Next: Bench press 3 × 100 kg'); }); test('A logged set cannot be logged again', () { From 746628db1438afc3a1e7ed9926c89d13c7e94582 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 30 Oct 2026 16:05:27 +0100 Subject: [PATCH 26/28] Skip the notification setup on platforms without notifications --- .../workout_notification_controller.dart | 5 +++++ .../workout_notification_controller_test.dart | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index cc1ab02cc..233be415c 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -246,6 +246,11 @@ const _backgroundStates = { final workoutNotificationControllerProvider = Provider((ref) { final service = ref.read(workoutNotificationServiceProvider); final controller = WorkoutNotificationController(ref, service); + + // Nothing to keep in line, and the web has no isolates for the actions + if (service is NoopWorkoutNotificationService) { + return controller; + } unawaited(service.initialize(controller.labels)); // Actions arrive from the background isolate diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index a762f2062..b8668bef7 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -240,6 +240,19 @@ void main() { verify(service.cancelAll()).called(1); }); + + test('Platforms without notifications set nothing up, the web has no isolates', () { + IsolateNameServer.removePortNameMapping(WORKOUT_NOTIFICATION_PORT); + final noop = ProviderContainer.test( + overrides: [ + workoutNotificationServiceProvider.overrideWithValue(NoopWorkoutNotificationService()), + ], + ); + + noop.read(workoutNotificationControllerProvider); + + expect(IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT), isNull); + }); }); group('Actions', () { From 18eb5f55ad63c0bd4483bbbee6103f2f62b83853 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 30 Oct 2026 16:11:24 +0100 Subject: [PATCH 27/28] Ask for the notification permission when switching a notification on --- .../routines/widgets/gym_mode/start_page.dart | 22 ++++++++++++-- .../widgets/gym_mode/start_page_test.dart | 29 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 7cc5fe926..deb26dd52 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -16,12 +16,15 @@ * along with this program. If not, see . */ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/exercises/widgets/images.dart'; import 'package:wger/features/routines/models/day.dart'; +import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; @@ -55,6 +58,15 @@ class _GymModeOptionsState extends ConsumerState { super.dispose(); } + /// Gym mode only asks on opening if a notification is on, so switching one + /// on later has to ask as well + void _requestPermissionsIfOn(bool value) { + if (value) { + final labels = WorkoutNotificationLabels.of(AppLocalizations.of(context)); + unawaited(ref.read(workoutNotificationServiceProvider).requestPermissions(labels)); + } + } + @override Widget build(BuildContext context) { final gymState = ref.watch(gymStateProvider); @@ -177,7 +189,10 @@ class _GymModeOptionsState extends ConsumerState { subtitle: Text(i18n.gymModeAlertOnRestEndHelp), value: gymState.alertOnCountdownEnd, onChanged: gymState.showTimerPages - ? (value) => gymNotifier.setAlertOnCountdownEnd(value) + ? (value) { + gymNotifier.setAlertOnCountdownEnd(value); + _requestPermissionsIfOn(value); + } : null, ), // Android delays alarms without the exact alarm permission @@ -206,7 +221,10 @@ class _GymModeOptionsState extends ConsumerState { title: Text(i18n.gymModeWorkoutNotification), subtitle: Text(i18n.gymModeWorkoutNotificationHelp), value: gymState.showWorkoutNotification, - onChanged: (value) => gymNotifier.setShowWorkoutNotification(value), + onChanged: (value) { + gymNotifier.setShowWorkoutNotification(value); + _requestPermissionsIfOn(value); + }, ), const Divider(), diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index 39151fa66..23c7dc793 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -166,6 +166,35 @@ void main() { expect(notifier.state.alertOnCountdownEnd, isFalse); }); + testWidgets('Switching a notification on asks for the permission, off does not', (tester) async { + // Gym mode was opened with both off, so it did not ask then + when(notificationService.requestPermissions(any)).thenAnswer((_) async {}); + final notifier = container.read(gymStateProvider.notifier); + notifier.setAlertOnCountdownEnd(false); + notifier.setShowWorkoutNotification(false); + await pumpGymModeOptions(tester); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + + for (final key in ['gym-mode-notify-countdown', 'gym-mode-workout-notification']) { + final toggle = find.byKey(ValueKey(key)); + await tester.ensureVisible(toggle); + await tester.tap(toggle); + await tester.pump(); + } + verify(notificationService.requestPermissions(any)).called(2); + + for (final key in ['gym-mode-notify-countdown', 'gym-mode-workout-notification']) { + final toggle = find.byKey(ValueKey(key)); + await tester.ensureVisible(toggle); + await tester.tap(toggle); + await tester.pump(); + } + verifyNever(notificationService.requestPermissions(any)); + expect(notifier.state.alertOnCountdownEnd, isFalse); + expect(notifier.state.showWorkoutNotification, isFalse); + }); + testWidgets('The workout notification switch only shows on Android', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); From ca698e5bf4c94dd1ed500b75ac0d5171ffe36ad7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 30 Oct 2026 16:18:43 +0100 Subject: [PATCH 28/28] Switch the workout notification at the rest end with the alert off --- .../workout_notification_content.dart | 11 ++++++-- .../workout_notification_service.dart | 19 +++++++++----- .../workout_notification_content_test.dart | 19 +++++++++++--- .../workout_notification_controller_test.dart | 7 ++++-- .../workout_notification_service_test.dart | 25 +++++++++++++++++++ 5 files changed, 67 insertions(+), 14 deletions(-) diff --git a/lib/features/routines/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index 23057f151..07be13b58 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -161,6 +161,9 @@ class RestAlarm extends Equatable { final List quickLogs; final Uri? image; + /// Without sound, only to switch the controls to the rest end + final bool silent; + const RestAlarm({ required this.at, required this.title, @@ -171,6 +174,7 @@ class RestAlarm extends Equatable { this.canExtendRest = false, this.quickLogs = const [], this.image, + this.silent = false, }); @override @@ -184,6 +188,7 @@ class RestAlarm extends Equatable { payload, quickLogs, image, + silent, ]; } @@ -367,8 +372,9 @@ WorkoutNotificationTarget buildWorkoutNotification( final restRunning = endsAt != null && endsAt.isAfter(now); // Once the rest is over the notification shows the set, like the page - // after the rest. Logging during the rest is left to the set itself. - final alarm = state.alertOnCountdownEnd && restRunning + // after the rest. Logging during the rest is left to the set itself. With + // the alert off the controls still switch over, silently. + final alarm = restRunning && (state.alertOnCountdownEnd || withControls) ? RestAlarm( at: endsAt, title: next == null ? i18n.workoutNotificationRestOver : exerciseName(next), @@ -380,6 +386,7 @@ WorkoutNotificationTarget buildWorkoutNotification( payload: actionPayload, quickLogs: next == null ? const [] : quickLogs(next), image: image(next ?? following), + silent: !state.alertOnCountdownEnd, ) : null; diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 3b1601d59..db9e95774 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -222,11 +222,18 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { : AndroidScheduleMode.inexactAllowWhileIdle, notificationDetails: NotificationDetails( android: AndroidNotificationDetails( - _alarmChannelId, - labels.alarmChannel, - importance: Importance.high, - priority: Priority.high, - category: AndroidNotificationCategory.alarm, + alarm.silent ? _controlsChannelId : _alarmChannelId, + alarm.silent ? labels.controlsChannel : labels.alarmChannel, + importance: alarm.silent ? Importance.low : Importance.high, + priority: alarm.silent ? Priority.low : Priority.high, + // A silent one stands in for the controls, so it stays like them + ongoing: alarm.silent, + autoCancel: !alarm.silent, + playSound: !alarm.silent, + enableVibration: !alarm.silent, + category: alarm.silent + ? AndroidNotificationCategory.workout + : AndroidNotificationCategory.alarm, visibility: NotificationVisibility.public, subText: alarm.subtitle, largeIcon: await _cachedImage(alarm.image), @@ -238,7 +245,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { ), iOS: DarwinNotificationDetails( subtitle: alarm.subtitle, - presentSound: true, + presentSound: !alarm.silent, // iOS fixes the actions per category, these are the combinations used categoryIdentifier: alarm.canLogSet ? _restEndCategory diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index 0f064049d..f28a8a1ec 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -110,14 +110,25 @@ void main() { expect(target.controls!.payload.restSlotKey, timer.key); }); - test('No alarm when the setting is off', () { + test('With the alert off the controls still switch at the rest end, silently', () { notifier.state = notifier.state.copyWith(alertOnCountdownEnd: false); - onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + final endsAt = now.add(const Duration(seconds: 90)); + onPage(timers().first, restStartedAt: now, restEndsAt: endsAt); final target = build(); - - expect(target.alarm, isNull); + expect(target.alarm!.silent, isTrue); + expect(target.alarm!.at, endsAt); + expect(target.alarm!.body, 'Set 2 of 3 · 3x100kg'); expect(target.controls, isNotNull); + + // Without controls there is nothing to switch + expect(build(withControls: false), WorkoutNotificationTarget.none); + }); + + test('With the alert on the alarm is not silent', () { + onPage(timers().first, restStartedAt: now, restEndsAt: now.add(const Duration(seconds: 90))); + + expect(build().alarm!.silent, isFalse); }); test('A rest that is already over has no alarm and no chronometer', () { diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index b8668bef7..73d20d5f6 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -194,7 +194,9 @@ void main() { initGymMode(); gymState.state = gymState.state.copyWith(alertOnCountdownEnd: false); await startRest(); - verifyNever(service.scheduleRestAlarm(any, any)); + // Only the silent switch of the controls at the rest end + final silent = verify(service.scheduleRestAlarm(captureAny, any)).captured.single as RestAlarm; + expect(silent.silent, isTrue); verify(service.showControls(any, any)); clearInteractions(service); @@ -205,7 +207,8 @@ void main() { ); await settle(); }); - verify(service.scheduleRestAlarm(any, any)).called(1); + final alarm = verify(service.scheduleRestAlarm(captureAny, any)).captured.single as RestAlarm; + expect(alarm.silent, isFalse); verifyNever(service.showControls(any, any)); }); diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart index 1b5b3da55..71524d913 100644 --- a/test/features/routines/notifications/workout_notification_service_test.dart +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -177,6 +177,31 @@ void main() { ]); }); + test('A silent alarm stands in for the controls, without sound', () async { + final service = LocalWorkoutNotificationService(); + + await service.scheduleRestAlarm(alarm(), labels); + expect(scheduled()['channelId'], 'rest_alarm'); + expect(scheduled()['playSound'], isTrue); + + calls.clear(); + await service.scheduleRestAlarm( + RestAlarm( + at: DateTime.now().add(const Duration(minutes: 2)), + title: 'Bench press', + body: 'Set 2 of 3 · 3x100kg', + payload: payload, + silent: true, + ), + labels, + ); + expect(scheduled()['channelId'], 'workout_controls'); + expect(scheduled()['playSound'], isFalse); + expect(scheduled()['enableVibration'], isFalse); + expect(scheduled()['ongoing'], isTrue); + expect(scheduled()['autoCancel'], isFalse); + }); + test('The alarm says next to the app name that the rest is over', () async { await LocalWorkoutNotificationService().scheduleRestAlarm( RestAlarm(