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..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/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index fa82d5621..758e0a42a 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -1,5 +1,6 @@ import Flutter import UIKit +import flutter_local_notifications private final class StorageExclusionPlugin: NSObject, FlutterPlugin { static let pluginName = "StorageExclusionPlugin" @@ -49,17 +50,83 @@ 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( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> 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 + override func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void + ) { + NotificationActionTasks.begin() + 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) + 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/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/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) => . + * 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/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; + final int dayId; + final int iteration; + final DateTime workoutStart; + + /// The log page the "log set" action logs + final String? logSlotKey; + + /// The timer page the "skip rest" action leaves + final String? restSlotKey; + + const WorkoutNotificationPayload({ + required this.routineId, + required this.dayId, + required this.iteration, + required this.workoutStart, + this.logSlotKey, + this.restSlotKey, + }); + + /// 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, + 'iteration': iteration, + 'workoutStart': workoutStart.toUtc().toIso8601String(), + 'logSlotKey': logSlotKey, + 'restSlotKey': restSlotKey, + }); + + /// 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), + logSlotKey: json['logSlotKey'] as String?, + restSlotKey: json['restSlotKey'] as String?, + ); + } on Object { + return null; + } + } + + @override + List get props => [routineId, dayId, iteration, workoutStart, logSlotKey, restSlotKey]; +} + +/// The ongoing notification while a workout runs (Android) +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; + + 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, + required this.payload, + this.subtitle, + this.chronometerAt, + this.chronometerCountsDown = false, + this.canLogSet = false, + this.canSkipRest = false, + this.canExtendRest = false, + this.quickLogs = const [], + this.image, + }); + + @override + List get props => [ + title, + body, + subtitle, + chronometerAt, + chronometerCountsDown, + canLogSet, + canSkipRest, + canExtendRest, + payload, + quickLogs, + image, + ]; +} + +/// The notification that fires when the rest is over +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; + + /// See [WorkoutControls.quickLogs] + 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, + required this.body, + required this.payload, + this.subtitle, + this.canLogSet = false, + this.canExtendRest = false, + this.quickLogs = const [], + this.image, + this.silent = false, + }); + + @override + List get props => [ + at, + title, + body, + subtitle, + canLogSet, + canExtendRest, + payload, + quickLogs, + image, + silent, + ]; +} + +/// 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; + final String notLoggedBody; + + const WorkoutNotificationLabels({ + required this.logSet, + required this.skipRest, + required this.extendRest, + required this.controlsChannel, + required this.alarmChannel, + required this.notLoggedTitle, + required this.notLoggedBody, + }); + + 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, + notLoggedBody = i18n.workoutNotificationNotLoggedBody; + + @override + List get props => [ + logSet, + skipRest, + extendRest, + controlsChannel, + alarmChannel, + notLoggedTitle, + notLoggedBody, + ]; +} + +/// 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]; +} + +/// 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. 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); + 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; + } + 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; +} + +/// 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; + } + + final slotPages = state.pages.expand((p) => p.slotPages).toList(); + final current = state.getSlotEntryPageByIndex(); + + // 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!; + return '${config.exercise.getTranslation(languageCode).name} ${values(config)}'; + } + + 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)}' + ' · ${values(page.setConfigData!)}'; + } + + bool canLog(SlotPageEntry page) => + !state.progressOf(page.key).done && + isWorkoutLogComplete( + repetitions: page.setConfigData!.repetitions, + weight: page.setConfigData!.weight, + ); + + List quickLogs(SlotPageEntry page) => + canLog(page) ? quickLogChoices(page.setConfigData!, recentLogs).keys.toList() : const []; + + Uri? image(SlotPageEntry? page) => + page == null ? null : mediaUrl?.call(page.setConfigData!.exercise.getMainImage?.image); + + WorkoutNotificationPayload payload({String? logSlotKey, String? restSlotKey}) => + WorkoutNotificationPayload( + routineId: state.routine.id!, + dayId: state.dayId, + iteration: state.iteration, + workoutStart: state.workoutStart, + logSlotKey: logSlotKey, + restSlotKey: restSlotKey, + ); + + if (current?.type == SlotPageType.timer) { + final following = slotPages.firstWhereOrNull( + (p) => p.type == SlotPageType.log && p.pageIndex > current!.pageIndex, + ); + // 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(logSlotKey: next?.key, restSlotKey: current.key); + + 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. 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), + 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: next == null ? const [] : quickLogs(next), + image: image(next ?? following), + silent: !state.alertOnCountdownEnd, + ) + : 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); + } + + if (!withControls) { + return WorkoutNotificationTarget.none; + } + + if (current?.type == SlotPageType.log) { + return WorkoutNotificationTarget( + controls: WorkoutControls( + title: exerciseName(current!), + body: setOf(current), + canLogSet: canLog(current), + payload: payload(logSlotKey: current.key), + quickLogs: quickLogs(current), + image: image(current), + ), + ); + } + + 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..233be415c --- /dev/null +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -0,0 +1,291 @@ +/* + * 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:isolate'; +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/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 +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 gym state and carries +/// out what the user does with them +class WorkoutNotificationController { + final _logger = Logger('WorkoutNotificationController'); + final Ref _ref; + final WorkoutNotificationService _service; + + /// What the platform shows, null if unknown + 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 + 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((_) => 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); + + // 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 + : 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 key = target.controls?.payload.logSlotKey; + final exerciseId = key == null ? null : state.getSlotPageByKey(key)?.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 + /// 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; + } + _shown = target; + + // Alarm and controls share one notification, so every change starts over + 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; + } + } + + /// Carries out a notification action. Stale actions only refresh the + /// notification, without a running session the user is sent to the app. + /// [input] is the quick log the user picked, if any. + Future handleAction(String? actionId, String? encodedPayload, [String? input]) async { + try { + await _handleAction(actionId, encodedPayload, input); + } 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, String? input) 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 key = payload.logSlotKey; + final config = key == null ? null : state.getSlotPageByKey(key)?.setConfigData; + if (config == null) { + break; + } + if (input == null) { + await notifier.logPlannedSet(key!); + } else { + // An unknown label is from an outdated notification + final valuesFrom = quickLogChoices(config, _recentLogs)[input]; + if (valuesFrom != null) { + await notifier.logPlannedSet(key!, valuesFrom: valuesFrom); + } + } + case WORKOUT_NOTIFICATION_ACTION_SKIP_REST: + if (state.getSlotEntryPageByIndex()?.key == payload.restSlotKey) { + notifier.skipRest(); + } + case WORKOUT_NOTIFICATION_ACTION_EXTEND_REST: + if (state.getSlotEntryPageByIndex()?.key == payload.restSlotKey) { + notifier.extendRest(REST_EXTENSION); + } + } + } catch (e) { + _logger.warning('Notification action $actionId failed: $e'); + } + } + + // The platform removes the notification on an action + refresh(); + } +} + +const _backgroundStates = { + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.detached, +}; + +/// Bootstraps the workout notifications, read once at app start +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 + final port = ReceivePort(); + IsolateNameServer.removePortNameMapping(WORKOUT_NOTIFICATION_PORT); + IsolateNameServer.registerPortWithName(port.sendPort, WORKOUT_NOTIFICATION_PORT); + port.listen((message) { + final [actionId, payload, input] = message as List; + unawaited(controller.handleAction(actionId as String?, payload as String?, input as String?)); + }); + + // 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(); + } + } + + 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 new file mode 100644 index 000000000..db9e95774 --- /dev/null +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -0,0 +1,383 @@ +/* + * 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:ui'; + +import 'package:extended_image/extended_image.dart'; +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'; +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'; +const WORKOUT_NOTIFICATION_ACTION_EXTEND_REST = 'extend_rest'; + +/// The main isolate receives notification actions on this port +const WORKOUT_NOTIFICATION_PORT = 'wger_workout_actions'; + +/// 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, response.input]); + 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 +/// replaces the controls in place when it fires. +abstract class WorkoutNotificationService { + /// Whether the platform has the ongoing controls notification + bool get supportsControls; + + /// Registers the actions, before anything else is shown + Future initialize(WorkoutNotificationLabels labels); + + 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); + + /// 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(); + + /// Lets the platform suspend the app again after an action + Future actionHandled(); +} + +/// For platforms without workout notifications +class NoopWorkoutNotificationService implements WorkoutNotificationService { + @override + bool get supportsControls => false; + + @override + Future initialize(WorkoutNotificationLabels labels) async {} + + @override + Future requestPermissions(WorkoutNotificationLabels labels) async {} + + @override + Future canScheduleExactAlarms() async => true; + + @override + Future requestExactAlarms() async {} + + @override + Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async {} + + @override + Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels) async {} + + @override + Future showNotLogged(WorkoutNotificationLabels labels) async {} + + @override + Future cancelAll() async {} + + @override + Future actionHandled() 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'; + static const _restEndNoLogCategory = 'workout_rest_end_no_log'; + static const _actionTasksChannel = MethodChannel('de.wger.flutter/notification_actions'); + + final _logger = Logger('LocalWorkoutNotificationService'); + final _plugin = FlutterLocalNotificationsPlugin(); + Future? _initialized; + + @override + bool get supportsControls => defaultTargetPlatform == TargetPlatform.android; + + @override + Future initialize(WorkoutNotificationLabels labels) { + // The iOS action labels are registered once, with the first labels seen + return _initialized ??= _plugin + .initialize( + settings: InitializationSettings( + android: const AndroidInitializationSettings('ic_stat_wger'), + iOS: DarwinInitializationSettings( + requestAlertPermission: false, + requestBadgePermission: false, + requestSoundPermission: false, + notificationCategories: [ + DarwinNotificationCategory( + _restEndCategory, + actions: [ + DarwinNotificationAction.plain( + 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, + ), + ], + ), + ], + ), + ), + onDidReceiveBackgroundNotificationResponse: workoutNotificationBackgroundHandler, + ) + .then((_) {}); + } + + Future _ensureInitialized(WorkoutNotificationLabels labels) => + _initialized ?? initialize(labels); + + @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'); + } + + 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: exact + ? AndroidScheduleMode.exactAllowWhileIdle + : AndroidScheduleMode.inexactAllowWhileIdle, + notificationDetails: NotificationDetails( + android: AndroidNotificationDetails( + 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), + actions: [ + if (alarm.canExtendRest) + AndroidNotificationAction(WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, labels.extendRest), + if (alarm.canLogSet) _logSetAction(alarm.quickLogs, labels), + ], + ), + iOS: DarwinNotificationDetails( + subtitle: alarm.subtitle, + presentSound: !alarm.silent, + // iOS fixes the actions per category, these are the combinations used + categoryIdentifier: alarm.canLogSet + ? _restEndCategory + : (alarm.canExtendRest ? _restEndNoLogCategory : 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, + subText: controls.subtitle, + showWhen: chronometerAt != null, + 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.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); + 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 { + // 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); + } + + @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 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 && + (defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS)) { + return LocalWorkoutNotificationService(); + } + return NoopWorkoutNotificationService(); +}); diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index ef5b5c9ac..8c6766f7c 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -35,6 +35,7 @@ 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_WORKOUT_NOTIFICATION = 'workoutNotificationPrefs'; const PREFS_STICKY_SET_VALUES = 'stickySetValuesPrefs'; /// In seconds @@ -170,6 +171,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; @@ -177,6 +181,9 @@ class GymModeState { final bool showDistinctLogs; final bool showWorkoutDuration; + /// Ongoing notification with the rest and the next set (Android) + final bool showWorkoutNotification; + /// Whether the log form of a set is pre-filled with the values last /// logged for the same exercise, in this or an earlier workout, instead /// of the planned ones. Disabled by default. @@ -207,6 +214,7 @@ class GymModeState { this.logScopeWeeks, this.showDistinctLogs = true, this.showWorkoutDuration = true, + this.showWorkoutNotification = true, this.stickySetValues = false, this.progress = const {}, this.addedExercises = const [], @@ -254,6 +262,7 @@ class GymModeState { bool clearLogScopeWeeks = false, bool? showDistinctLogs, bool? showWorkoutDuration, + bool? showWorkoutNotification, bool? stickySetValues, Map? progress, List? addedExercises, @@ -279,6 +288,7 @@ class GymModeState { logScopeWeeks: clearLogScopeWeeks ? null : (logScopeWeeks ?? this.logScopeWeeks), showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, + showWorkoutNotification: showWorkoutNotification ?? this.showWorkoutNotification, stickySetValues: stickySetValues ?? this.stickySetValues, progress: progress ?? this.progress, addedExercises: addedExercises ?? this.addedExercises, @@ -295,6 +305,31 @@ 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; + } + + /// When the rest on the current timer page started, null on other pages + DateTime? get restStartedAt { + final slotPage = getSlotEntryPageByIndex(); + return slotPage?.type == SlotPageType.timer ? progressOf(slotPage!.key).timerStartedAt : null; + } + + /// When the countdown on the current timer page ends, null if it counts up + DateTime? get restEndsAt { + final startedAt = restStartedAt; + if (startedAt == null) { + return null; + } + final duration = restDurationFor(getSlotEntryPageByIndex()!); + return duration == null ? null : startedAt.add(duration); + } + int get totalPages { // Main pages (start, session, etc.) var count = pages.where((p) => p.type != PageType.set).length; @@ -398,6 +433,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 29d6a71a2..a45348275 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -36,7 +36,9 @@ import 'package:wger/features/routines/models/workout_progress.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/providers/workout_logs_repository.dart'; +import 'package:wger/features/routines/validators.dart'; part 'gym_state_notifier.g.dart'; @@ -102,6 +104,11 @@ class GymStateNotifier extends _$GymStateNotifier { state = state.copyWith(stickySetValues: stickySetValues); } + 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 ' @@ -111,7 +118,8 @@ class GymStateNotifier extends _$GymStateNotifier { 'defaultCountdownDurationSeconds=$defaultCountdownDurationSeconds' 'logScopeWeeks=$logScopeWeeks ' 'showDistinctLogs=$showDistinctLogs ' - 'showWorkoutDuration=$showWorkoutDuration ', + 'showWorkoutDuration=$showWorkoutDuration ' + 'workoutNotification=$workoutNotification ', ); } @@ -133,6 +141,7 @@ 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_STICKY_SET_VALUES, state.stickySetValues); + await prefs.setBool(PREFS_WORKOUT_NOTIFICATION, state.showWorkoutNotification); _logger.finer( 'Saved preferences: ' @@ -143,7 +152,8 @@ class GymStateNotifier extends _$GymStateNotifier { 'defaultCountdownDuration=${state.countdownDuration.inSeconds}' 'logScopeWeeks=${state.logScopeWeeks} ' 'showDistinctLogs=${state.showDistinctLogs} ' - 'showWorkoutDuration=${state.showWorkoutDuration} ', + 'showWorkoutDuration=${state.showWorkoutDuration} ' + 'workoutNotification=${state.showWorkoutNotification} ', ); } @@ -466,6 +476,13 @@ class GymStateNotifier extends _$GymStateNotifier { // form with the saved entry (keeping its id and session) so saving // updates the row instead of inserting a duplicate. final slotPage = state.getSlotEntryPageByIndex(); + + // Not only from the timer widget, the notifications need the rest while + // the app draws no frames in the background + if (slotPage?.type == SlotPageType.timer) { + startTimerIfNeeded(slotPage!.key); + } + final loggedEntry = slotPage == null ? null : state.progressOf(slotPage.key).loggedEntry; if (loggedEntry != null) { ref.read(gymLogProvider.notifier).editLog(loggedEntry); @@ -484,12 +501,7 @@ class GymStateNotifier extends _$GymStateNotifier { return; } - final log = Log.fromSetConfigData( - slotEntryPage.setConfigData!, - routineId: state.routine.id, - iteration: state.iteration, - ); - final logNotifier = ref.read(gymLogProvider.notifier)..setLog(log); + final logNotifier = ref.read(gymLogProvider.notifier)..setLog(_draftFor(slotEntryPage)); if (!state.stickySetValues) { return; } @@ -508,6 +520,102 @@ class GymStateNotifier extends _$GymStateNotifier { } } + /// 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); + } + + /// 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 slotPage = state.getSlotEntryPageByIndex(); + final endsAt = state.restEndsAt; + if (slotPage == null || endsAt == null) { + return; + } + final now = clock.now(); + final newEnd = (endsAt.isAfter(now) ? endsAt : now).add(extra); + + // The rest is stored by its start, so the start moves along with the end + final startedAt = newEnd.subtract(state.restDurationFor(slotPage)!); + _updateProgress(slotPage.key, (p) => p.copyWith(timerStartedAt: startedAt)); + } + + /// Saves the log draft of the current log page, a new set or a correction, + /// 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 + final wasDone = state.progressOf(slotPage.key).done; + _updateProgress(slotPage.key, (p) => p.copyWith(done: true)); + try { + final logs = ref.read(workoutLogProvider); + if (log.id == null) { + await logs.addEntry(log, dayId: state.dayId); + } else { + await logs.updateEntry(log); + } + } catch (_) { + _updateProgress(slotPage.key, (p) => p.copyWith(done: wasDone)); + rethrow; + } + markSlotPageAsDone(slotPage.key, isDone: true, log: log); + + // 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 [slotPageKey] 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, in both cases the values of + /// [valuesFrom] if given. False if stale, done or incomplete. + Future logPlannedSet(String slotPageKey, {Log? valuesFrom}) async { + final target = state.getSlotPageByKey(slotPageKey); + if (target == null || target.type != SlotPageType.log || state.progressOf(target.key).done) { + 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 = valuesFrom ?? (onTarget ? ref.read(gymLogProvider) : _draftFor(target)); + if (log == null || !isWorkoutLogComplete(repetitions: log.repetitions, weight: log.weight)) { + return false; + } + + if (onRestBefore) { + setCurrentPage(target.pageIndex); + } + if (valuesFrom != null) { + ref.read(gymLogProvider.notifier).copyValuesFrom(valuesFrom); + } + await logCurrentSet(); + return true; + } + void setShowExercisePages(bool value) { state = state.copyWith(showExercisePages: value); calculatePages(); @@ -556,6 +664,11 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } + void setShowWorkoutNotification(bool value) { + state = state.copyWith(showWorkoutNotification: value); + _savePrefs(); + } + /// Applies [update] to the progress of the page with [key] void _updateProgress(String key, PageProgress Function(PageProgress) update) { state = state.copyWith(progress: {...state.progress, key: update(state.progressOf(key))}); 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/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 653474649..908c72e0d 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -23,14 +23,19 @@ 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'; 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'; @@ -53,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(); } @@ -74,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; @@ -98,9 +109,26 @@ class _GymModeState extends ConsumerState { fallbackLog: 'Server unreachable, starting from the local routine', ); - return ref + final initialPage = await ref .read(gymStateProvider.notifier) .open(routine, widget._args.dayId, widget._args.iteration); + _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.alertOnCountdownEnd || + (service.supportsControls && gymState.showWorkoutNotification); + if (wanted && mounted) { + unawaited( + service.requestPermissions(WorkoutNotificationLabels.of(AppLocalizations.of(context))), + ); + } } List _getContent(GymModeState state) { @@ -121,16 +149,11 @@ class _GymModeState extends ConsumerState { out.add(LogPage(_controller, slotPage.key)); } - // 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(), - slotPage.key, - ) + rest != null + ? TimerCountdownWidget(_controller, rest.inSeconds, slotPage.key) : TimerWidget(_controller, slotPage.key), ); } @@ -144,8 +167,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 412b1b4e6..1e1f344df 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'; @@ -186,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: [ @@ -294,7 +294,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 @@ -395,35 +394,21 @@ 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. - // - // Re-saving a page that was already logged in this workout - // updates the existing row instead of inserting a duplicate. - if (isNewEntry) { - await logProvider.addEntry(log, dayId: gymState.dayId); - } else { - await logProvider.updateEntry(log); - } + // error handler; the success path below is then skipped. A page + // logged before updates its row, and the PageView follows the + // page change from the gym state. + await ref.read(gymStateProvider.notifier).logCurrentSet(); if (!context.mounted) { return; } - gymProvider.markSlotPageAsDone(page.key, isDone: true, log: log); showSnackbar( context, i18n.successfullySaved, 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/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 3d316aebd..deb26dd52 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -16,18 +16,26 @@ * 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'; 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(); @@ -50,10 +58,20 @@ 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); 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 @@ -62,164 +80,208 @@ 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, - ), - - 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)), + // 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.gymModeAlertOnRestEnd), + subtitle: Text(i18n.gymModeAlertOnRestEndHelp), + value: gymState.alertOnCountdownEnd, + onChanged: gymState.showTimerPages + ? (value) { + gymNotifier.setAlertOnCountdownEnd(value); + _requestPermissionsIfOn(value); + } + : null, + ), + // Android delays alarms without the exact alarm permission + if (isAndroid && + gymState.showTimerPages && + gymState.alertOnCountdownEnd && + 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); + _requestPermissionsIfOn(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-sticky-set-values'), + title: Text(i18n.gymModeStickySetValues), + subtitle: Text(i18n.gymModeStickySetValuesHelp), + value: gymState.stickySetValues, + onChanged: (value) => gymNotifier.setStickySetValues(value), + ), + ], ), - 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-sticky-set-values'), - title: Text(i18n.gymModeStickySetValues), - subtitle: Text(i18n.gymModeStickySetValuesHelp), - value: gymState.stickySetValues, - onChanged: (value) => gymNotifier.setStickySetValues(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), + ), + ], + ), ); } } @@ -241,50 +303,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 f647a3332..5b834de16 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -128,7 +128,9 @@ class TimerCountdownWidget extends ConsumerStatefulWidget { class _TimerCountdownWidgetState extends ConsumerState { late Timer _uiTimer; - bool _hasNotified = false; + /// The end the alert was played for, so each rest (also an extended one) + /// alerts once + DateTime? _alertedFor; /// The moment the countdown ends. The start time lives in the gym state so /// the countdown continues when the page is disposed and re-created while @@ -144,7 +146,8 @@ class _TimerCountdownWidgetState extends ConsumerState { // Don't notify when returning to a countdown that already expired while // the user was on another page. Set before the first build, which notifies. - _hasNotified = _endTime(ref.read(gymStateProvider)).isBefore(clock.now()); + final endTime = _endTime(ref.read(gymStateProvider)); + _alertedFor = endTime.isBefore(clock.now()) ? endTime : null; // Deferred because a provider can't be modified during the widget // life-cycle. @@ -171,21 +174,22 @@ class _TimerCountdownWidgetState extends ConsumerState { @override Widget build(BuildContext context) { final gymState = ref.watch(gymStateProvider); - final remaining = _endTime(gymState).difference(clock.now()); + final endTime = _endTime(gymState); + final remaining = endTime.difference(clock.now()); final remainingSeconds = remaining.inSeconds <= 0 ? 0 : remaining.inSeconds; final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds)); // When countdown finishes, notify ONCE, and respect settings - if (remainingSeconds == 0 && !_hasNotified) { + if (remainingSeconds == 0 && _alertedFor != endTime) { + _alertedFor = endTime; 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); } - setState(() { - _hasNotified = true; - }); } return Column( 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 98aedeaed..2453a5e92 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": { @@ -1178,6 +1177,23 @@ "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", + "gymModeAlertOnRestEnd": "Am Pausenende benachrichtigen", + "gymModeAlertOnRestEndHelp": "Vibriert im Studiomodus oder schickt eine Benachrichtigung, wenn die App im Hintergrund ist", + "gymModeWorkoutNotification": "Trainings-Benachrichtigung", + "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", + "workoutNotificationNext": "Als Nächstes: {set}", + "workoutNotificationSetOf": "Satz {current} von {total}", + "workoutNotificationInProgress": "Training läuft", + "workoutNotificationLogSet": "Wie geplant eintragen", + "workoutNotificationSkipRest": "Überspringen", + "workoutNotificationExtendRest": "+{seconds} s", + "workoutNotificationNotLoggedTitle": "Satz nicht eingetragen", + "workoutNotificationNotLoggedBody": "Öffne den Studiomodus, um das Training fortzusetzen", + "workoutNotificationAlarmChannel": "Pausenalarm", + "workoutNotificationChannel": "Training", "gymModeStickySetValues": "Werte des letzten Satzes übernehmen", "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du zuletzt dafür eingetragen hast", "upNext": "Als Nächstes" diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8839af841..284e9a4db 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -375,7 +375,61 @@ "countdown": "Countdown", "stopwatch": "Stopwatch", "gymModeDefaultCountdownTime": "Default countdown time, in seconds", - "gymModeNotifyOnCountdownFinish": "Notify on countdown end", + "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": "Allows accessing and controlling the current workout via a persistent notification", + "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 planned set", + "@workoutNotificationLogSet": { + "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" + }, + "workoutNotificationExtendRest": "+{seconds} s", + "@workoutNotificationExtendRest": { + "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" + } + } + }, + "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" + }, "duration": "Duration", "durationHoursMinutes": "{hours}h {minutes}m", "@durationHoursMinutes": { diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index d8ea971bf..b5cbb6b75 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": { @@ -1195,6 +1194,24 @@ "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", + "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": "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", + "workoutNotificationNext": "Siguiente: {set}", + "workoutNotificationSetOf": "Serie {current} de {total}", + "workoutNotificationInProgress": "Entrenamiento en curso", + "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", + "workoutNotificationChannel": "Entrenamiento", + "authorHelpText": "Se muestra como autor del ejercicio (CC BY-SA 4.0). Cámbialo solo si no eres el autor.", "gymModeStickySetValues": "Mantener los valores de la última serie", "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez", "upNext": "A continuación" diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 47cd4c55c..adae245c6 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": { @@ -1187,6 +1186,23 @@ "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", + "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": "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", + "workoutNotificationNext": "Ensuite : {set}", + "workoutNotificationSetOf": "Série {current} sur {total}", + "workoutNotificationInProgress": "Entraînement en cours", + "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", + "workoutNotificationChannel": "Entraînement", "gymModeStickySetValues": "Reprendre les valeurs de la dernière série", "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées", "upNext": "À suivre" 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/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/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 802d672b2..3291be28b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -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: fd5fc8966a8b34337ac182dc394f3506139b69d8138d4e9e174a13d6468adcd4 + url: "https://pub.dev" + source: hosted + version: "22.3.3" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: "3b89a4bf095fa5f8a99beeabf982c5bd506c3ad25e7b9e61da945e994dc5b615" + url: "https://pub.dev" + source: hosted + version: "8.0.2" + 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 @@ -1313,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: diff --git a/pubspec.yaml b/pubspec.yaml index 14ab2b8e1..760f87e7d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -78,11 +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.3 dev_dependencies: flutter_test: diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 2b86b41fe..7b552f83d 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -1473,12 +1473,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); @@ -5599,6 +5742,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/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 { 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 new file mode 100644 index 000000000..f28a8a1ec --- /dev/null +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -0,0 +1,392 @@ +/* + * 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/core/consts.dart'; +import 'package:wger/features/exercises/models/image.dart'; +import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/models/page_progress.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, + List recentLogs = const [], + Uri? Function(String? path)? mediaUrl, + }) => buildWorkoutNotification( + notifier.state, + now: now, + i18n: i18n, + languageCode: 'en', + withControls: withControls, + recentLogs: recentLogs, + mediaUrl: mediaUrl, + ); + + /// The state keeps a rest by its start, the end of a countdown follows from + /// the rest length of [page] + void onPage(SlotPageEntry page, {DateTime? restStartedAt, DateTime? restEndsAt}) { + final startedAt = restEndsAt == null + ? restStartedAt + : restEndsAt.subtract(notifier.state.restDurationFor(page)!); + notifier.state = notifier.state.copyWith( + currentPage: page.pageIndex, + progress: { + ...notifier.state.progress, + if (startedAt != null) page.key: PageProgress(timerStartedAt: startedAt), + }, + ); + } + + 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(); + + // The alarm already shows the set, like the page after the rest + 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!.canLogSet, isTrue); + expect(target.alarm!.payload.logSlotKey, logs()[1].key); + 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); + expect(target.controls!.payload.restSlotKey, timer.key); + }); + + test('With the alert off the controls still switch at the rest end, silently', () { + notifier.state = notifier.state.copyWith(alertOnCountdownEnd: false); + final endsAt = now.add(const Duration(seconds: 90)); + onPage(timers().first, restStartedAt: now, restEndsAt: endsAt); + + final target = build(); + 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', () { + 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, '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', () { + 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!.title, 'Rest is over'); + 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.logSlotKey, logs()[1].key); + }); + + 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 · 3 × 100 kg'); + + 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', () { + notifier.markSlotPageAsDone(logs()[1].key, 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('"+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); + + // The other exercise has no rest time and the countdown setting is off + onPage(timers().last, 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]); + + expect(build(withControls: false), WorkoutNotificationTarget.none); + }); + }); + + 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: 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', '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', () { + 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 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, 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']); + + notifier.markSlotPageAsDone(logs()[1].key, 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( + routineId: 1, + dayId: 2, + iteration: 3, + workoutStart: DateTime.utc(2025, 3, 29, 14, 33), + logSlotKey: 'log', + restSlotKey: '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..73d20d5f6 --- /dev/null +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -0,0 +1,476 @@ +/* + * 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:ui'; + +import 'package:clock/clock.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.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/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'; +import 'workout_notification_controller_test.mocks.dart'; + +@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; + + 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 {}); + when(service.showNotLogged(any)).thenAnswer((_) async {}); + when(service.actionHandled()).thenAnswer((_) async {}); + when(service.initialize(any)).thenAnswer((_) async {}); + logRepo = MockWorkoutLogRepository(); + when(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {}); + + container = ProviderContainer.test( + overrides: [ + workoutNotificationServiceProvider.overrideWithValue(service), + workoutLogRepositoryProvider.overrideWithValue(logRepo), + ], + ); + 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); + } + + /// 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); + withClock(Clock.fixed(now), () => gymState.setCurrentPage(timer.pageIndex - 1)); + await withClock(Clock.fixed(now), () async { + gymState.setCurrentPage(timer.pageIndex); + await settle(); + }); + } + + test('A rest in the background 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('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); + + toForeground(); + await settle(); + verify(service.cancelAll()).called(1); + verifyNever(service.scheduleRestAlarm(any, any)); + verifyNever(service.showControls(any, any)); + + await withClock(Clock.fixed(now), () async { + 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); + + 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(alertOnCountdownEnd: false); + await startRest(); + // 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); + await withClock(Clock.fixed(now), () async { + gymState.state = gymState.state.copyWith( + alertOnCountdownEnd: true, + showWorkoutNotification: false, + ); + await settle(); + }); + final alarm = verify(service.scheduleRestAlarm(captureAny, any)).captured.single as RestAlarm; + expect(alarm.silent, isFalse); + 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)); + }); + + group('Startup', () { + 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 { + 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); + }); + + 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', () { + SlotPageEntry slotPage(int index) => gymState.state.getSlotEntryPageByIndex(index)!; + + /// The payload the notification on the current page carries + String payloadFor({String? logSlotKey, String? restSlotKey, DateTime? workoutStart}) => + WorkoutNotificationPayload( + routineId: gymState.state.routine.id!, + dayId: gymState.state.dayId, + iteration: gymState.state.iteration, + workoutStart: workoutStart ?? gymState.state.workoutStart, + logSlotKey: logSlotKey, + restSlotKey: restSlotKey, + ).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(logSlotKey: slotPage(rest + 1).key), + ); + await settle(); + }); + + 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.restSlotKey, slotPage(rest + 2).key); + }); + + 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(restSlotKey: slotPage(rest).key), + 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 rest end offers earlier logs of the next set', () async { + await startRest(); + + // 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 { + 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(); + + // 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 { + await startRest(); + final rest = gymState.state.currentPage; + + IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT)!.send([ + WORKOUT_NOTIFICATION_ACTION_LOG_SET, + payloadFor(logSlotKey: slotPage(rest + 1).key), + '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(logSlotKey: slotPage(rest + 1).key), + '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(restSlotKey: slotPage(rest).key), + ); + 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(restSlotKey: '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; + 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( + logSlotKey: slotPage(rest + 1).key, + workoutStart: DateTime.utc(2020), + ), + ); + // For a rest the user already left + await controller.handleAction( + WORKOUT_NOTIFICATION_ACTION_SKIP_REST, + payloadFor(restSlotKey: slotPage(rest - 2).key), + ); + 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(); + + 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 new file mode 100644 index 000000000..99453be3e --- /dev/null +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -0,0 +1,200 @@ +// 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/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 +// 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) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels]), + 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); + + @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]. +/// +/// 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<_i6.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i6.Log?>.value(), + ) + as _i3.Future<_i6.Log?>); + + @override + _i3.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i3.Future>.value(<_i6.Log>[]), + ) + as _i3.Future>); + + @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/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart new file mode 100644 index 000000000..71524d913 --- /dev/null +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -0,0 +1,327 @@ +/* + * 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: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'; + +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', + extendRest: '+30 s', + 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); + + 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(); + 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, + 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; + + 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)); + }); + + 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, + ]); + }); + + 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( + 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( + (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); + }); + }); + + 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); + }); + }); +} diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 03f503be2..ea5441106 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -55,12 +55,17 @@ import 'gym_state_test.mocks.dart'; 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, @@ -730,6 +735,398 @@ void main() { }); }); + group('GymStateNotifier notification settings', () { + test('Both are on without stored preferences', () async { + await notifier.loadPrefs(); + + expect(notifier.state.alertOnCountdownEnd, isTrue); + expect(notifier.state.showWorkoutNotification, isTrue); + }); + + test('Stored values are loaded', () async { + await PreferenceHelper.asyncPref.setBool(PREFS_ALERT_COUNTDOWN, false); + await PreferenceHelper.asyncPref.setBool(PREFS_WORKOUT_NOTIFICATION, false); + + await notifier.loadPrefs(); + + expect(notifier.state.alertOnCountdownEnd, isFalse); + expect(notifier.state.showWorkoutNotification, isFalse); + }); + + test('The setters change only their own flag and persist it', () async { + notifier.setAlertOnCountdownEnd(false); + await pumpEventQueue(); + expect(notifier.state.alertOnCountdownEnd, isFalse); + expect(notifier.state.showWorkoutNotification, isTrue); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_ALERT_COUNTDOWN), false); + + notifier.setShowWorkoutNotification(false); + await pumpEventQueue(); + expect(notifier.state.alertOnCountdownEnd, 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); + + 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('Other pages have no 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 continues its rest', () { + // E.g. after going back to correct the set during the rest + final timer = timerWithRestTime(); + goTo(timer); + goTo(timer + 1); + + goTo(timer, at: later); + + expect(notifier.state.restStartedAt, start); + expect(notifier.state.restEndsAt, start.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 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.progressOf(log.key).done, 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.progressOf(log.key).done, isFalse); + expect(notifier.state.currentPage, log.pageIndex); + }); + + test('logCurrentSet updates a corrected set and keeps its rest running', () async { + when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((invocation) async { + (invocation.positionalArguments.first as Log).id = 'log-1'; + }); + when(mockLogRepo.updateLocalDrift(any)).thenAnswer((_) async {}); + final log = firstLog(); + notifier.setCurrentPage(log.pageIndex); + await withClock(Clock.fixed(start), notifier.logCurrentSet); + + // Back to the set during the rest, the form holds the saved entry + notifier.setCurrentPage(log.pageIndex); + container.read(gymLogProvider.notifier).setRepetitions(5); + await withClock(Clock.fixed(start.add(const Duration(seconds: 40))), notifier.logCurrentSet); + + final updated = verify(mockLogRepo.updateLocalDrift(captureAny)).captured.single as Log; + expect(updated.id, 'log-1'); + expect(updated.repetitions, 5); + verify(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1); + expect(notifier.state.currentPage, log.pageIndex + 1); + expect(notifier.state.restStartedAt, start); + }); + + 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.key), + ); + + expect(logged, isTrue); + final saved = capturedLog(); + expect(saved.repetitions, log.setConfigData!.repetitions); + expect(saved.weight, log.setConfigData!.weight); + expect(notifier.state.progressOf(log.key).done, 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.key), isTrue); + + 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))); + }); + + 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.key, 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.key, 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(); + notifier.state = notifier.state.copyWith(currentPage: log.pageIndex); + + expect(await notifier.logPlannedSet(log.key), 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.key); + final second = await notifier.logPlannedSet(log.key); + 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 timerKey = notifier.state.getSlotEntryPageByIndex()!.key; + + expect(await notifier.logPlannedSet('unknown'), isFalse, reason: 'unknown page'); + expect(await notifier.logPlannedSet(timerKey), isFalse, reason: 'not a log page'); + expect(await notifier.logPlannedSet(firstLog().key), isFalse, reason: 'not the next set'); + + notifier.markSlotPageAsDone(log.key, isDone: true); + expect(await notifier.logPlannedSet(log.key), 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.key), 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.key), 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 sticky set values', () { // Page structure of the test routine (exercise + timer pages enabled): // start(0) diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index bc7ae4bbf..c22d106cd 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 @@ -506,6 +514,119 @@ 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( + '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_ALERT_COUNTDOWN, false); + await PreferenceHelper.asyncPref.setBool(PREFS_WORKOUT_NOTIFICATION, false); + addTearDown(() async { + await PreferenceHelper.asyncPref.remove(PREFS_ALERT_COUNTDOWN); + 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 ccf083404..68113e753 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -28,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; @@ -631,3 +633,108 @@ 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 initialize(_i32.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels]), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + + @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 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, + _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 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( + Invocation.method(#cancelAll, []), + returnValue: _i10.Future.value(), + 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.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index e71541e63..23c7dc793 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -16,11 +16,15 @@ * 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'; +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'; @@ -28,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), ], ); @@ -51,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, @@ -90,27 +101,36 @@ 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(); + 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(); @@ -124,11 +144,70 @@ 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.showWorkoutNotification, isFalse); expect(notifier.state.stickySetValues, isTrue); }); + 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('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); + + await pumpGymModeOptions(tester); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('gym-mode-notify-countdown')), 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 { await pumpGymModeOptions(tester); @@ -226,4 +305,81 @@ 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('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 end alert off', (tester) async { + await openOptions(tester); + expect(hint, findsNothing); + + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); + container.invalidate(exactAlarmsAllowedProvider); + container.read(gymStateProvider.notifier).setAlertOnCountdownEnd(false); + await tester.pumpAndSettle(); + 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); + }); } 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..8d27c80b0 --- /dev/null +++ b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart @@ -0,0 +1,130 @@ +// 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) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels]), + 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); + + @override + _i3.Future actionHandled() => + (super.noSuchMethod( + Invocation.method(#actionHandled, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart index 2b5223957..f3f23849a 100644 --- a/test/features/routines/widgets/gym_mode/timer_test.dart +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -23,6 +23,7 @@ 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/models/page_progress.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'; @@ -49,7 +50,7 @@ void main() { notifier.initData(routine, routine.days.first.id!, 1); }); - Future pumpTimer(WidgetTester tester, int timerPageIndex) async { + Future pumpTimer(WidgetTester tester, int timerPageIndex, {bool countsUp = false}) async { final slotPage = container.read(gymStateProvider).getSlotEntryPageByIndex(timerPageIndex)!; expect(slotPage.type, SlotPageType.timer); @@ -68,7 +69,12 @@ void main() { final controller = PageController(); return PageView( controller: controller, - children: [TimerCountdownWidget(controller, 90, slotPage.key)], + children: [ + if (countsUp) + TimerWidget(controller, slotPage.key) + else + TimerCountdownWidget(controller, 90, slotPage.key), + ], ); }, ), @@ -162,5 +168,61 @@ void main() { }); expect(haptics, hasLength(1)); }); + + testWidgets('alerts again when the rest is extended after its end', (tester) async { + final haptics = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + call, + ) async { + if (call.method == 'HapticFeedback.vibrate') { + haptics.add(call); + } + return null; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final t0 = DateTime(2024, 5, 2, 12); + final key = container.read(gymStateProvider).getSlotEntryPageByIndex(3)!.key; + + await withClock(Clock.fixed(t0), () => pumpTimer(tester, 3)); + await withClock(Clock.fixed(t0.add(const Duration(seconds: 95))), () => pumpTimer(tester, 3)); + expect(haptics, hasLength(1)); + expect(haptics.single.arguments, isNull, reason: 'the full vibration, not a light impact'); + + // Extending moves the start, so the countdown ends 30 s later + final notifier = container.read(gymStateProvider.notifier); + notifier.state = notifier.state.copyWith( + progress: {key: PageProgress(timerStartedAt: t0.add(const Duration(seconds: 30)))}, + ); + await withClock( + Clock.fixed(t0.add(const Duration(seconds: 100))), + () => pumpTimer(tester, 3), + ); + expect(find.text('0:20'), findsOneWidget); + expect(haptics, hasLength(1)); + + await withClock( + Clock.fixed(t0.add(const Duration(seconds: 125))), + () => pumpTimer(tester, 3), + ); + expect(haptics, hasLength(2)); + }); + + testWidgets('counts up from the start in the gym state', (tester) async { + final t0 = DateTime(2024, 5, 2, 12); + final key = container.read(gymStateProvider).getSlotEntryPageByIndex(3)!.key; + final notifier = container.read(gymStateProvider.notifier); + notifier.state = notifier.state.copyWith( + progress: {key: PageProgress(timerStartedAt: t0.subtract(const Duration(seconds: 30)))}, + ); + + await withClock(Clock.fixed(t0), () => pumpTimer(tester, 3, countsUp: true)); + + expect(find.text('0:30'), findsOneWidget); + }); }); } 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(); 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 )