From bca079565c7c60da5213c3c5aa400a14756bf9a2 Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Sun, 11 Oct 2026 10:32:43 +0200 Subject: [PATCH] feat(vs): answer the calibrator from the rider's controller While a calibration run is on, the rider never has to touch the screen: - hold shift down: too heavy - hold shift up: too light - press both shifters together: about right / next grade - buttons mapped to navigate left / select / navigate right answer directly on controllers that have them Short presses still shift, so the rider can pick a gear on each grade. The run installs a ControllerInputInterceptor on BaseDevice; the device layer offers it every press (with the button's single-click action), claims the long press of the shift buttons, and catches the shifter chord before the front-shift combo. Consumed presses are not forwarded to a trainer app, keyboard or touch output. Two controller halves pressed together within 150 ms count as the chord and undo the first shift; a held button cannot answer twice within 700 ms. Every way a run ends (finish, stop, leaving the page, a trainer app connecting) removes the interceptor. An answer gives the shift haptic/sound feedback, outlines its button briefly and is announced for screen readers. With a controller connected, each answer shows its controller gesture underneath, in all six locales. Co-Authored-By: Claude Opus 5.5 --- lib/bluetooth/devices/base_device.dart | 41 +++++- .../devices/controller_input_interceptor.dart | 29 ++++ lib/i10n/intl_de.arb | 7 +- lib/i10n/intl_en.arb | 7 +- lib/i10n/intl_es.arb | 7 +- lib/i10n/intl_fr.arb | 7 +- lib/i10n/intl_it.arb | 7 +- lib/i10n/intl_pl.arb | 7 +- .../vs_calibration_page.dart | 132 +++++++++++++++++- .../calibration_controller_input.dart | 127 +++++++++++++++++ .../calibration_controller_routing_test.dart | 115 +++++++++++++++ .../vs_calibration_page_test.dart | 91 ++++++++++++ .../calibration_controller_input_test.dart | 132 ++++++++++++++++++ 13 files changed, 696 insertions(+), 13 deletions(-) create mode 100644 lib/bluetooth/devices/controller_input_interceptor.dart create mode 100644 lib/services/vs_calibration/calibration_controller_input.dart create mode 100644 test/bluetooth/calibration_controller_routing_test.dart create mode 100644 test/services/vs_calibration/calibration_controller_input_test.dart diff --git a/lib/bluetooth/devices/base_device.dart b/lib/bluetooth/devices/base_device.dart index 267e5c98..ae85d04a 100644 --- a/lib/bluetooth/devices/base_device.dart +++ b/lib/bluetooth/devices/base_device.dart @@ -4,7 +4,8 @@ import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart'; import 'package:bike_control/bluetooth/devices/zwift/constants.dart'; import 'package:bike_control/gen/l10n.dart'; import 'package:bike_control/main.dart'; -import 'package:bike_control/utils/actions/base_actions.dart' show Success; +import 'package:bike_control/bluetooth/devices/controller_input_interceptor.dart'; +import 'package:bike_control/utils/actions/base_actions.dart' show ActionResult, Success; import 'package:bike_control/utils/actions/desktop.dart'; import 'package:bike_control/utils/core.dart'; import 'package:bike_control/utils/iap/iap_manager.dart'; @@ -67,6 +68,11 @@ abstract class BaseDevice { /// connect/disconnect notifications for the cycle. bool get isResetting => false; + /// While set, every controller press is offered to it first (see + /// [ControllerInputInterceptor]); the shifting calibrator installs one for + /// the length of a run and removes it on every way out. + static ControllerInputInterceptor? inputInterceptor; + static const Duration _longPressTriggerDelay = Duration(milliseconds: 550); static const Duration _doubleClickDelay = Duration(milliseconds: 320); static const Duration _repeatInterval = Duration(milliseconds: 250); @@ -125,6 +131,13 @@ abstract class BaseDevice { _activeLongPressButtons.clear(); } _previouslyPressedButtons = buttonsClicked.toSet(); + // Before the front-shift combo: while a screen owns the chord (the + // calibrator's "both shifters"), it must not also change the ring. + final chord = inputInterceptor?.interceptChord(buttonsClicked, buttonsClicked.map(_mappedAction).toList()); + if (chord != null) { + _reportIntercepted(chord); + return; + } if (await _maybeHandleFrontShiftCombo(buttonsClicked)) return; await performClick(buttonsClicked, trigger: ButtonTrigger.singleClick); return; @@ -282,7 +295,28 @@ abstract class BaseDevice { } } + /// What the rider's keymap does with [button] on a single click. + InGameAction? _mappedAction(ControllerButton button) => + core.actionHandler.supportedApp?.keymap.getKeyPair(button, trigger: ButtonTrigger.singleClick)?.inGameAction; + + bool _longPressClaimed(ControllerButton button) => + supportsLongPress && (inputInterceptor?.claimsLongPress(_mappedAction(button)) ?? false); + + /// Offers a press to [inputInterceptor]; non-null means it was consumed. + ActionResult? _intercept(ControllerButton button, ButtonTrigger trigger, {required bool isKeyDown}) { + final interceptor = inputInterceptor; + if (interceptor == null) return null; + final result = interceptor.intercept(button, _mappedAction(button), trigger, isKeyDown: isKeyDown); + if (result != null) _reportIntercepted(result); + return result; + } + + void _reportIntercepted(ActionResult result) { + if (result.message.isNotEmpty) actionStreamInternal.add(ActionNotification(result)); + } + bool _hasTriggerAction(ControllerButton button, ButtonTrigger trigger) { + if (trigger == ButtonTrigger.longPress && _longPressClaimed(button)) return true; final keyPair = core.actionHandler.supportedApp?.keymap.getKeyPair(button, trigger: trigger); if (keyPair == null && core.actionHandler.supportedApp == null) { return trigger == ButtonTrigger.singleClick; @@ -312,6 +346,8 @@ abstract class BaseDevice { /// Active by default for Pro users when no explicit long press action is set. bool _shouldRepeatSingleClick(ControllerButton button) { if (!supportsLongPress) return false; + // A claimed hold is an answer, not a stream of repeated clicks. + if (_longPressClaimed(button)) return false; if (!isProEnabledForRepeat) return false; final longPressPair = core.actionHandler.supportedApp?.keymap.getKeyPair( button, @@ -361,6 +397,7 @@ abstract class BaseDevice { ButtonTrigger trigger = ButtonTrigger.longPress, }) async { for (final action in buttonsClicked) { + if (_intercept(action, trigger, isKeyDown: true) != null) continue; // Check IAP status before executing command if (!_canExecuteCommand()) { //actionStreamInternal.add(AlertNotification(LogLevel.LOGLEVEL_ERROR, _getCommandLimitMessage())); @@ -422,6 +459,7 @@ abstract class BaseDevice { ButtonTrigger trigger = ButtonTrigger.singleClick, }) async { for (final action in buttonsClicked) { + if (_intercept(action, trigger, isKeyDown: true) != null) continue; // Check IAP status before executing command if (!_canExecuteCommand()) { _showCommandLimitAlert(); @@ -445,6 +483,7 @@ abstract class BaseDevice { }) async { _stopRepeatingSingleClick(); for (final action in buttonsReleased) { + if (_intercept(action, trigger, isKeyDown: false) != null) continue; // Skip normal release handling for repeat-on-long-press buttons if (_shouldRepeatSingleClick(action)) { continue; diff --git a/lib/bluetooth/devices/controller_input_interceptor.dart b/lib/bluetooth/devices/controller_input_interceptor.dart new file mode 100644 index 00000000..05490443 --- /dev/null +++ b/lib/bluetooth/devices/controller_input_interceptor.dart @@ -0,0 +1,29 @@ +import 'package:bike_control/utils/actions/base_actions.dart'; +import 'package:bike_control/utils/keymap/buttons.dart'; +import 'package:bike_control/utils/keymap/keymap.dart'; + +/// Lets a screen take over some controller presses for as long as it is +/// installed in `BaseDevice.inputInterceptor`, before they become actions. +/// +/// Every press is offered with the action the rider's keymap gives the button +/// on a single click ([mappedAction]), so a scheme can be written in terms of +/// "the shift up button" rather than hardware button names. A non-null result +/// consumes the press: it is not forwarded to the trainer app, keyboard or +/// touch output. Null lets it through unchanged. +abstract interface class ControllerInputInterceptor { + /// True when a long press of a button mapped to [mappedAction] should be + /// detected (and offered to [intercept]) even though the keymap gives it no + /// long-press action. Its short press then fires on release, as for any + /// button with a long-press action. + bool claimsLongPress(InGameAction? mappedAction); + + ActionResult? intercept( + ControllerButton button, + InGameAction? mappedAction, + ButtonTrigger trigger, { + required bool isKeyDown, + }); + + /// Several buttons pressed in the same frame. + ActionResult? interceptChord(List buttons, List mappedActions); +} diff --git a/lib/i10n/intl_de.arb b/lib/i10n/intl_de.arb index 226c886a..78a655ec 100644 --- a/lib/i10n/intl_de.arb +++ b/lib/i10n/intl_de.arb @@ -2885,5 +2885,10 @@ "@vsCalibratePct": {"placeholders": {"pct": {"type": "int"}}}, "vsCalibrateReset": "Auf 100 % zurücksetzen", "vsCalibrateAgain": "Erneut kalibrieren", - "vsGroupCheck": "Prüfen und kalibrieren" + "vsGroupCheck": "Prüfen und kalibrieren", + "vsCalibrateControllerAnswered": "{answer}, über deinen Controller", + "@vsCalibrateControllerAnswered": {"placeholders": {"answer": {"type": "String"}}}, + "vsCalibrateHintTooHeavy": "Runterschalten halten", + "vsCalibrateHintAboutRight": "Beide Schalter drücken", + "vsCalibrateHintTooLight": "Hochschalten halten" } diff --git a/lib/i10n/intl_en.arb b/lib/i10n/intl_en.arb index a9c18803..a35be150 100644 --- a/lib/i10n/intl_en.arb +++ b/lib/i10n/intl_en.arb @@ -3295,5 +3295,10 @@ "@vsCalibratePct": {"placeholders": {"pct": {"type": "int"}}}, "vsCalibrateReset": "Reset to 100%", "vsCalibrateAgain": "Calibrate again", - "vsGroupCheck": "Check and calibrate" + "vsGroupCheck": "Check and calibrate", + "vsCalibrateControllerAnswered": "{answer}, from your controller", + "@vsCalibrateControllerAnswered": {"placeholders": {"answer": {"type": "String"}}}, + "vsCalibrateHintTooHeavy": "Hold shift down", + "vsCalibrateHintAboutRight": "Press both shifters", + "vsCalibrateHintTooLight": "Hold shift up" } diff --git a/lib/i10n/intl_es.arb b/lib/i10n/intl_es.arb index 986c0c3a..05c4c775 100644 --- a/lib/i10n/intl_es.arb +++ b/lib/i10n/intl_es.arb @@ -2885,5 +2885,10 @@ "@vsCalibratePct": {"placeholders": {"pct": {"type": "int"}}}, "vsCalibrateReset": "Restablecer a 100 %", "vsCalibrateAgain": "Calibrar de nuevo", - "vsGroupCheck": "Comprobar y calibrar" + "vsGroupCheck": "Comprobar y calibrar", + "vsCalibrateControllerAnswered": "{answer}, desde tu mando", + "@vsCalibrateControllerAnswered": {"placeholders": {"answer": {"type": "String"}}}, + "vsCalibrateHintTooHeavy": "Mantén bajar marcha", + "vsCalibrateHintAboutRight": "Pulsa ambos cambios", + "vsCalibrateHintTooLight": "Mantén subir marcha" } diff --git a/lib/i10n/intl_fr.arb b/lib/i10n/intl_fr.arb index 4470f817..2055539f 100644 --- a/lib/i10n/intl_fr.arb +++ b/lib/i10n/intl_fr.arb @@ -2885,5 +2885,10 @@ "@vsCalibratePct": {"placeholders": {"pct": {"type": "int"}}}, "vsCalibrateReset": "Réinitialiser à 100 %", "vsCalibrateAgain": "Calibrer à nouveau", - "vsGroupCheck": "Vérifier et calibrer" + "vsGroupCheck": "Vérifier et calibrer", + "vsCalibrateControllerAnswered": "{answer}, depuis ta manette", + "@vsCalibrateControllerAnswered": {"placeholders": {"answer": {"type": "String"}}}, + "vsCalibrateHintTooHeavy": "Maintiens vitesse inférieure", + "vsCalibrateHintAboutRight": "Appuie sur les deux leviers", + "vsCalibrateHintTooLight": "Maintiens vitesse supérieure" } diff --git a/lib/i10n/intl_it.arb b/lib/i10n/intl_it.arb index f5a829bf..f216703e 100644 --- a/lib/i10n/intl_it.arb +++ b/lib/i10n/intl_it.arb @@ -2885,5 +2885,10 @@ "@vsCalibratePct": {"placeholders": {"pct": {"type": "int"}}}, "vsCalibrateReset": "Ripristina a 100%", "vsCalibrateAgain": "Calibra di nuovo", - "vsGroupCheck": "Verifica e calibra" + "vsGroupCheck": "Verifica e calibra", + "vsCalibrateControllerAnswered": "{answer}, dal tuo controller", + "@vsCalibrateControllerAnswered": {"placeholders": {"answer": {"type": "String"}}}, + "vsCalibrateHintTooHeavy": "Tieni premuto marcia giù", + "vsCalibrateHintAboutRight": "Premi entrambi i comandi", + "vsCalibrateHintTooLight": "Tieni premuto marcia su" } diff --git a/lib/i10n/intl_pl.arb b/lib/i10n/intl_pl.arb index 3cceec3d..1221c910 100644 --- a/lib/i10n/intl_pl.arb +++ b/lib/i10n/intl_pl.arb @@ -2885,5 +2885,10 @@ "@vsCalibratePct": {"placeholders": {"pct": {"type": "int"}}}, "vsCalibrateReset": "Przywróć 100%", "vsCalibrateAgain": "Kalibruj ponownie", - "vsGroupCheck": "Sprawdź i skalibruj" + "vsGroupCheck": "Sprawdź i skalibruj", + "vsCalibrateControllerAnswered": "{answer}, z kontrolera", + "@vsCalibrateControllerAnswered": {"placeholders": {"answer": {"type": "String"}}}, + "vsCalibrateHintTooHeavy": "Przytrzymaj bieg w dół", + "vsCalibrateHintAboutRight": "Naciśnij obie manetki", + "vsCalibrateHintTooLight": "Przytrzymaj bieg w górę" } diff --git a/lib/pages/proxy_device_details/vs_calibration_page.dart b/lib/pages/proxy_device_details/vs_calibration_page.dart index 0b696ee6..03f8ac80 100644 --- a/lib/pages/proxy_device_details/vs_calibration_page.dart +++ b/lib/pages/proxy_device_details/vs_calibration_page.dart @@ -1,10 +1,13 @@ import 'dart:async'; +import 'package:bike_control/bluetooth/devices/base_device.dart'; import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart'; import 'package:bike_control/gen/l10n.dart'; import 'package:bike_control/main.dart' show recordError; import 'package:bike_control/pages/proxy_device_details/gear_ratios_editor_page.dart' show updateActiveShiftingConfig; +import 'package:bike_control/services/vs_calibration/calibration_controller_input.dart'; import 'package:bike_control/services/vs_calibration/vs_calibration_session.dart'; +import 'package:bike_control/utils/core.dart'; import 'package:bike_control/widgets/ui/app_theme.dart' show BkComponentThemes; import 'package:bike_control/widgets/ui/bk_grouped_section.dart'; import 'package:bike_control/widgets/ui/bk_icon_button.dart'; @@ -13,6 +16,7 @@ import 'package:bike_control/widgets/ui/bk_page_header.dart'; import 'package:bike_control/widgets/ui/stepper_control.dart'; import 'package:bike_control/widgets/ui/type_scale.dart'; import 'package:prop/emulators/definitions/fitness_bike_definition.dart'; +import 'package:flutter/semantics.dart' show SemanticsService; import 'package:shadcn_flutter/shadcn_flutter.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; @@ -56,6 +60,16 @@ class _VsCalibrationPageState extends State { /// grade), handed back however the run ends. TrainerControlSnapshot? _startControl; + /// The rider's controller answering the run (see + /// [CalibrationControllerInput] for the scheme); installed on + /// [BaseDevice.inputInterceptor] for exactly as long as a run is on. + CalibrationControllerInput? _controllerInput; + + /// The answer the controller just gave, outlined on its button for a + /// moment so the rider sees it registered. + CalibrationRating? _controllerFlash; + Timer? _flashTimer; + /// True once the current grade has been adjusted at least once, so the /// "ride it again" line only appears after a change. bool _adjustedHere = false; @@ -72,6 +86,7 @@ class _VsCalibrationPageState extends State { // A run outlives the page unless ended here: the trainer would stay on a // calibration grade at a difficulty nobody accepted. _abandonRun(); + _flashTimer?.cancel(); super.dispose(); } @@ -105,6 +120,13 @@ class _VsCalibrationPageState extends State { _runDef = def; _session = session; def.setCalibrationGrade(session.grade001Pct); + final input = CalibrationControllerInput( + onAnswer: _onControllerAnswer, + currentGear: () => def.currentGear.value, + restoreGear: (gear) => def.setTargetGear(gear), + ); + _controllerInput = input; + BaseDevice.inputInterceptor = input; _wakelock(true); setState(() { _refusal = null; @@ -130,9 +152,50 @@ class _VsCalibrationPageState extends State { setState(() => _adjustedHere = session.stepIndex == stepBefore); } + /// A controller answer: the same as tapping it, plus the shift feedback the + /// rider gets for a gear change and a screen-reader announcement. + void _onControllerAnswer(CalibrationRating rating) { + if (!mounted || _session == null) return; + final l10n = AppLocalizations.of(context); + unawaited(core.shiftFeedback.shifted(up: rating != CalibrationRating.tooHeavy)); + final view = View.maybeOf(context); + if (view != null) { + unawaited( + SemanticsService.sendAnnouncement( + view, + l10n.vsCalibrateControllerAnswered(_answerLabel(l10n, rating)), + Directionality.maybeOf(context) ?? TextDirection.ltr, + ), + ); + } + _flashTimer?.cancel(); + setState(() => _controllerFlash = rating); + _flashTimer = Timer(const Duration(milliseconds: 700), () { + if (mounted) setState(() => _controllerFlash = null); + }); + _rate(rating); + } + + static String _answerLabel(AppLocalizations l10n, CalibrationRating rating) => switch (rating) { + CalibrationRating.tooHeavy => l10n.vsCalibrateTooHeavy, + CalibrationRating.aboutRight => l10n.vsCalibrateAboutRight, + CalibrationRating.tooLight => l10n.vsCalibrateTooLight, + }; + + /// Hands the controller back to its normal mapping; every way a run ends + /// goes through here. + void _releaseController() { + final input = _controllerInput; + _controllerInput = null; + if (input != null && identical(BaseDevice.inputInterceptor, input)) { + BaseDevice.inputInterceptor = null; + } + } + Future _finish(FitnessBikeDefinition def, int pct) async { _session = null; _runDef = null; + _releaseController(); _wakelock(false); // The difficulty stays; the trainer goes back to whatever it was doing. _restoreControl(def); @@ -152,6 +215,7 @@ class _VsCalibrationPageState extends State { final def = _runDef; _session = null; _runDef = null; + _releaseController(); if (def == null) return; _wakelock(false); if (!_owns(def)) return; @@ -449,16 +513,72 @@ class _VsCalibrationPageState extends State { : Button.outline(key: ValueKey(key), alignment: Alignment.center, onPressed: () => _rate(rating), child: child); } + final cs = Theme.of(context).colorScheme; + // With a controller connected, each answer says how to give it from the + // bars (the scheme is documented on [CalibrationControllerInput]). + final hints = core.connection.controllerDevices.any((d) => d.isConnected); + + Widget slot(Widget button, CalibrationRating rating, String hint) { + final flashing = _controllerFlash == rating; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 4, + children: [ + // A fixed 2 px ring, coloured only while flashing, so the answer + // that registered stands out without the layout jumping. + Container( + key: flashing ? const ValueKey('vs-cal-controller-flash') : null, + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all(color: flashing ? cs.primary : const Color(0x00000000), width: 2), + ), + child: button, + ), + if (hints) + ExcludeSemantics( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + spacing: 6, + children: [ + Icon(LucideIcons.gamepad2, size: 13, color: cs.mutedForeground), + Flexible( + child: Text( + hint, + textAlign: TextAlign.center, + style: context.typography.caption.copyWith(color: cs.mutedForeground), + ), + ), + ], + ), + ), + ], + ); + } + final buttons = [ - answer('vs-cal-too-heavy', LucideIcons.weight, l10n.vsCalibrateTooHeavy, CalibrationRating.tooHeavy), - answer('vs-cal-about-right', LucideIcons.check, l10n.vsCalibrateAboutRight, CalibrationRating.aboutRight, primary: true), - answer('vs-cal-too-light', LucideIcons.feather, l10n.vsCalibrateTooLight, CalibrationRating.tooLight), + slot( + answer('vs-cal-too-heavy', LucideIcons.weight, l10n.vsCalibrateTooHeavy, CalibrationRating.tooHeavy), + CalibrationRating.tooHeavy, + l10n.vsCalibrateHintTooHeavy, + ), + slot( + answer('vs-cal-about-right', LucideIcons.check, l10n.vsCalibrateAboutRight, CalibrationRating.aboutRight, primary: true), + CalibrationRating.aboutRight, + l10n.vsCalibrateHintAboutRight, + ), + slot( + answer('vs-cal-too-light', LucideIcons.feather, l10n.vsCalibrateTooLight, CalibrationRating.tooLight), + CalibrationRating.tooLight, + l10n.vsCalibrateHintTooLight, + ), ]; - return LayoutBuilder( + final layout = LayoutBuilder( builder: (context, constraints) => constraints.maxWidth >= 480 - ? Row(spacing: 8, children: [for (final b in buttons) Expanded(child: b)]) - : Column(crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 8, children: buttons), + ? Row(crossAxisAlignment: CrossAxisAlignment.start, spacing: 8, children: [for (final b in buttons) Expanded(child: b)]) + : Column(crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 6, children: buttons), ); + return hints ? KeyedSubtree(key: const ValueKey('vs-cal-controller-hints'), child: layout) : layout; } // ----------------------------------------------------------------- result diff --git a/lib/services/vs_calibration/calibration_controller_input.dart b/lib/services/vs_calibration/calibration_controller_input.dart new file mode 100644 index 00000000..97442e67 --- /dev/null +++ b/lib/services/vs_calibration/calibration_controller_input.dart @@ -0,0 +1,127 @@ +import 'package:bike_control/bluetooth/devices/controller_input_interceptor.dart'; +import 'package:bike_control/gen/l10n.dart'; +import 'package:bike_control/services/vs_calibration/vs_calibration_session.dart'; +import 'package:bike_control/utils/actions/base_actions.dart'; +import 'package:bike_control/utils/keymap/buttons.dart'; +import 'package:bike_control/utils/keymap/keymap.dart'; + +/// Answers the shifting calibrator from the rider's own controller, so a run +/// never needs a hand off the bars. +/// +/// The scheme has to work on a controller with nothing but two shift buttons, +/// and the rider keeps shifting with those to pick a gear on every grade, so a +/// short press must stay a shift: +/// +/// * hold shift down: too heavy (the way the rider wants the gear to go) +/// * hold shift up: too light +/// * press both shifters together: about right, on to the next grade +/// +/// A hold is the existing long-press trigger (claimed via [claimsLongPress], +/// so it is detected even with no long-press mapping); a short press then +/// fires on release, as on any button with a long-press action. Both shifters +/// arrive either as one chord (one controller) or as two shifts from two +/// controller halves within [chordWindow]; in the second case the first shift +/// has already gone through, so it is undone. +/// +/// A controller with navigation buttons answers directly with whatever the +/// rider's keymap maps to navigate left / select / navigate right, left to +/// right as the answers are laid out on screen. +class CalibrationControllerInput implements ControllerInputInterceptor { + CalibrationControllerInput({ + required this.onAnswer, + required this.currentGear, + required this.restoreGear, + DateTime Function()? now, + }) : _now = now ?? DateTime.now; + + final void Function(CalibrationRating rating) onAnswer; + final int Function() currentGear; + final void Function(int gear) restoreGear; + final DateTime Function() _now; + + /// Two shifts this close together, one up and one down, are one chord. + static const chordWindow = Duration(milliseconds: 150); + + /// A held navigation button repeats; presses closer together than this + /// count as one. + static const answerDebounce = Duration(milliseconds: 700); + + DateTime? _lastAnswerAt; + ({InGameAction action, DateTime at, int gearBefore})? _lastShift; + + @override + bool claimsLongPress(InGameAction? mappedAction) => + mappedAction == InGameAction.shiftUp || mappedAction == InGameAction.shiftDown; + + @override + ActionResult? intercept( + ControllerButton button, + InGameAction? mappedAction, + ButtonTrigger trigger, { + required bool isKeyDown, + }) { + if (trigger == ButtonTrigger.longPress && claimsLongPress(mappedAction)) { + if (!isKeyDown) return Ignored('', button: button); + return _answer( + mappedAction == InGameAction.shiftDown ? CalibrationRating.tooHeavy : CalibrationRating.tooLight, + button, + ); + } + final direct = switch (mappedAction) { + InGameAction.navigateLeft => CalibrationRating.tooHeavy, + InGameAction.select => CalibrationRating.aboutRight, + InGameAction.navigateRight => CalibrationRating.tooLight, + _ => null, + }; + if (direct != null) { + return isKeyDown ? _answer(direct, button) : Ignored('', button: button); + } + if (trigger == ButtonTrigger.singleClick && isKeyDown && claimsLongPress(mappedAction)) { + return _shift(mappedAction!, button); + } + return null; + } + + @override + ActionResult? interceptChord(List buttons, List mappedActions) { + if (!mappedActions.contains(InGameAction.shiftUp) || !mappedActions.contains(InGameAction.shiftDown)) { + return null; + } + return _answer(CalibrationRating.aboutRight, buttons.first); + } + + /// A plain shift passes through, unless it completes a chord with the + /// opposite shift from another controller half. + ActionResult? _shift(InGameAction action, ControllerButton button) { + final now = _now(); + final last = _lastShift; + if (last != null && last.action != action && now.difference(last.at) <= chordWindow) { + _lastShift = null; + restoreGear(last.gearBefore); + return _answer(CalibrationRating.aboutRight, button); + } + _lastShift = (action: action, at: now, gearBefore: currentGear()); + return null; + } + + ActionResult _answer(CalibrationRating rating, ControllerButton button) { + final now = _now(); + final last = _lastAnswerAt; + // Measured from the last answer press, consumed or not, so a held button + // that keeps repeating never gets a second answer through. + _lastAnswerAt = now; + if (last != null && now.difference(last) < answerDebounce) { + return Ignored('', button: button); + } + onAnswer(rating); + final l10n = AppLocalizations.current; + return Success( + switch (rating) { + CalibrationRating.tooHeavy => l10n.vsCalibrateTooHeavy, + CalibrationRating.aboutRight => l10n.vsCalibrateAboutRight, + CalibrationRating.tooLight => l10n.vsCalibrateTooLight, + }, + button: button, + ); + } +} diff --git a/test/bluetooth/calibration_controller_routing_test.dart b/test/bluetooth/calibration_controller_routing_test.dart new file mode 100644 index 00000000..ff4f029d --- /dev/null +++ b/test/bluetooth/calibration_controller_routing_test.dart @@ -0,0 +1,115 @@ +// While the shifting calibrator runs, a controller's long press and chords +// answer it instead of reaching the trainer app; short presses still shift. +// Once it ends, the controller behaves exactly as before. +import 'package:bike_control/bluetooth/devices/base_device.dart'; +import 'package:bike_control/gen/l10n.dart'; +import 'package:bike_control/services/vs_calibration/calibration_controller_input.dart'; +import 'package:bike_control/services/vs_calibration/vs_calibration_session.dart'; +import 'package:bike_control/utils/actions/base_actions.dart'; +import 'package:bike_control/utils/core.dart'; +import 'package:bike_control/utils/keymap/apps/custom_app.dart'; +import 'package:bike_control/utils/keymap/buttons.dart'; +import 'package:bike_control/utils/keymap/keymap.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Future main() async { + const plus = ControllerButton('calPlus'); + const minus = ControllerButton('calMinus'); + + await AppLocalizations.load(const Locale('en')); + + final devices = []; + late List answers; + + CustomApp twoShifters() { + final app = CustomApp(profileName: 'Two shifters'); + for (final (button, action) in [(plus, InGameAction.shiftUp), (minus, InGameAction.shiftDown)]) { + app.keymap.addKeyPair( + KeyPair( + buttons: [button], + physicalKey: null, + logicalKey: null, + trigger: ButtonTrigger.singleClick, + inGameAction: action, + ), + ); + } + return app; + } + + _Shifters device() { + final d = _Shifters(); + devices.add(d); + return d; + } + + setUp(() { + answers = []; + core.actionHandler = StubActions(); + core.actionHandler.init(twoShifters()); + BaseDevice.inputInterceptor = CalibrationControllerInput( + onAnswer: answers.add, + currentGear: () => 12, + restoreGear: (_) {}, + ); + }); + + tearDown(() async { + BaseDevice.inputInterceptor = null; + for (final d in devices) { + await d.disconnect(); + } + devices.clear(); + }); + + StubActions stub() => core.actionHandler as StubActions; + + test('a short press still reaches the shift action', () async { + final d = device(); + await d.handleButtonsClicked([plus]); + await d.handleButtonsClicked([]); + expect(stub().performedActions.map((a) => (a.button.name, a.trigger)), [(plus.name, ButtonTrigger.singleClick)]); + expect(answers, isEmpty); + }); + + test('holding shift down answers too heavy and forwards nothing', () async { + final d = device(); + await d.handleButtonsClicked([minus]); + await Future.delayed(const Duration(milliseconds: 650)); + await d.handleButtonsClicked([]); + expect(answers, [CalibrationRating.tooHeavy]); + expect(stub().performedActions, isEmpty); + }); + + test('both shifters together answer about right and shift nothing', () async { + final d = device(); + await d.handleButtonsClicked([plus, minus]); + await d.handleButtonsClicked([]); + expect(answers, [CalibrationRating.aboutRight]); + expect(stub().performedActions, isEmpty); + }); + + test('after the calibrator ends, a hold is an ordinary press again', () async { + BaseDevice.inputInterceptor = null; + final d = device(); + await d.handleButtonsClicked([minus]); + await Future.delayed(const Duration(milliseconds: 650)); + await d.handleButtonsClicked([]); + expect(answers, isEmpty); + expect(stub().performedActions.map((a) => (a.button.name, a.trigger)), [(minus.name, ButtonTrigger.singleClick)]); + }); +} + +class _Shifters extends BaseDevice { + _Shifters() + : super( + 'Shifters', + uniqueId: 'calibration-shifters', + availableButtons: const [ControllerButton('calPlus'), ControllerButton('calMinus')], + icon: Icons.gamepad, + ); + + @override + Future connect() async {} +} diff --git a/test/pages/proxy_device_details/vs_calibration_page_test.dart b/test/pages/proxy_device_details/vs_calibration_page_test.dart index c1920e18..90617ff4 100644 --- a/test/pages/proxy_device_details/vs_calibration_page_test.dart +++ b/test/pages/proxy_device_details/vs_calibration_page_test.dart @@ -1,12 +1,18 @@ // The virtual shifting calibrator: the rider pedals, the page puts three grades // on the trainer, and their "too heavy / about right / too light" tunes the // difficulty of every virtual gear on this trainer. +import 'package:bike_control/bluetooth/devices/base_device.dart'; +import 'package:bike_control/bluetooth/devices/gamepad/gamepad_device.dart'; import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart'; import 'package:bike_control/gen/l10n.dart'; import 'package:bike_control/main.dart' show OtherLocalizationsDelegate, installLoggerErrorListener, navigatorKey; import 'package:bike_control/pages/proxy_device_details/vs_calibration_page.dart'; +import 'package:bike_control/services/vs_calibration/calibration_controller_input.dart'; +import 'package:bike_control/services/vs_calibration/vs_calibration_session.dart'; import 'package:bike_control/utils/actions/base_actions.dart'; import 'package:bike_control/utils/core.dart'; +import 'package:bike_control/utils/keymap/buttons.dart'; +import 'package:bike_control/utils/keymap/keymap.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:intl/date_symbol_data_local.dart'; @@ -305,6 +311,90 @@ Future main() async { }); }); + group('the rider\'s controller', () { + const minus = ControllerButton('calMinus'); + + Future started(WidgetTester tester, ProxyDevice device) async { + await pumpPage(tester, VsCalibrationPage(device: device)); + await tapKey(tester, 'vs-cal-start'); + return device.fitnessBike!; + } + + testWidgets('answers while a run is on, with feedback for screen readers', (tester) async { + final device = trainer(); + final def = await started(tester, device); + final input = BaseDevice.inputInterceptor; + expect(input, isNotNull); + + input!.intercept(minus, InGameAction.shiftDown, ButtonTrigger.longPress, isKeyDown: true); + await tester.pump(); + expect(def.difficultyPct.value, 80); + expect( + tester.takeAnnouncements().map((a) => a.message), + contains(AppLocalizations.current.vsCalibrateControllerAnswered(AppLocalizations.current.vsCalibrateTooHeavy)), + ); + expect(find.byKey(const ValueKey('vs-cal-controller-flash')), findsOneWidget); + await tester.pump(const Duration(seconds: 1)); + expect(find.byKey(const ValueKey('vs-cal-controller-flash')), findsNothing); + + await tearDownPage(tester); + }); + + testWidgets('both shifters walk through to the result', (tester) async { + final device = trainer(); + await started(tester, device); + for (var i = 0; i < VsCalibrationSession.grades001Pct.length; i++) { + // The answer debounce runs on the wall clock: let it pass for real. + if (i > 0) await tester.runAsync(() => Future.delayed(CalibrationControllerInput.answerDebounce)); + BaseDevice.inputInterceptor!.interceptChord( + const [ControllerButton('calPlus'), minus], + const [InGameAction.shiftUp, InGameAction.shiftDown], + ); + await tester.pump(const Duration(seconds: 1)); + } + expect(find.byKey(const ValueKey('vs-cal-result')), findsOneWidget); + expect(BaseDevice.inputInterceptor, isNull, reason: 'finishing hands the controller back'); + await tearDownPage(tester); + }); + + testWidgets('stopping hands the controller back', (tester) async { + await started(tester, trainer()); + await tapKey(tester, 'vs-cal-stop'); + expect(BaseDevice.inputInterceptor, isNull); + await tearDownPage(tester); + }); + + testWidgets('leaving the page hands the controller back', (tester) async { + await started(tester, trainer()); + await tearDownPage(tester); + expect(BaseDevice.inputInterceptor, isNull); + }); + + testWidgets('a trainer app connecting hands the controller back', (tester) async { + final device = trainer(); + await started(tester, device); + device.debugSetTrainerAppConnected(true); + await tester.pump(); + expect(BaseDevice.inputInterceptor, isNull); + await tearDownPage(tester); + }); + + testWidgets('the controller scheme is shown next to the answers when a controller is connected', (tester) async { + final controller = GamepadDevice('Pad', id: 'calibration-pad')..isConnected = true; + core.connection.devices.add(controller); + addTearDown(() => core.connection.devices.remove(controller)); + await started(tester, trainer()); + expect(find.byKey(const ValueKey('vs-cal-controller-hints')), findsOneWidget); + await tearDownPage(tester); + }); + + testWidgets('and left out without one', (tester) async { + await started(tester, trainer()); + expect(find.byKey(const ValueKey('vs-cal-controller-hints')), findsNothing); + await tearDownPage(tester); + }); + }); + testWidgets('the on-screen shift buttons move the gear, for mouse and keyboard riders', (tester) async { final device = trainer(); final def = device.fitnessBike!; @@ -357,3 +447,4 @@ Future main() async { await tearDownPage(tester); }); } + diff --git a/test/services/vs_calibration/calibration_controller_input_test.dart b/test/services/vs_calibration/calibration_controller_input_test.dart new file mode 100644 index 00000000..77f4d55e --- /dev/null +++ b/test/services/vs_calibration/calibration_controller_input_test.dart @@ -0,0 +1,132 @@ +import 'package:bike_control/gen/l10n.dart'; +import 'package:bike_control/services/vs_calibration/calibration_controller_input.dart'; +import 'package:bike_control/services/vs_calibration/vs_calibration_session.dart'; +import 'package:bike_control/utils/actions/base_actions.dart'; +import 'package:bike_control/utils/keymap/buttons.dart'; +import 'package:bike_control/utils/keymap/keymap.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The calibrator answered from the rider's own controller: hold shift down = +/// too heavy, hold shift up = too light, both shifters together = about right, +/// and on controllers with navigation buttons left / select / right. +Future main() async { + await AppLocalizations.load(const Locale('en')); + + const plus = ControllerButton('plus'); + const minus = ControllerButton('minus'); + const nav = ControllerButton('nav'); + + late List answers; + late int gear; + late DateTime clock; + late CalibrationControllerInput input; + + setUp(() { + answers = []; + gear = 12; + clock = DateTime(2026, 10, 11, 8); + input = CalibrationControllerInput( + onAnswer: answers.add, + currentGear: () => gear, + restoreGear: (g) => gear = g, + now: () => clock, + ); + }); + + void advance(int ms) => clock = clock.add(Duration(milliseconds: ms)); + + group('two shifters', () { + test('only the shift buttons have their long press claimed', () { + expect(input.claimsLongPress(InGameAction.shiftUp), isTrue); + expect(input.claimsLongPress(InGameAction.shiftDown), isTrue); + expect(input.claimsLongPress(InGameAction.select), isFalse); + expect(input.claimsLongPress(null), isFalse); + }); + + test('holding shift down answers too heavy, and nothing is forwarded', () { + final down = input.intercept(minus, InGameAction.shiftDown, ButtonTrigger.longPress, isKeyDown: true); + expect(down, isA()); + expect(answers, [CalibrationRating.tooHeavy]); + + final up = input.intercept(minus, InGameAction.shiftDown, ButtonTrigger.longPress, isKeyDown: false); + expect(up, isNotNull, reason: 'the release of a claimed hold is consumed too'); + expect(answers, [CalibrationRating.tooHeavy]); + }); + + test('holding shift up answers too light', () { + input.intercept(plus, InGameAction.shiftUp, ButtonTrigger.longPress, isKeyDown: true); + expect(answers, [CalibrationRating.tooLight]); + }); + + test('a short press still shifts', () { + expect(input.intercept(plus, InGameAction.shiftUp, ButtonTrigger.singleClick, isKeyDown: true), isNull); + advance(400); + expect(input.intercept(minus, InGameAction.shiftDown, ButtonTrigger.singleClick, isKeyDown: true), isNull); + expect(answers, isEmpty); + }); + + test('both shifters at once on one controller answer about right', () { + final r = input.interceptChord([plus, minus], [InGameAction.shiftUp, InGameAction.shiftDown]); + expect(r, isNotNull); + expect(answers, [CalibrationRating.aboutRight]); + }); + + test('both shifters on two separate halves answer about right and undo the first shift', () { + // The first half's shift has already gone through by the time the + // second arrives. + expect(input.intercept(plus, InGameAction.shiftUp, ButtonTrigger.singleClick, isKeyDown: true), isNull); + gear = 13; + advance(60); + final second = input.intercept(minus, InGameAction.shiftDown, ButtonTrigger.singleClick, isKeyDown: true); + expect(second, isNotNull, reason: 'the second shift is not forwarded'); + expect(answers, [CalibrationRating.aboutRight]); + expect(gear, 12, reason: 'the gear goes back to where it was before the chord'); + }); + + test('a dedicated front-shift button still shifts the chainring', () { + // The both-shifters chord is caught before the front-shift combo can + // turn it into a chainring change, so a front shift that does arrive + // comes from its own button and is the rider picking a gear. + expect(input.intercept(plus, InGameAction.frontShift, ButtonTrigger.singleClick, isKeyDown: true), isNull); + expect(answers, isEmpty); + }); + + test('the second half of a chord after the window is just a shift', () { + input.intercept(plus, InGameAction.shiftUp, ButtonTrigger.singleClick, isKeyDown: true); + advance(CalibrationControllerInput.chordWindow.inMilliseconds + 50); + expect(input.intercept(minus, InGameAction.shiftDown, ButtonTrigger.singleClick, isKeyDown: true), isNull); + expect(answers, isEmpty); + }); + + test('a chord of anything but the two shifters is left alone', () { + expect(input.interceptChord([plus, nav], [InGameAction.shiftUp, InGameAction.uturn]), isNull); + expect(answers, isEmpty); + }); + }); + + group('navigation buttons', () { + test('left, select and right answer directly and are not forwarded', () { + expect(input.intercept(nav, InGameAction.navigateLeft, ButtonTrigger.singleClick, isKeyDown: true), isNotNull); + advance(1000); + expect(input.intercept(nav, InGameAction.select, ButtonTrigger.singleClick, isKeyDown: true), isNotNull); + advance(1000); + expect(input.intercept(nav, InGameAction.navigateRight, ButtonTrigger.singleClick, isKeyDown: true), isNotNull); + expect(answers, [CalibrationRating.tooHeavy, CalibrationRating.aboutRight, CalibrationRating.tooLight]); + }); + + test('a held navigation button repeating does not ratchet the difficulty', () { + for (var i = 0; i < 4; i++) { + input.intercept(nav, InGameAction.navigateLeft, ButtonTrigger.singleClick, isKeyDown: true); + advance(250); + } + expect(answers, [CalibrationRating.tooHeavy]); + }); + + test('anything else passes through untouched', () { + expect(input.intercept(nav, InGameAction.uturn, ButtonTrigger.singleClick, isKeyDown: true), isNull); + expect(input.intercept(nav, null, ButtonTrigger.singleClick, isKeyDown: true), isNull); + expect(answers, isEmpty); + }); + }); +}