mirror of
https://github.com/jonasbark/swiftcontrol.git
synced 2026-11-29 09:11:17 +01:00
Companion mode: arrange it yourself, full screen, ride mode
Trainer Controls lays its buttons out on a 12-column grid. Edit layout moves and resizes every tile, removes it, and adds buttons or ride data (gear, power, cadence, ratio, ERG target, SIM/ERG as a label, the gear card). A layout is saved per orientation. Ride mode puts a big − and + on the screen with the readings between them; full screen hides everything else. The settings line of Ride's virtual shifting card opens it full screen. Shift actions now go through BikeControl's own virtual shifting when it runs (performInGameAction), like a controller press: ERG steps watts and the shift vibration plays. Before, they went straight to the trainer app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
- Clearer trial: BikeControl warns you (also as a notification) when 10 button presses are left for today, and the trial card shows what you get after the trial. If your trainer app does its own shifting, Ride no longer suggests BikeControl's virtual shifting, and keyboard control is marked optional next to an OpenBikeControl connection.
|
||||
- KICKR Headwind: the fan can follow your heart rate (from a strap connected to BikeControl) as well as your power, and you set where it starts and where it reaches full speed. The page shows the live reading and the speed it gives.
|
||||
- Elite Rizer: incline now works with any smart trainer.
|
||||
- Trainer Controls (Companion mode) is now yours to arrange: move and resize every button, add your gear, power, cadence and ratio, and go full screen. Ride mode puts a big − and + on the screen with your gear between them, and Ride's virtual shifting card opens it with one tap. Its − and + now shift BikeControl's own virtual shifting, with the shift vibration.
|
||||
|
||||
**Fixes**:
|
||||
- Zwift: Ride On Bomb fires on a short press too (Zwift needs the button held for a moment).
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- Klarere Testphase: BikeControl warnt dich (auch als Mitteilung), wenn für heute noch 10 Tastendrücke übrig sind, und die Testphasen-Karte zeigt, was nach der Testphase gilt. Schaltet deine Trainer-App selbst, schlägt „Fahren“ kein virtuelles Schalten von BikeControl mehr vor, und die Tastatursteuerung ist neben einer OpenBikeControl-Verbindung als optional markiert.
|
||||
- KICKR Headwind: Der Ventilator kann deiner Herzfrequenz (von einem mit BikeControl verbundenen Brustgurt) oder deiner Leistung folgen, und du legst fest, ab wann er anläuft und wann er volle Stufe erreicht. Die Seite zeigt den aktuellen Wert und die Stufe, die daraus wird.
|
||||
- Elite Rizer: Die Steigung funktioniert jetzt mit jedem Smart Trainer.
|
||||
- Trainer-Steuerung (Companion Mode) gestaltest du jetzt selbst: Verschieb jede Taste und ändere ihre Größe, füge Gang, Leistung, Trittfrequenz und Übersetzung hinzu und schalte auf Vollbild. Der Fahrmodus zeigt ein großes − und + mit deinem Gang dazwischen, und die Karte für virtuelles Schalten auf Fahren öffnet ihn mit einem Tipp. − und + schalten dort jetzt BikeControls eigenes virtuelles Schalten, mit Vibration beim Schalten.
|
||||
|
||||
**Fixes**:
|
||||
- Zwift: Die Ride-On-Bombe zündet jetzt auch bei kurzem Druck (Zwift braucht die Taste einen Moment lang gedrückt).
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- Una prueba más clara: BikeControl te avisa (también con una notificación) cuando te quedan 10 pulsaciones para hoy, y la tarjeta de prueba muestra lo que tendrás después. Si tu app de entrenamiento cambia de marcha por sí misma, «Rodar» ya no sugiere el cambio virtual de BikeControl, y el control por teclado aparece como opcional junto a una conexión OpenBikeControl.
|
||||
- KICKR Headwind: el ventilador puede seguir tu frecuencia cardíaca (de una banda conectada a BikeControl) o tu potencia, y tú decides dónde arranca y dónde llega a velocidad máxima. La página muestra la lectura actual y la velocidad resultante.
|
||||
- Elite Rizer: la inclinación ahora funciona con cualquier rodillo inteligente.
|
||||
- Ahora organizas tú los Controles del rodillo (modo Companion): mueve y cambia el tamaño de cada botón, añade tu marcha, potencia, cadencia y desarrollo, y ponlo a pantalla completa. El modo pedaleo muestra un − y un + grandes con tu marcha en medio, y la tarjeta de cambio virtual de Rodar lo abre con un toque. Su − y + cambian ahora con el cambio virtual de BikeControl, con la vibración al cambiar.
|
||||
|
||||
**Fixes**:
|
||||
- Zwift: la Bomba Ride On se lanza también con una pulsación corta (Zwift necesita el botón pulsado un momento).
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- Un essai plus clair : BikeControl te prévient (aussi par notification) quand il te reste 10 appuis pour aujourd'hui, et la carte d'essai indique ce que tu auras après l'essai. Si ton app d'entraînement gère elle-même les vitesses, « Rouler » ne propose plus le changement de vitesse virtuel de BikeControl, et le contrôle au clavier est indiqué comme optionnel à côté d'une connexion OpenBikeControl.
|
||||
- KICKR Headwind : le ventilateur peut suivre votre fréquence cardiaque (d'une ceinture connectée à BikeControl) ou votre puissance, et vous réglez où il démarre et où il atteint la pleine vitesse. La page affiche la valeur actuelle et la vitesse qui en découle.
|
||||
- Elite Rizer : l'inclinaison fonctionne maintenant avec n'importe quel home trainer connecté.
|
||||
- Tu organises maintenant toi-même les Commandes du home trainer (mode Companion) : déplace et redimensionne chaque bouton, ajoute ta vitesse, ta puissance, ta cadence et ton développement, et passe en plein écran. Le mode pédalage affiche un grand − et un grand + avec ta vitesse au milieu, et la carte de changement de vitesse virtuel de Rouler l'ouvre d'un geste. Ses − et + passent maintenant par le changement de vitesse virtuel de BikeControl, avec la vibration au changement.
|
||||
|
||||
**Fixes**:
|
||||
- Zwift : la Bombe Ride On part aussi sur un appui court (Zwift a besoin que le bouton reste appuyé un instant).
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- Una prova più chiara: BikeControl ti avvisa (anche con una notifica) quando ti restano 10 pressioni per oggi, e la scheda della prova mostra cosa avrai dopo. Se la tua app di allenamento cambia marcia da sola, «Pedala» non propone più il cambio virtuale di BikeControl, e il controllo da tastiera è indicato come facoltativo accanto a una connessione OpenBikeControl.
|
||||
- KICKR Headwind: il ventilatore può seguire la tua frequenza cardiaca (da una fascia collegata a BikeControl) o la tua potenza, e scegli tu dove parte e dove arriva alla velocità massima. La pagina mostra il valore attuale e la velocità che ne deriva.
|
||||
- Elite Rizer: l'inclinazione ora funziona con qualsiasi rullo smart.
|
||||
- I Controlli del rullo (Companion Mode) ora li organizzi tu: sposta e ridimensiona ogni pulsante, aggiungi rapporto, potenza, cadenza e sviluppo, e passa a schermo intero. La modalità pedalata mostra un − e un + grandi con il rapporto al centro, e la scheda della cambiata virtuale in Pedala la apre con un tocco. I suoi − e + ora usano la cambiata virtuale di BikeControl, con la vibrazione alla cambiata.
|
||||
|
||||
**Fixes**:
|
||||
- Zwift: la Bomba Ride On parte anche con una pressione breve (Zwift vuole il pulsante tenuto premuto per un attimo).
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- Czytelniejszy okres próbny: BikeControl ostrzega cię (także powiadomieniem), gdy zostało 10 naciśnięć na dziś, a karta okresu próbnego pokazuje, co zostaje po nim. Jeśli twoja aplikacja treningowa sama zmienia biegi, „Jazda” nie proponuje już wirtualnej zmiany biegów BikeControl, a sterowanie klawiaturą jest oznaczone jako opcjonalne obok połączenia OpenBikeControl.
|
||||
- KICKR Headwind: wentylator może podążać za tętnem (z pasa połączonego z BikeControl) lub mocą, a ty ustawiasz, kiedy rusza i kiedy osiąga pełną prędkość. Strona pokazuje bieżący odczyt i wynikającą z niego prędkość.
|
||||
- Elite Rizer: nachylenie działa teraz z każdym trenażerem smart.
|
||||
- Sterowanie trenażerem (Companion Mode) układasz teraz sam: przesuwaj i zmieniaj rozmiar każdego przycisku, dodaj bieg, moc, kadencję i przełożenie, i włącz pełny ekran. Tryb jazdy pokazuje duże − i + z biegiem pośrodku, a karta wirtualnej zmiany biegów w Jeździe otwiera go jednym dotknięciem. Jego − i + zmieniają teraz biegi przez wirtualną zmianę biegów BikeControl, z wibracją przy zmianie.
|
||||
|
||||
**Fixes**:
|
||||
- Zwift: Bomba Ride On odpala się też po krótkim naciśnięciu (Zwift wymaga chwilowego przytrzymania przycisku).
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- 更清晰的试用:今天还剩 10 次按键时,BikeControl 会提醒你(也会发送通知),试用卡片会显示试用结束后的额度。如果你的训练 App 自己负责换挡,“骑行”页不再推荐 BikeControl 的虚拟变速;在 OpenBikeControl 连接旁,键盘控制会标为可选。
|
||||
- KICKR Headwind:风扇可以跟随你的心率(来自连接到 BikeControl 的心率带)或功率,并由你设置启动点和全速点。页面会显示实时读数及对应的风扇速度。
|
||||
- Elite Rizer:坡度模拟现在适用于任何智能骑行台。
|
||||
- 骑行台控制(Companion 模式)现在可以自由布局:移动每个按钮并调整大小,添加档位、功率、踏频和传动比,并可全屏显示。骑行模式在屏幕上显示大号 − 和 +,中间是你的档位;在“骑行”页的虚拟变速卡片上轻点一下即可打开。它的 − 和 + 现在使用 BikeControl 自己的虚拟变速,换挡时会振动。
|
||||
|
||||
**Fixes**:
|
||||
- Zwift:短按也能发出 Ride On 炸弹(Zwift 需要按住按键片刻)。
|
||||
|
||||
@@ -3138,5 +3138,23 @@
|
||||
"connectErrorPairing": "Das Koppeln hat nicht geklappt. Entferne das Gerät in den Bluetooth-Einstellungen und versuch es erneut.",
|
||||
"connectErrorDropped": "Die Verbindung ist beim Aufbau abgebrochen.",
|
||||
"connectErrorUnknown": "Etwas ist schiefgelaufen.",
|
||||
"connectErrorRetrying": "BikeControl versucht es weiter."
|
||||
"connectErrorRetrying": "BikeControl versucht es weiter.",
|
||||
"companionEditLayout": "Layout bearbeiten",
|
||||
"companionAddTile": "Kachel hinzufügen",
|
||||
"companionLayouts": "Layouts",
|
||||
"companionLayoutStandard": "Standard",
|
||||
"companionLayoutStandardBody": "Alle Tasten deiner Trainings-App",
|
||||
"companionLayoutRideMode": "Fahrmodus",
|
||||
"companionLayoutRideModeBody": "Großes − und + mit deinem Gang dazwischen",
|
||||
"companionFullScreen": "Vollbild",
|
||||
"companionExitFullScreen": "Vollbild beenden",
|
||||
"companionEditHint": "Zieh eine Kachel, um sie zu verschieben, und ihre Ecke, um die Größe zu ändern.",
|
||||
"companionAddButtons": "Tasten",
|
||||
"companionAddRideData": "Fahrdaten",
|
||||
"companionRideDataHint": "Fahrdaten erscheinen, während BikeControl die Gänge deines Trainers schaltet.",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"companionTileRideCard": "Gang-Karte",
|
||||
"companionRemoveTile": "{name} entfernen",
|
||||
"companionRideLine": "Mit großen Tasten auf diesem Bildschirm schalten",
|
||||
"companionAllAdded": "Alles ist schon auf der Seite."
|
||||
}
|
||||
|
||||
@@ -3655,5 +3655,26 @@
|
||||
"connectErrorUnknown": "Something went wrong.",
|
||||
"@connectErrorUnknown": {"description": "Why connecting to a Bluetooth device failed, after \"Connection failed: <device> - \" in the alert and Activity log."},
|
||||
"connectErrorRetrying": "BikeControl keeps trying.",
|
||||
"@connectErrorRetrying": {"description": "Added after the reason a Bluetooth connect failed, when BikeControl has scheduled another attempt."}
|
||||
"@connectErrorRetrying": {"description": "Added after the reason a Bluetooth connect failed, when BikeControl has scheduled another attempt."},
|
||||
"companionEditLayout": "Edit layout",
|
||||
"companionAddTile": "Add tile",
|
||||
"companionLayouts": "Layouts",
|
||||
"companionLayoutStandard": "Standard",
|
||||
"companionLayoutStandardBody": "Every button of your trainer app",
|
||||
"companionLayoutRideMode": "Ride mode",
|
||||
"companionLayoutRideModeBody": "Big − and + with your gear between them",
|
||||
"companionFullScreen": "Full screen",
|
||||
"companionExitFullScreen": "Exit full screen",
|
||||
"companionEditHint": "Drag a tile to move it, drag its corner to resize it.",
|
||||
"companionAddButtons": "Buttons",
|
||||
"companionAddRideData": "Ride data",
|
||||
"companionRideDataHint": "Ride data shows while BikeControl shifts your trainer's gears.",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"@companionTileMode": {"description": "Companion page: the tile that shows the trainer's mode as a label (never a switch)."},
|
||||
"companionTileRideCard": "Gear card",
|
||||
"companionRemoveTile": "Remove {name}",
|
||||
"@companionRemoveTile": {"description": "Companion page, edit mode: accessibility label of a tile's remove button.", "placeholders": {"name": {"type": "String"}}},
|
||||
"companionRideLine": "Shift with big buttons on this screen",
|
||||
"@companionRideLine": {"description": "Ride tab: line at the foot of the virtual shifting card; its link opens the companion page full screen."},
|
||||
"companionAllAdded": "Everything is on the page already."
|
||||
}
|
||||
|
||||
@@ -3138,5 +3138,23 @@
|
||||
"connectErrorPairing": "El emparejamiento no funcionó. Elimina el dispositivo en los ajustes de Bluetooth e inténtalo de nuevo.",
|
||||
"connectErrorDropped": "La conexión se cortó al conectar.",
|
||||
"connectErrorUnknown": "Algo salió mal.",
|
||||
"connectErrorRetrying": "BikeControl sigue intentándolo."
|
||||
"connectErrorRetrying": "BikeControl sigue intentándolo.",
|
||||
"companionEditLayout": "Editar diseño",
|
||||
"companionAddTile": "Añadir mosaico",
|
||||
"companionLayouts": "Diseños",
|
||||
"companionLayoutStandard": "Estándar",
|
||||
"companionLayoutStandardBody": "Todos los botones de tu app de entrenamiento",
|
||||
"companionLayoutRideMode": "Modo pedaleo",
|
||||
"companionLayoutRideModeBody": "− y + grandes con tu marcha en medio",
|
||||
"companionFullScreen": "Pantalla completa",
|
||||
"companionExitFullScreen": "Salir de pantalla completa",
|
||||
"companionEditHint": "Arrastra un mosaico para moverlo y su esquina para cambiar su tamaño.",
|
||||
"companionAddButtons": "Botones",
|
||||
"companionAddRideData": "Datos de la sesión",
|
||||
"companionRideDataHint": "Los datos de la sesión aparecen mientras BikeControl cambia las marchas de tu rodillo.",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"companionTileRideCard": "Tarjeta de marcha",
|
||||
"companionRemoveTile": "Quitar {name}",
|
||||
"companionRideLine": "Cambia de marcha con botones grandes en esta pantalla",
|
||||
"companionAllAdded": "Ya está todo en la página."
|
||||
}
|
||||
|
||||
@@ -3138,5 +3138,23 @@
|
||||
"connectErrorPairing": "L'appairage n'a pas fonctionné. Supprime l'appareil dans les réglages Bluetooth et réessaie.",
|
||||
"connectErrorDropped": "La connexion s'est coupée pendant l'établissement.",
|
||||
"connectErrorUnknown": "Quelque chose s'est mal passé.",
|
||||
"connectErrorRetrying": "BikeControl continue d'essayer."
|
||||
"connectErrorRetrying": "BikeControl continue d'essayer.",
|
||||
"companionEditLayout": "Modifier la disposition",
|
||||
"companionAddTile": "Ajouter une tuile",
|
||||
"companionLayouts": "Dispositions",
|
||||
"companionLayoutStandard": "Standard",
|
||||
"companionLayoutStandardBody": "Tous les boutons de votre app d'entraînement",
|
||||
"companionLayoutRideMode": "Mode pédalage",
|
||||
"companionLayoutRideModeBody": "Grands − et + avec votre vitesse au milieu",
|
||||
"companionFullScreen": "Plein écran",
|
||||
"companionExitFullScreen": "Quitter le plein écran",
|
||||
"companionEditHint": "Faites glisser une tuile pour la déplacer, et son coin pour la redimensionner.",
|
||||
"companionAddButtons": "Boutons",
|
||||
"companionAddRideData": "Données de sortie",
|
||||
"companionRideDataHint": "Les données de sortie s'affichent tant que BikeControl change les vitesses de votre home trainer.",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"companionTileRideCard": "Carte de vitesse",
|
||||
"companionRemoveTile": "Retirer {name}",
|
||||
"companionRideLine": "Changez de vitesse avec de grands boutons sur cet écran",
|
||||
"companionAllAdded": "Tout est déjà sur la page."
|
||||
}
|
||||
|
||||
@@ -3138,5 +3138,23 @@
|
||||
"connectErrorPairing": "L'abbinamento non è riuscito. Rimuovi il dispositivo nelle impostazioni Bluetooth e riprova.",
|
||||
"connectErrorDropped": "La connessione si è interrotta durante il collegamento.",
|
||||
"connectErrorUnknown": "Qualcosa è andato storto.",
|
||||
"connectErrorRetrying": "BikeControl continua a provare."
|
||||
"connectErrorRetrying": "BikeControl continua a provare.",
|
||||
"companionEditLayout": "Modifica layout",
|
||||
"companionAddTile": "Aggiungi riquadro",
|
||||
"companionLayouts": "Layout",
|
||||
"companionLayoutStandard": "Standard",
|
||||
"companionLayoutStandardBody": "Tutti i pulsanti della tua app di allenamento",
|
||||
"companionLayoutRideMode": "Modalità pedalata",
|
||||
"companionLayoutRideModeBody": "− e + grandi con il rapporto al centro",
|
||||
"companionFullScreen": "Schermo intero",
|
||||
"companionExitFullScreen": "Esci da schermo intero",
|
||||
"companionEditHint": "Trascina un riquadro per spostarlo e il suo angolo per ridimensionarlo.",
|
||||
"companionAddButtons": "Pulsanti",
|
||||
"companionAddRideData": "Dati di pedalata",
|
||||
"companionRideDataHint": "I dati di pedalata compaiono mentre BikeControl cambia i rapporti del tuo rullo.",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"companionTileRideCard": "Scheda rapporto",
|
||||
"companionRemoveTile": "Rimuovi {name}",
|
||||
"companionRideLine": "Cambia rapporto con pulsanti grandi su questo schermo",
|
||||
"companionAllAdded": "È già tutto sulla pagina."
|
||||
}
|
||||
|
||||
@@ -3138,5 +3138,23 @@
|
||||
"connectErrorPairing": "Parowanie nie powiodło się. Usuń urządzenie w ustawieniach Bluetooth i spróbuj ponownie.",
|
||||
"connectErrorDropped": "Połączenie zerwało się podczas łączenia.",
|
||||
"connectErrorUnknown": "Coś poszło nie tak.",
|
||||
"connectErrorRetrying": "BikeControl próbuje dalej."
|
||||
"connectErrorRetrying": "BikeControl próbuje dalej.",
|
||||
"companionEditLayout": "Edytuj układ",
|
||||
"companionAddTile": "Dodaj kafelek",
|
||||
"companionLayouts": "Układy",
|
||||
"companionLayoutStandard": "Standardowy",
|
||||
"companionLayoutStandardBody": "Wszystkie przyciski Twojej aplikacji treningowej",
|
||||
"companionLayoutRideMode": "Tryb jazdy",
|
||||
"companionLayoutRideModeBody": "Duże − i + z biegiem pośrodku",
|
||||
"companionFullScreen": "Pełny ekran",
|
||||
"companionExitFullScreen": "Zamknij pełny ekran",
|
||||
"companionEditHint": "Przeciągnij kafelek, aby go przesunąć, a jego róg, aby zmienić rozmiar.",
|
||||
"companionAddButtons": "Przyciski",
|
||||
"companionAddRideData": "Dane jazdy",
|
||||
"companionRideDataHint": "Dane jazdy pojawiają się, gdy BikeControl zmienia biegi Twojego trenażera.",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"companionTileRideCard": "Karta biegu",
|
||||
"companionRemoveTile": "Usuń {name}",
|
||||
"companionRideLine": "Zmieniaj biegi dużymi przyciskami na tym ekranie",
|
||||
"companionAllAdded": "Wszystko jest już na stronie."
|
||||
}
|
||||
|
||||
@@ -4312,5 +4312,23 @@
|
||||
"connectErrorPairing": "配对失败。请在蓝牙设置中移除该设备后重试。",
|
||||
"connectErrorDropped": "连接过程中断开。",
|
||||
"connectErrorUnknown": "出了点问题。",
|
||||
"connectErrorRetrying": "BikeControl 会继续尝试。"
|
||||
"connectErrorRetrying": "BikeControl 会继续尝试。",
|
||||
"companionEditLayout": "编辑布局",
|
||||
"companionAddTile": "添加图块",
|
||||
"companionLayouts": "布局",
|
||||
"companionLayoutStandard": "标准",
|
||||
"companionLayoutStandardBody": "训练应用的所有按钮",
|
||||
"companionLayoutRideMode": "骑行模式",
|
||||
"companionLayoutRideModeBody": "大号 − 和 +,中间显示档位",
|
||||
"companionFullScreen": "全屏",
|
||||
"companionExitFullScreen": "退出全屏",
|
||||
"companionEditHint": "拖动图块可移动,拖动其角可调整大小。",
|
||||
"companionAddButtons": "按钮",
|
||||
"companionAddRideData": "骑行数据",
|
||||
"companionRideDataHint": "BikeControl 为你的骑行台换挡时显示骑行数据。",
|
||||
"companionTileMode": "SIM / ERG",
|
||||
"companionTileRideCard": "档位卡片",
|
||||
"companionRemoveTile": "移除 {name}",
|
||||
"companionRideLine": "在此屏幕上用大按钮换挡",
|
||||
"companionAllAdded": "所有内容都已在页面上。"
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
234
lib/pages/companion/companion_canvas.dart
Normal file
234
lib/pages/companion/companion_canvas.dart
Normal file
@@ -0,0 +1,234 @@
|
||||
import 'package:bike_control/pages/companion/companion_layout.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
||||
|
||||
/// Lays [layout]'s tiles out on its grid, [rowHeight] tall per row and the
|
||||
/// full width across. While [editing], each tile can be dragged to another
|
||||
/// cell, resized from its corner handle and removed; every change that fits
|
||||
/// goes to [onChanged]. Outside editing the tiles are just their content.
|
||||
class CompanionCanvas extends StatefulWidget {
|
||||
const CompanionCanvas({
|
||||
super.key,
|
||||
required this.layout,
|
||||
required this.rowHeight,
|
||||
required this.editing,
|
||||
required this.onChanged,
|
||||
required this.tileBuilder,
|
||||
required this.removeLabel,
|
||||
this.gap = 8,
|
||||
});
|
||||
|
||||
final CompanionLayout layout;
|
||||
final double rowHeight;
|
||||
final bool editing;
|
||||
final ValueChanged<CompanionLayout> onChanged;
|
||||
final Widget Function(BuildContext context, CompanionTile tile) tileBuilder;
|
||||
|
||||
/// The remove button's accessibility label for [tile].
|
||||
final String Function(CompanionTile tile) removeLabel;
|
||||
|
||||
/// Space between tiles.
|
||||
final double gap;
|
||||
|
||||
@override
|
||||
State<CompanionCanvas> createState() => _CompanionCanvasState();
|
||||
}
|
||||
|
||||
class _CompanionCanvasState extends State<CompanionCanvas> {
|
||||
/// The tile being dragged or resized, where it started and how far the
|
||||
/// finger has gone since.
|
||||
String? _activeId;
|
||||
CompanionTile? _start;
|
||||
Offset _delta = Offset.zero;
|
||||
bool _resizing = false;
|
||||
|
||||
/// The corner of a tile that resizes it rather than moving it.
|
||||
static const double _handle = 44;
|
||||
|
||||
/// One drag recognizer per tile: a drag that starts in its bottom-right
|
||||
/// corner resizes, any other moves. (A second recognizer on the handle
|
||||
/// lost the gesture arena to the tile's.)
|
||||
void _begin(CompanionTile tile, Offset local, Size size) {
|
||||
setState(() {
|
||||
_activeId = tile.id;
|
||||
_start = tile;
|
||||
_delta = Offset.zero;
|
||||
_resizing = local.dx >= size.width - _handle && local.dy >= size.height - _handle;
|
||||
});
|
||||
}
|
||||
|
||||
void _end() => setState(() {
|
||||
_activeId = null;
|
||||
_start = null;
|
||||
});
|
||||
|
||||
void _drag(Offset delta, double cellWidth) {
|
||||
final resize = _resizing;
|
||||
final start = _start;
|
||||
if (start == null) return;
|
||||
_delta += delta;
|
||||
final dc = (_delta.dx / cellWidth).round();
|
||||
final dr = (_delta.dy / widget.rowHeight).round();
|
||||
final next = resize
|
||||
? widget.layout.resized(start.id, w: start.w + dc, h: start.h + dr)
|
||||
: widget.layout.moved(start.id, col: start.col + dc, row: start.row + dr);
|
||||
if (next == null) return;
|
||||
final now = widget.layout.tile(start.id);
|
||||
if (next.tile(start.id) == now) return;
|
||||
widget.onChanged(next);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cs = Theme.of(context).colorScheme;
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final cellWidth = width / widget.layout.columns;
|
||||
final rows = widget.layout.usedRows + (widget.editing ? 2 : 0);
|
||||
final half = widget.gap / 2;
|
||||
return SizedBox(
|
||||
width: width,
|
||||
height: rows * widget.rowHeight,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
if (widget.editing)
|
||||
Positioned.fill(
|
||||
child: CustomPaint(
|
||||
key: const ValueKey('companion-grid'),
|
||||
painter: _GridPainter(
|
||||
columns: widget.layout.columns,
|
||||
cellWidth: cellWidth,
|
||||
rowHeight: widget.rowHeight,
|
||||
color: cs.border,
|
||||
),
|
||||
),
|
||||
),
|
||||
for (final tile in widget.layout.tiles)
|
||||
Positioned(
|
||||
key: ValueKey('companion-tile-${tile.id}'),
|
||||
left: tile.col * cellWidth + half,
|
||||
top: tile.row * widget.rowHeight + half,
|
||||
width: tile.w * cellWidth - widget.gap,
|
||||
height: tile.h * widget.rowHeight - widget.gap,
|
||||
child: widget.editing ? _editable(context, tile, cellWidth) : widget.tileBuilder(context, tile),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _editable(BuildContext context, CompanionTile tile, double cellWidth) {
|
||||
final cs = Theme.of(context).colorScheme;
|
||||
final active = _activeId == tile.id;
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) => GestureDetector(
|
||||
key: ValueKey('companion-move-${tile.id}'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanDown: (d) => _begin(tile, d.localPosition, constraints.biggest),
|
||||
onPanUpdate: (d) => _drag(d.delta, cellWidth),
|
||||
onPanEnd: (_) => _end(),
|
||||
onPanCancel: _end,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: AnimatedOpacity(
|
||||
duration: const Duration(milliseconds: 120),
|
||||
opacity: active ? 0.7 : 0.9,
|
||||
child: widget.tileBuilder(context, tile),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: active ? cs.primary : cs.mutedForeground.withValues(alpha: 0.6),
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// The handles sit inside the tile: a touch outside its box never
|
||||
// reaches it.
|
||||
PositionedDirectional(
|
||||
top: 0,
|
||||
end: 0,
|
||||
child: Semantics(
|
||||
button: true,
|
||||
label: widget.removeLabel(tile),
|
||||
child: GestureDetector(
|
||||
key: ValueKey('companion-remove-${tile.id}'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => widget.onChanged(widget.layout.removed(tile.id)),
|
||||
child: SizedBox(
|
||||
width: 36,
|
||||
height: 36,
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: 26,
|
||||
height: 26,
|
||||
decoration: BoxDecoration(color: cs.destructive, shape: BoxShape.circle),
|
||||
child: Icon(LucideIcons.x, size: 16, color: cs.background),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: IgnorePointer(
|
||||
key: ValueKey('companion-resize-${tile.id}'),
|
||||
child: SizedBox(
|
||||
width: _handle,
|
||||
height: _handle,
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: 26,
|
||||
height: 26,
|
||||
decoration: BoxDecoration(color: cs.primary, shape: BoxShape.circle),
|
||||
child: Icon(LucideIcons.moveDiagonal2, size: 14, color: cs.primaryForeground),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Faint dots at the cell corners while editing, so the snap is visible.
|
||||
class _GridPainter extends CustomPainter {
|
||||
_GridPainter({required this.columns, required this.cellWidth, required this.rowHeight, required this.color});
|
||||
|
||||
final int columns;
|
||||
final double cellWidth;
|
||||
final double rowHeight;
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()..color = color;
|
||||
for (var y = 0.0; y <= size.height + 0.5; y += rowHeight) {
|
||||
for (var c = 0; c <= columns; c++) {
|
||||
canvas.drawCircle(Offset(c * cellWidth, y), 1.5, paint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_GridPainter old) =>
|
||||
old.columns != columns || old.cellWidth != cellWidth || old.rowHeight != rowHeight || old.color != color;
|
||||
}
|
||||
233
lib/pages/companion/companion_info_tile.dart
Normal file
233
lib/pages/companion/companion_info_tile.dart
Normal file
@@ -0,0 +1,233 @@
|
||||
import 'package:bike_control/gen/l10n.dart';
|
||||
import 'package:bike_control/pages/companion/companion_layout.dart';
|
||||
import 'package:bike_control/services/overlay/overlay_state.dart';
|
||||
import 'package:bike_control/utils/core.dart';
|
||||
import 'package:bike_control/utils/gear_readout.dart';
|
||||
import 'package:bike_control/widgets/overlay/trainer_overlay_view.dart';
|
||||
import 'package:bike_control/widgets/ui/app_theme.dart';
|
||||
import 'package:bike_control/widgets/ui/colors.dart';
|
||||
import 'package:bike_control/widgets/ui/type_scale.dart';
|
||||
import 'package:prop/emulators/definitions/fitness_bike_definition.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
||||
|
||||
/// The name a ride-data tile goes by in the add list.
|
||||
String companionTileName(AppLocalizations l, CompanionTileKind kind) => switch (kind) {
|
||||
CompanionTileKind.action => '',
|
||||
CompanionTileKind.gear => l.rideGear,
|
||||
CompanionTileKind.power => l.sensorQuantityPower,
|
||||
CompanionTileKind.cadence => l.sensorQuantityCadence,
|
||||
CompanionTileKind.ratio => l.rideRatio,
|
||||
CompanionTileKind.ergTarget => l.overlayFieldErgTarget,
|
||||
CompanionTileKind.mode => l.companionTileMode,
|
||||
CompanionTileKind.rideCard => l.companionTileRideCard,
|
||||
};
|
||||
|
||||
IconData companionTileIcon(CompanionTileKind kind) => switch (kind) {
|
||||
CompanionTileKind.action => LucideIcons.squareMousePointer,
|
||||
CompanionTileKind.gear => LucideIcons.cog,
|
||||
CompanionTileKind.power => LucideIcons.zap,
|
||||
CompanionTileKind.cadence => LucideIcons.rotateCw,
|
||||
CompanionTileKind.ratio => LucideIcons.chartSpline,
|
||||
CompanionTileKind.ergTarget => LucideIcons.target,
|
||||
CompanionTileKind.mode => LucideIcons.toggleLeft,
|
||||
CompanionTileKind.rideCard => LucideIcons.panelTop,
|
||||
};
|
||||
|
||||
/// A ride-data tile: one reading of [definition], its label above and the
|
||||
/// value as big as the tile allows. Nothing on it can be tapped. With no
|
||||
/// virtual shifting session it shows "--".
|
||||
class CompanionInfoTile extends StatelessWidget {
|
||||
const CompanionInfoTile({super.key, required this.kind, required this.definition});
|
||||
|
||||
final CompanionTileKind kind;
|
||||
final FitnessBikeDefinition? definition;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final def = definition;
|
||||
if (kind == CompanionTileKind.rideCard) {
|
||||
return def == null ? _frame(context, companionTileName(context.l, kind), '--') : _RideCard(definition: def);
|
||||
}
|
||||
if (def == null) return _frame(context, _label(context, null), '--');
|
||||
return AnimatedBuilder(
|
||||
animation: Listenable.merge([
|
||||
def.currentGear,
|
||||
def.trainerMode,
|
||||
def.ergTargetPower,
|
||||
def.powerW,
|
||||
def.cadenceRpm,
|
||||
def.gearRatio,
|
||||
def.frontRing,
|
||||
]),
|
||||
builder: (context, _) => _frame(context, _label(context, def), _value(def)),
|
||||
);
|
||||
}
|
||||
|
||||
String _label(BuildContext context, FitnessBikeDefinition? def) {
|
||||
final l = context.l;
|
||||
final erg = def?.trainerMode.value == TrainerMode.ergMode;
|
||||
return switch (kind) {
|
||||
// The mode rides along with the gear: "GEAR · SIM", or "ERG" while the
|
||||
// number is the target.
|
||||
CompanionTileKind.gear => erg ? l.ergMode : '${l.rideGear} · ${l.simMode}',
|
||||
_ => companionTileName(l, kind),
|
||||
};
|
||||
}
|
||||
|
||||
String _value(FitnessBikeDefinition def) {
|
||||
final erg = def.trainerMode.value == TrainerMode.ergMode;
|
||||
final target = def.ergTargetPower.value;
|
||||
return switch (kind) {
|
||||
CompanionTileKind.gear =>
|
||||
erg
|
||||
? (target == null ? '--' : '$target W')
|
||||
: formatGearReadout(
|
||||
currentGear: def.currentGear.value,
|
||||
maxGear: def.maxGear,
|
||||
frontShiftEnabled: def.frontShiftEnabled,
|
||||
largeRing: def.frontRing.value == FrontRing.large,
|
||||
),
|
||||
CompanionTileKind.power => def.powerW.value == null ? '-- W' : '${def.powerW.value} W',
|
||||
CompanionTileKind.cadence => def.cadenceRpm.value == null ? '-- rpm' : '${def.cadenceRpm.value} rpm',
|
||||
CompanionTileKind.ratio => erg ? '--' : formatGearRatio(def.gearRatio.value),
|
||||
CompanionTileKind.ergTarget => target == null ? '--' : '$target W',
|
||||
CompanionTileKind.mode => erg ? 'ERG' : 'SIM',
|
||||
_ => '',
|
||||
};
|
||||
}
|
||||
|
||||
Widget _frame(BuildContext context, String label, String value) {
|
||||
final cs = Theme.of(context).colorScheme;
|
||||
return Semantics(
|
||||
container: true,
|
||||
label: '$label $value',
|
||||
excludeSemantics: true,
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: cs.card,
|
||||
borderRadius: BorderRadius.circular(BkComponentThemes.cardRadius),
|
||||
boxShadow: bkCardShadow(context),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(10, 6, 10, 6),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// A narrow tile shrinks the label rather than cut "GEAR · SIM".
|
||||
FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Text(
|
||||
label.toUpperCase(),
|
||||
maxLines: 1,
|
||||
textAlign: TextAlign.center,
|
||||
style: context.typography.caption.copyWith(
|
||||
color: cs.mutedForeground,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.8,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: FittedBox(
|
||||
fit: BoxFit.contain,
|
||||
child: Text(
|
||||
value,
|
||||
key: ValueKey('companion-info-${kind.name}'),
|
||||
style: kind == CompanionTileKind.gear
|
||||
? BkNumerals.gear(64, color: cs.foreground, height: 1.0)
|
||||
: BkNumerals.display(56, color: cs.foreground, height: 1.0),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The gear overlay's card, live, scaled to its tile. The −/+ stay off: the
|
||||
/// page has its own buttons.
|
||||
class _RideCard extends StatefulWidget {
|
||||
const _RideCard({required this.definition});
|
||||
|
||||
final FitnessBikeDefinition definition;
|
||||
|
||||
@override
|
||||
State<_RideCard> createState() => _RideCardState();
|
||||
}
|
||||
|
||||
class _RideCardState extends State<_RideCard> {
|
||||
late final ValueNotifier<TrainerOverlayState> _state = ValueNotifier(_read());
|
||||
late Listenable _live;
|
||||
|
||||
FitnessBikeDefinition get _def => widget.definition;
|
||||
|
||||
Listenable _listenTo(FitnessBikeDefinition d) => Listenable.merge([
|
||||
d.currentGear,
|
||||
d.gearRatio,
|
||||
d.trainerMode,
|
||||
d.ergTargetPower,
|
||||
d.powerW,
|
||||
d.cadenceRpm,
|
||||
d.frontRing,
|
||||
]);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_live = _listenTo(_def)..addListener(_refresh);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_RideCard oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.definition != widget.definition) {
|
||||
_live.removeListener(_refresh);
|
||||
_live = _listenTo(_def)..addListener(_refresh);
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_live.removeListener(_refresh);
|
||||
_state.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
TrainerOverlayState _read() => TrainerOverlayState(
|
||||
gear: _def.currentGear.value,
|
||||
maxGear: _def.maxGear,
|
||||
gearRatio: _def.gearRatio.value,
|
||||
mode: _def.trainerMode.value,
|
||||
powerW: _def.powerW.value,
|
||||
cadenceRpm: _def.cadenceRpm.value,
|
||||
ergTargetW: _def.ergTargetPower.value,
|
||||
fields: {...core.settings.getOverlayFields()}..remove(OverlayField.controls),
|
||||
frontShiftEnabled: _def.frontShiftEnabled,
|
||||
frontRingLarge: _def.frontRing.value == FrontRing.large,
|
||||
);
|
||||
|
||||
void _refresh() => _state.value = _read();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: FittedBox(
|
||||
fit: BoxFit.contain,
|
||||
child: ValueListenableBuilder<TrainerOverlayState>(
|
||||
valueListenable: _state,
|
||||
builder: (context, s, child) =>
|
||||
SizedBox(width: TrainerOverlayView.fitWindowSizeOf(context, s, drag: false).width, child: child),
|
||||
child: TrainerOverlayView(state: _state, pill: true),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension on BuildContext {
|
||||
AppLocalizations get l => AppLocalizations.of(this);
|
||||
}
|
||||
401
lib/pages/companion/companion_layout.dart
Normal file
401
lib/pages/companion/companion_layout.dart
Normal file
@@ -0,0 +1,401 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:bike_control/utils/keymap/buttons.dart';
|
||||
|
||||
/// What a tile on the companion page shows.
|
||||
enum CompanionTileKind {
|
||||
/// A button that presses [CompanionTile.action].
|
||||
action,
|
||||
|
||||
/// The gear in SIM (the target watts in ERG), with the mode as its label.
|
||||
gear,
|
||||
power,
|
||||
cadence,
|
||||
ratio,
|
||||
ergTarget,
|
||||
|
||||
/// SIM or ERG, as a label — never a switch, so a missed tap can't change
|
||||
/// the trainer's mode mid-effort.
|
||||
mode,
|
||||
|
||||
/// The gear overlay's card: gear, mode and the readings in one.
|
||||
rideCard;
|
||||
|
||||
bool get isRideData => this != action;
|
||||
|
||||
static CompanionTileKind? fromName(Object? name) {
|
||||
for (final k in values) {
|
||||
if (k.name == name) return k;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// One tile, placed on the grid in whole cells.
|
||||
class CompanionTile {
|
||||
const CompanionTile({
|
||||
required this.id,
|
||||
required this.kind,
|
||||
this.action,
|
||||
required this.col,
|
||||
required this.row,
|
||||
required this.w,
|
||||
required this.h,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final CompanionTileKind kind;
|
||||
final InGameAction? action;
|
||||
final int col;
|
||||
final int row;
|
||||
final int w;
|
||||
final int h;
|
||||
|
||||
int get right => col + w;
|
||||
int get bottom => row + h;
|
||||
|
||||
bool overlaps(CompanionTile other) =>
|
||||
col < other.right && other.col < right && row < other.bottom && other.row < bottom;
|
||||
|
||||
CompanionTile copyWith({int? col, int? row, int? w, int? h}) => CompanionTile(
|
||||
id: id,
|
||||
kind: kind,
|
||||
action: action,
|
||||
col: col ?? this.col,
|
||||
row: row ?? this.row,
|
||||
w: w ?? this.w,
|
||||
h: h ?? this.h,
|
||||
);
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'id': id,
|
||||
'kind': kind.name,
|
||||
if (action != null) 'action': action!.name,
|
||||
'col': col,
|
||||
'row': row,
|
||||
'w': w,
|
||||
'h': h,
|
||||
};
|
||||
|
||||
static CompanionTile? fromJson(Object? json) {
|
||||
if (json is! Map) return null;
|
||||
final kind = CompanionTileKind.fromName(json['kind']);
|
||||
if (kind == null) return null;
|
||||
InGameAction? action;
|
||||
if (kind == CompanionTileKind.action) {
|
||||
action = InGameAction.values.where((a) => a.name == json['action']).firstOrNull;
|
||||
if (action == null) return null;
|
||||
}
|
||||
final id = json['id'];
|
||||
final col = json['col'];
|
||||
final row = json['row'];
|
||||
final w = json['w'];
|
||||
final h = json['h'];
|
||||
if (id is! String || col is! int || row is! int || w is! int || h is! int) return null;
|
||||
if (col < 0 || row < 0 || w < 1 || h < 1 || col + w > CompanionLayout.gridColumns) return null;
|
||||
return CompanionTile(id: id, kind: kind, action: action, col: col, row: row, w: w, h: h);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is CompanionTile &&
|
||||
other.id == id &&
|
||||
other.kind == kind &&
|
||||
other.action == action &&
|
||||
other.col == col &&
|
||||
other.row == row &&
|
||||
other.w == w &&
|
||||
other.h == h;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(id, kind, action, col, row, w, h);
|
||||
|
||||
@override
|
||||
String toString() => 'CompanionTile($id, ${action?.name ?? kind.name}, $col,$row ${w}x$h)';
|
||||
}
|
||||
|
||||
/// The companion page's layout for one orientation: tiles on a grid of
|
||||
/// [columns] × [rows] cells that fills the screen. Tiles snap to whole cells
|
||||
/// and never overlap. A layout taller than [rows] scrolls.
|
||||
class CompanionLayout {
|
||||
CompanionLayout({required this.landscape, required List<CompanionTile> tiles}) : tiles = List.unmodifiable(tiles);
|
||||
|
||||
static const int gridColumns = 12;
|
||||
static const int gridRows = 12;
|
||||
|
||||
/// The smallest a tile can be resized to, in cells.
|
||||
static const int minSpan = 2;
|
||||
|
||||
/// How far down a tile may go, so a runaway drag can't lose it.
|
||||
static const int maxRows = 60;
|
||||
|
||||
final bool landscape;
|
||||
final List<CompanionTile> tiles;
|
||||
|
||||
int get columns => gridColumns;
|
||||
int get rows => gridRows;
|
||||
|
||||
/// The rows the tiles take up, at least one screen.
|
||||
int get usedRows => tiles.fold(rows, (m, t) => math.max(m, t.bottom));
|
||||
|
||||
CompanionTile? tile(String id) => tiles.where((t) => t.id == id).firstOrNull;
|
||||
|
||||
CompanionTile? tileFor(InGameAction action) =>
|
||||
tiles.where((t) => t.kind == CompanionTileKind.action && t.action == action).firstOrNull;
|
||||
|
||||
bool _fits(CompanionTile candidate) =>
|
||||
candidate.col >= 0 &&
|
||||
candidate.row >= 0 &&
|
||||
candidate.right <= columns &&
|
||||
candidate.bottom <= maxRows &&
|
||||
!tiles.any((t) => t.id != candidate.id && t.overlaps(candidate));
|
||||
|
||||
CompanionLayout _replace(CompanionTile tile) =>
|
||||
CompanionLayout(landscape: landscape, tiles: [for (final t in tiles) t.id == tile.id ? tile : t]);
|
||||
|
||||
/// [id] moved to [col], [row] (clamped to the grid), or null when it would
|
||||
/// land on another tile.
|
||||
CompanionLayout? moved(String id, {required int col, required int row}) {
|
||||
final t = tile(id);
|
||||
if (t == null) return null;
|
||||
final next = t.copyWith(
|
||||
col: col.clamp(0, columns - t.w),
|
||||
row: row.clamp(0, maxRows - t.h),
|
||||
);
|
||||
if (!_fits(next)) return null;
|
||||
return _replace(next);
|
||||
}
|
||||
|
||||
/// [id] resized to [w] × [h] cells (at least [minSpan], at most to the
|
||||
/// grid's edge), or null when it would cover another tile.
|
||||
CompanionLayout? resized(String id, {required int w, required int h}) {
|
||||
final t = tile(id);
|
||||
if (t == null) return null;
|
||||
final next = t.copyWith(
|
||||
w: w.clamp(minSpan, columns - t.col),
|
||||
h: h.clamp(minSpan, maxRows - t.row),
|
||||
);
|
||||
if (!_fits(next)) return null;
|
||||
return _replace(next);
|
||||
}
|
||||
|
||||
CompanionLayout removed(String id) => CompanionLayout(
|
||||
landscape: landscape,
|
||||
tiles: [
|
||||
for (final t in tiles)
|
||||
if (t.id != id) t,
|
||||
],
|
||||
);
|
||||
|
||||
/// The size a new tile of [kind] starts at.
|
||||
(int, int) _startSize(CompanionTileKind kind) => switch (kind) {
|
||||
CompanionTileKind.rideCard => (landscape ? 6 : 12, 3),
|
||||
CompanionTileKind.action => (landscape ? 3 : 4, landscape ? 3 : 2),
|
||||
_ => (landscape ? 3 : 4, landscape ? 3 : 2),
|
||||
};
|
||||
|
||||
String _nextId() {
|
||||
final used = tiles.map((t) => t.id).toSet();
|
||||
var i = tiles.length;
|
||||
while (used.contains('t$i')) {
|
||||
i++;
|
||||
}
|
||||
return 't$i';
|
||||
}
|
||||
|
||||
/// A new tile in the first free spot, reading order; below everything when
|
||||
/// the screen is full.
|
||||
CompanionLayout added({required CompanionTileKind kind, InGameAction? action}) {
|
||||
final (w, h) = _startSize(kind);
|
||||
final id = _nextId();
|
||||
for (var row = 0; row <= maxRows - h; row++) {
|
||||
for (var col = 0; col <= columns - w; col++) {
|
||||
final candidate = CompanionTile(id: id, kind: kind, action: action, col: col, row: row, w: w, h: h);
|
||||
if (_fits(candidate)) {
|
||||
return CompanionLayout(landscape: landscape, tiles: [...tiles, candidate]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
String toJsonString() => jsonEncode({
|
||||
'v': 1,
|
||||
'tiles': [for (final t in tiles) t.toJson()],
|
||||
});
|
||||
|
||||
/// The layout saved as [raw], or null when it isn't one. Tiles this version
|
||||
/// doesn't know (an action since removed) are dropped, as are tiles that
|
||||
/// would overlap one read before them.
|
||||
static CompanionLayout? tryParse(String raw, {required bool landscape}) {
|
||||
Object? json;
|
||||
try {
|
||||
json = jsonDecode(raw);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
if (json is! Map || json['tiles'] is! List) return null;
|
||||
final tiles = <CompanionTile>[];
|
||||
for (final entry in json['tiles'] as List) {
|
||||
final t = CompanionTile.fromJson(entry);
|
||||
if (t == null || tiles.any((o) => o.id == t.id || o.overlaps(t))) continue;
|
||||
tiles.add(t);
|
||||
}
|
||||
return CompanionLayout(landscape: landscape, tiles: tiles);
|
||||
}
|
||||
|
||||
/// Today's page as a layout: the ride card when there is ride data, − and
|
||||
/// + side by side as the biggest targets, steering under them, then the
|
||||
/// other [actions] as an even grid.
|
||||
factory CompanionLayout.standard({
|
||||
required List<InGameAction> actions,
|
||||
required bool landscape,
|
||||
required bool hasRideData,
|
||||
}) {
|
||||
final tiles = <CompanionTile>[];
|
||||
var row = 0;
|
||||
var n = 0;
|
||||
String id() => 't${n++}';
|
||||
if (hasRideData) {
|
||||
tiles.add(CompanionTile(id: id(), kind: CompanionTileKind.rideCard, col: 0, row: 0, w: gridColumns, h: 3));
|
||||
row = 3;
|
||||
}
|
||||
final hasShift = actions.contains(InGameAction.shiftUp) && actions.contains(InGameAction.shiftDown);
|
||||
final hasSteer = actions.contains(InGameAction.steerLeft) && actions.contains(InGameAction.steerRight);
|
||||
const half = gridColumns ~/ 2;
|
||||
if (hasShift) {
|
||||
final h = landscape ? 5 : 4;
|
||||
tiles
|
||||
..add(
|
||||
CompanionTile(
|
||||
id: id(),
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.shiftDown,
|
||||
col: 0,
|
||||
row: row,
|
||||
w: half,
|
||||
h: h,
|
||||
),
|
||||
)
|
||||
..add(
|
||||
CompanionTile(
|
||||
id: id(),
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.shiftUp,
|
||||
col: half,
|
||||
row: row,
|
||||
w: half,
|
||||
h: h,
|
||||
),
|
||||
);
|
||||
row += h;
|
||||
}
|
||||
if (hasSteer) {
|
||||
tiles
|
||||
..add(
|
||||
CompanionTile(
|
||||
id: id(),
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.steerLeft,
|
||||
col: 0,
|
||||
row: row,
|
||||
w: half,
|
||||
h: 2,
|
||||
),
|
||||
)
|
||||
..add(
|
||||
CompanionTile(
|
||||
id: id(),
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.steerRight,
|
||||
col: half,
|
||||
row: row,
|
||||
w: half,
|
||||
h: 2,
|
||||
),
|
||||
);
|
||||
row += 2;
|
||||
}
|
||||
final rest = actions.where(
|
||||
(a) =>
|
||||
!(hasShift && (a == InGameAction.shiftUp || a == InGameAction.shiftDown)) &&
|
||||
!(hasSteer && (a == InGameAction.steerLeft || a == InGameAction.steerRight)),
|
||||
);
|
||||
// Actions that take a value (camera angle, emote) are half a row wide:
|
||||
// their name and the two values used last sit in them. The rest are an
|
||||
// even grid under them.
|
||||
var col = 0;
|
||||
var rowHeight = 0;
|
||||
void place(InGameAction action, int w, int h) {
|
||||
if (col + w > gridColumns || (rowHeight != 0 && rowHeight != h)) {
|
||||
col = 0;
|
||||
row += rowHeight;
|
||||
rowHeight = 0;
|
||||
}
|
||||
tiles.add(
|
||||
CompanionTile(id: id(), kind: CompanionTileKind.action, action: action, col: col, row: row, w: w, h: h),
|
||||
);
|
||||
col += w;
|
||||
rowHeight = h;
|
||||
}
|
||||
|
||||
for (final action in rest.where((a) => a.possibleValues != null)) {
|
||||
place(action, half, landscape ? 4 : 3);
|
||||
}
|
||||
for (final action in rest.where((a) => a.possibleValues == null)) {
|
||||
place(action, landscape ? 3 : 4, landscape ? 3 : 2);
|
||||
}
|
||||
return CompanionLayout(landscape: landscape, tiles: tiles);
|
||||
}
|
||||
|
||||
/// Big − and + taking most of the screen, the readings between them:
|
||||
/// + on top and − at the bottom in portrait, − left and + right in
|
||||
/// landscape. Nothing else to tap.
|
||||
factory CompanionLayout.rideMode({required bool landscape, required bool hasRideData}) {
|
||||
const c = gridColumns;
|
||||
const r = gridRows;
|
||||
CompanionTile button(String id, InGameAction action, int col, int row, int w, int h) =>
|
||||
CompanionTile(id: id, kind: CompanionTileKind.action, action: action, col: col, row: row, w: w, h: h);
|
||||
CompanionTile info(String id, CompanionTileKind kind, int col, int row, int w, int h) =>
|
||||
CompanionTile(id: id, kind: kind, col: col, row: row, w: w, h: h);
|
||||
if (!hasRideData) {
|
||||
return CompanionLayout(
|
||||
landscape: landscape,
|
||||
tiles: landscape
|
||||
? [
|
||||
button('t0', InGameAction.shiftDown, 0, 0, c ~/ 2, r),
|
||||
button('t1', InGameAction.shiftUp, c ~/ 2, 0, c ~/ 2, r),
|
||||
]
|
||||
: [
|
||||
button('t0', InGameAction.shiftUp, 0, 0, c, r ~/ 2),
|
||||
button('t1', InGameAction.shiftDown, 0, r ~/ 2, c, r ~/ 2),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (landscape) {
|
||||
return CompanionLayout(
|
||||
landscape: true,
|
||||
tiles: [
|
||||
button('t0', InGameAction.shiftDown, 0, 0, 4, r),
|
||||
info('t1', CompanionTileKind.gear, 4, 0, 4, 6),
|
||||
info('t2', CompanionTileKind.power, 4, 6, 2, 3),
|
||||
info('t3', CompanionTileKind.cadence, 6, 6, 2, 3),
|
||||
info('t4', CompanionTileKind.ratio, 4, 9, 4, 3),
|
||||
button('t5', InGameAction.shiftUp, 8, 0, 4, r),
|
||||
],
|
||||
);
|
||||
}
|
||||
return CompanionLayout(
|
||||
landscape: false,
|
||||
tiles: [
|
||||
button('t0', InGameAction.shiftUp, 0, 0, c, 5),
|
||||
info('t1', CompanionTileKind.gear, 0, 5, 3, 2),
|
||||
info('t2', CompanionTileKind.power, 3, 5, 3, 2),
|
||||
info('t3', CompanionTileKind.cadence, 6, 5, 3, 2),
|
||||
info('t4', CompanionTileKind.ratio, 9, 5, 3, 2),
|
||||
button('t5', InGameAction.shiftDown, 0, 7, c, 5),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1355,6 +1355,12 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
|
||||
),
|
||||
linkLabel: context.i18n.rideVsSettingsLink,
|
||||
onPressed: () => _openVsSettings(proxy),
|
||||
// Big − and + on this screen, full screen: for riders who shift
|
||||
// from the phone on the bars.
|
||||
trailingKey: const ValueKey('ride-vs-full-screen'),
|
||||
trailingIcon: LucideIcons.maximize2,
|
||||
trailingLabel: context.i18n.companionRideLine,
|
||||
onTrailing: () => context.push(const ButtonSimulator(startFullScreen: true)),
|
||||
),
|
||||
),
|
||||
?overlay,
|
||||
|
||||
@@ -239,9 +239,12 @@ abstract class BaseActions {
|
||||
|
||||
/// Dispatch [action] as if a mapped button fired it, with no physical button.
|
||||
/// Used by the both-shifters combo (this file's coincidence detector and the
|
||||
/// same-frame detector in base_device.dart) to emit a frontShift.
|
||||
Future<ActionResult> performInGameAction(InGameAction action) async {
|
||||
final synthButton = ControllerButton('frontShiftCombo', action: action);
|
||||
/// same-frame detector in base_device.dart) to emit a frontShift, and by the
|
||||
/// companion page's on-screen buttons, so a shift there goes through
|
||||
/// BikeControl's own virtual shifting (and its haptics) like a controller's.
|
||||
/// [source] names the stand-in button.
|
||||
Future<ActionResult> performInGameAction(InGameAction action, {String source = 'frontShiftCombo'}) async {
|
||||
final synthButton = ControllerButton(source, action: action);
|
||||
final keyPair = KeyPair(
|
||||
buttons: [synthButton],
|
||||
physicalKey: null,
|
||||
|
||||
@@ -928,6 +928,22 @@ class Settings {
|
||||
await setButtonSimulatorHotkeys(hotkeys);
|
||||
}
|
||||
|
||||
/// The companion page's own layout for one orientation, as saved by
|
||||
/// `CompanionLayout.toJsonString`; null while the rider hasn't changed it.
|
||||
String? getCompanionLayout({required bool landscape}) =>
|
||||
prefs.getString(landscape ? 'companion_layout_landscape' : 'companion_layout_portrait');
|
||||
|
||||
/// Saves [json] as the companion layout for one orientation; null goes back
|
||||
/// to the generated one.
|
||||
Future<void> setCompanionLayout(String? json, {required bool landscape}) async {
|
||||
final key = landscape ? 'companion_layout_landscape' : 'companion_layout_portrait';
|
||||
if (json == null) {
|
||||
await prefs.remove(key);
|
||||
} else {
|
||||
await prefs.setString(key, json);
|
||||
}
|
||||
}
|
||||
|
||||
/// WHEELTOP keepalive experiment (see WheeltopProbe): tries reply
|
||||
/// candidates to the TX pod's status frame, one per reconnect. On by
|
||||
/// default — TX shifters are unusable without it, and the pod drops too
|
||||
|
||||
@@ -200,6 +200,10 @@ class RideSettingsLine extends StatelessWidget {
|
||||
required this.text,
|
||||
required this.linkLabel,
|
||||
required this.onPressed,
|
||||
this.trailingIcon,
|
||||
this.trailingLabel,
|
||||
this.onTrailing,
|
||||
this.trailingKey,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
@@ -207,13 +211,21 @@ class RideSettingsLine extends StatelessWidget {
|
||||
final String linkLabel;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
/// A button of its own at the end of the line, after a hairline: a 48
|
||||
/// target beside the line rather than a line of its own, so the card
|
||||
/// keeps its height. Shown when [onTrailing] is set.
|
||||
final IconData? trailingIcon;
|
||||
final String? trailingLabel;
|
||||
final VoidCallback? onTrailing;
|
||||
final Key? trailingKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cs = Theme.of(context).colorScheme;
|
||||
final accent = bkAccentText(context);
|
||||
final textStyle = context.typography.small.copyWith(color: cs.foreground, fontWeight: FontWeight.w500);
|
||||
final linkStyle = context.typography.small.copyWith(color: accent, fontWeight: FontWeight.w600);
|
||||
return BkTappable(
|
||||
final line = BkTappable(
|
||||
onPressed: onPressed,
|
||||
label: '$text, $linkLabel',
|
||||
excludeChildSemantics: true,
|
||||
@@ -268,5 +280,25 @@ class RideSettingsLine extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
);
|
||||
final onTrailing = this.onTrailing;
|
||||
if (onTrailing == null) return line;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(child: line),
|
||||
const Gap(4),
|
||||
Container(width: 1, height: 24, color: cs.border),
|
||||
const Gap(4),
|
||||
BkTappable(
|
||||
key: trailingKey,
|
||||
onPressed: onTrailing,
|
||||
label: trailingLabel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: SizedBox.square(
|
||||
dimension: BkTouchTarget.minSize,
|
||||
child: Icon(trailingIcon, size: 18, color: accent),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ class _ComboStubActions extends StubActions {
|
||||
bool get frontShiftComboEnabled => comboEnabled;
|
||||
|
||||
@override
|
||||
Future<ActionResult> performInGameAction(InGameAction action) async {
|
||||
Future<ActionResult> performInGameAction(InGameAction action, {String source = 'frontShiftCombo'}) async {
|
||||
inGameActionsPerformed.add(action);
|
||||
return Success('stub', button: null);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// The companion page is used mid-ride: shifting leads and is the biggest
|
||||
// target, steering follows it (it used to sit below "Other", off the first
|
||||
// screen), the remaining actions are an even grid, and an action's quick
|
||||
// values sit in its own row instead of floating under a tile.
|
||||
// values sit in its own tile, under its name.
|
||||
import 'package:bike_control/gen/l10n.dart';
|
||||
import 'package:bike_control/pages/button_simulator.dart';
|
||||
import 'package:bike_control/utils/core.dart';
|
||||
@@ -65,18 +65,20 @@ Future<void> main() async {
|
||||
expect(tuck.height, uturn.height, reason: 'the other actions are an even grid');
|
||||
});
|
||||
|
||||
testWidgets('quick values sit in their action\'s own row', (tester) async {
|
||||
testWidgets('quick values sit in their action\'s own tile, under its name', (tester) async {
|
||||
connectMyWhoosh();
|
||||
await render(tester);
|
||||
|
||||
final row = find.byKey(ValueKey('quick-values-${InGameAction.cameraAngle.name}'));
|
||||
expect(row, findsOneWidget);
|
||||
final tile = tester.getRect(row);
|
||||
final title = tester.getRect(find.descendant(of: row, matching: find.text(InGameAction.cameraAngle.title)));
|
||||
final chips = find.descendant(of: row, matching: find.byType(Button));
|
||||
expect(chips, findsAtLeastNWidgets(2));
|
||||
for (final chip in chips.evaluate()) {
|
||||
final r = tester.getRect(find.byElementPredicate((e) => identical(e, chip)));
|
||||
expect((r.center.dy - title.center.dy).abs(), lessThan(r.height / 2), reason: 'chips beside the title');
|
||||
expect(r.top, greaterThanOrEqualTo(title.bottom), reason: 'chips under the title');
|
||||
expect(tile.contains(r.center), isTrue, reason: 'chips inside their tile');
|
||||
expect(r.height, greaterThanOrEqualTo(44), reason: 'a sweaty thumb needs a 44 pt target');
|
||||
}
|
||||
});
|
||||
@@ -128,9 +130,14 @@ Future<void> main() async {
|
||||
final l10n = AppLocalizations.current;
|
||||
final row = find.ancestor(of: find.text(l10n.setShortcut), matching: find.byType(BkGroupedRow)).first;
|
||||
expect(find.descendant(of: row, matching: find.text(l10n.clear)), findsNothing);
|
||||
// The shortcuts sit under a screen of buttons.
|
||||
await tester.ensureVisible(row);
|
||||
await tester.pump();
|
||||
await tester.tap(find.descendant(of: row, matching: find.text(l10n.setShortcut)));
|
||||
await tester.pump();
|
||||
expect(find.text(l10n.pressAKey), findsOneWidget);
|
||||
await tester.ensureVisible(find.text(l10n.clear));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text(l10n.clear));
|
||||
await tester.pump();
|
||||
expect(core.settings.getButtonSimulatorHotkeys().containsKey(InGameAction.shiftUp), isFalse);
|
||||
|
||||
225
test/pages/companion/companion_layout_test.dart
Normal file
225
test/pages/companion/companion_layout_test.dart
Normal file
@@ -0,0 +1,225 @@
|
||||
// The companion page's layout: tiles on a snapping grid that the rider
|
||||
// moves, resizes, adds and removes, saved per orientation.
|
||||
import 'package:bike_control/pages/companion/companion_layout.dart';
|
||||
import 'package:bike_control/utils/keymap/buttons.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
const actions = [
|
||||
InGameAction.shiftUp,
|
||||
InGameAction.shiftDown,
|
||||
InGameAction.steerLeft,
|
||||
InGameAction.steerRight,
|
||||
InGameAction.tuck,
|
||||
InGameAction.uturn,
|
||||
InGameAction.toggleUi,
|
||||
InGameAction.cameraAngle,
|
||||
];
|
||||
|
||||
void expectNoOverlap(CompanionLayout layout) {
|
||||
for (final a in layout.tiles) {
|
||||
expect(a.col, greaterThanOrEqualTo(0));
|
||||
expect(a.row, greaterThanOrEqualTo(0));
|
||||
expect(a.col + a.w, lessThanOrEqualTo(layout.columns), reason: '${a.id} inside the columns');
|
||||
for (final b in layout.tiles) {
|
||||
if (identical(a, b)) continue;
|
||||
expect(a.overlaps(b), isFalse, reason: '${a.id} overlaps ${b.id}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group('JSON', () {
|
||||
test('round-trips every tile kind', () {
|
||||
final layout = CompanionLayout(
|
||||
landscape: true,
|
||||
tiles: [
|
||||
const CompanionTile(
|
||||
id: 'a',
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.shiftUp,
|
||||
col: 0,
|
||||
row: 0,
|
||||
w: 4,
|
||||
h: 3,
|
||||
),
|
||||
for (final (i, kind) in CompanionTileKind.values.where((k) => k != CompanionTileKind.action).indexed)
|
||||
CompanionTile(id: 'i$i', kind: kind, col: 4 + i % 2 * 4, row: i * 2, w: 4, h: 2),
|
||||
],
|
||||
);
|
||||
final back = CompanionLayout.tryParse(layout.toJsonString(), landscape: true);
|
||||
expect(back, isNotNull);
|
||||
expect(back!.tiles, layout.tiles);
|
||||
});
|
||||
|
||||
test('a broken or unknown value parses to null, unknown tiles are dropped', () {
|
||||
expect(CompanionLayout.tryParse('{nope', landscape: false), isNull);
|
||||
expect(CompanionLayout.tryParse('[]', landscape: false), isNull);
|
||||
final partial = CompanionLayout.tryParse(
|
||||
'{"v":1,"tiles":[{"id":"x","kind":"warpDrive","col":0,"row":0,"w":2,"h":2},'
|
||||
'{"id":"y","kind":"action","action":"shiftUp","col":0,"row":0,"w":2,"h":2},'
|
||||
'{"id":"z","kind":"action","action":"noSuchAction","col":2,"row":0,"w":2,"h":2}]}',
|
||||
landscape: false,
|
||||
);
|
||||
expect(partial!.tiles.map((t) => t.id), ['y']);
|
||||
});
|
||||
});
|
||||
|
||||
group('default layout', () {
|
||||
test('portrait: − left and + right lead, steering under them, the rest an even grid', () {
|
||||
final layout = CompanionLayout.standard(actions: actions, landscape: false, hasRideData: false);
|
||||
final up = layout.tileFor(InGameAction.shiftUp)!;
|
||||
final down = layout.tileFor(InGameAction.shiftDown)!;
|
||||
final left = layout.tileFor(InGameAction.steerLeft)!;
|
||||
final tuck = layout.tileFor(InGameAction.tuck)!;
|
||||
final uturn = layout.tileFor(InGameAction.uturn)!;
|
||||
expect(down.col, lessThan(up.col));
|
||||
expect(up.row, 0);
|
||||
expect(up.h, greaterThan(left.h));
|
||||
expect(left.row, greaterThanOrEqualTo(up.row + up.h));
|
||||
expect(tuck.row, greaterThanOrEqualTo(left.row + left.h));
|
||||
expect(tuck.w, uturn.w);
|
||||
expect(tuck.h, uturn.h);
|
||||
expectNoOverlap(layout);
|
||||
expect(layout.tiles.where((t) => t.kind == CompanionTileKind.action).length, actions.length);
|
||||
});
|
||||
|
||||
test('with ride data the gear leads above the buttons', () {
|
||||
final layout = CompanionLayout.standard(actions: actions, landscape: false, hasRideData: true);
|
||||
final card = layout.tiles.firstWhere((t) => t.kind == CompanionTileKind.rideCard);
|
||||
expect(card.row, 0);
|
||||
expect(layout.tileFor(InGameAction.shiftUp)!.row, greaterThanOrEqualTo(card.h));
|
||||
expectNoOverlap(layout);
|
||||
});
|
||||
|
||||
test('landscape fits more to a row', () {
|
||||
final portrait = CompanionLayout.standard(actions: actions, landscape: false, hasRideData: false);
|
||||
final landscape = CompanionLayout.standard(actions: actions, landscape: true, hasRideData: false);
|
||||
expect(landscape.tileFor(InGameAction.tuck)!.w, lessThan(portrait.tileFor(InGameAction.tuck)!.w));
|
||||
expectNoOverlap(landscape);
|
||||
});
|
||||
});
|
||||
|
||||
group('ride mode', () {
|
||||
test('portrait: + fills the top, − the bottom, the readings a strip between', () {
|
||||
final layout = CompanionLayout.rideMode(landscape: false, hasRideData: true);
|
||||
final up = layout.tileFor(InGameAction.shiftUp)!;
|
||||
final down = layout.tileFor(InGameAction.shiftDown)!;
|
||||
expect(up.row, 0);
|
||||
expect(up.w, layout.columns);
|
||||
expect(down.w, layout.columns);
|
||||
expect(down.row + down.h, layout.rows);
|
||||
final info = layout.tiles.where((t) => t.kind != CompanionTileKind.action).toList();
|
||||
expect(
|
||||
info.map((t) => t.kind),
|
||||
containsAll([CompanionTileKind.gear, CompanionTileKind.power, CompanionTileKind.cadence]),
|
||||
);
|
||||
for (final t in info) {
|
||||
expect(t.row, greaterThanOrEqualTo(up.row + up.h));
|
||||
expect(t.row + t.h, lessThanOrEqualTo(down.row));
|
||||
}
|
||||
expect(up.h * up.w, greaterThan(layout.columns * layout.rows / 3), reason: 'most of the screen is the buttons');
|
||||
expectNoOverlap(layout);
|
||||
});
|
||||
|
||||
test('landscape: − left, + right, readings in the centre', () {
|
||||
final layout = CompanionLayout.rideMode(landscape: true, hasRideData: true);
|
||||
final up = layout.tileFor(InGameAction.shiftUp)!;
|
||||
final down = layout.tileFor(InGameAction.shiftDown)!;
|
||||
expect(down.col, 0);
|
||||
expect(up.col + up.w, layout.columns);
|
||||
expect(up.h, layout.rows);
|
||||
for (final t in layout.tiles.where((t) => t.kind != CompanionTileKind.action)) {
|
||||
expect(t.col, greaterThanOrEqualTo(down.col + down.w));
|
||||
expect(t.col + t.w, lessThanOrEqualTo(up.col));
|
||||
}
|
||||
expectNoOverlap(layout);
|
||||
});
|
||||
|
||||
test('without ride data the two buttons share the whole screen', () {
|
||||
final layout = CompanionLayout.rideMode(landscape: false, hasRideData: false);
|
||||
expect(layout.tiles, hasLength(2));
|
||||
expect(layout.tiles.fold<int>(0, (sum, t) => sum + t.w * t.h), layout.columns * layout.rows);
|
||||
});
|
||||
|
||||
test('SIM/ERG is never a button in ride mode', () {
|
||||
for (final landscape in [false, true]) {
|
||||
final layout = CompanionLayout.rideMode(landscape: landscape, hasRideData: true);
|
||||
expect(layout.tileFor(InGameAction.trainerSwitchMode), isNull);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('editing', () {
|
||||
final base = CompanionLayout(
|
||||
landscape: false,
|
||||
tiles: const [
|
||||
CompanionTile(
|
||||
id: 'a',
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.shiftDown,
|
||||
col: 0,
|
||||
row: 0,
|
||||
w: 6,
|
||||
h: 3,
|
||||
),
|
||||
CompanionTile(
|
||||
id: 'b',
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.shiftUp,
|
||||
col: 6,
|
||||
row: 0,
|
||||
w: 6,
|
||||
h: 3,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
test('a move onto another tile is refused, a free spot is taken', () {
|
||||
expect(base.moved('a', col: 4, row: 0), isNull);
|
||||
final moved = base.moved('a', col: 0, row: 5)!;
|
||||
expect(moved.tile('a')!.row, 5);
|
||||
});
|
||||
|
||||
test('a move is clamped to the grid', () {
|
||||
final right = base.moved('a', col: 99, row: 10)!.tile('a')!;
|
||||
expect(right.col, base.columns - right.w);
|
||||
expect(right.row, 10);
|
||||
final top = base.moved('a', col: 0, row: -4)!.tile('a')!;
|
||||
expect(top.row, 0);
|
||||
});
|
||||
|
||||
test('resizing keeps a minimum size and stops at a neighbour', () {
|
||||
final small = base.resized('a', w: 0, h: 0)!;
|
||||
expect(small.tile('a')!.w, CompanionLayout.minSpan);
|
||||
expect(small.tile('a')!.h, CompanionLayout.minSpan);
|
||||
expect(base.resized('a', w: 8, h: 3), isNull, reason: 'would cover b');
|
||||
expect(base.resized('a', w: 6, h: 6)!.tile('a')!.h, 6);
|
||||
});
|
||||
|
||||
test('added tiles land in the first free spot and removing frees it', () {
|
||||
final added = base.added(kind: CompanionTileKind.gear);
|
||||
expectNoOverlap(added);
|
||||
final gear = added.tiles.last;
|
||||
expect(gear.kind, CompanionTileKind.gear);
|
||||
expect(gear.row, 3);
|
||||
final removed = added.removed(gear.id);
|
||||
expect(removed.tiles, base.tiles);
|
||||
});
|
||||
|
||||
test('a new tile on a full screen goes below, the canvas grows', () {
|
||||
final full = CompanionLayout.rideMode(landscape: false, hasRideData: false);
|
||||
final added = full.added(kind: CompanionTileKind.action, action: InGameAction.tuck);
|
||||
expectNoOverlap(added);
|
||||
expect(added.tiles.last.row, greaterThanOrEqualTo(full.rows));
|
||||
expect(added.usedRows, greaterThan(full.rows));
|
||||
});
|
||||
|
||||
test('new ids never collide', () {
|
||||
var layout = base;
|
||||
for (var i = 0; i < 5; i++) {
|
||||
layout = layout.added(kind: CompanionTileKind.power);
|
||||
}
|
||||
expect(layout.tiles.map((t) => t.id).toSet(), hasLength(layout.tiles.length));
|
||||
});
|
||||
});
|
||||
}
|
||||
280
test/pages/companion/companion_page_test.dart
Normal file
280
test/pages/companion/companion_page_test.dart
Normal file
@@ -0,0 +1,280 @@
|
||||
// The companion page as a ride screen: buttons and ride data on a grid the
|
||||
// rider arranges, a full-screen view, and − / + that shift BikeControl's own
|
||||
// virtual shifting the way a controller does.
|
||||
import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart';
|
||||
import 'package:bike_control/gen/l10n.dart';
|
||||
import 'package:bike_control/pages/button_simulator.dart';
|
||||
import 'package:bike_control/pages/companion/companion_layout.dart';
|
||||
import 'package:bike_control/utils/core.dart';
|
||||
import 'package:bike_control/utils/keymap/apps/my_whoosh.dart';
|
||||
import 'package:bike_control/utils/keymap/apps/rouvy.dart';
|
||||
import 'package:bike_control/utils/keymap/buttons.dart';
|
||||
import 'package:bike_control/utils/requirements/multi.dart' show Target;
|
||||
import 'package:bike_control/widgets/ui/bk_page_header.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:prop/emulators/definitions/fitness_bike_definition.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
||||
import 'package:universal_ble/universal_ble.dart';
|
||||
|
||||
import '../../widget_snapshot.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
await ensureSnapshotHarness();
|
||||
|
||||
setUp(() async {
|
||||
await core.settings.setCompanionLayout(null, landscape: false);
|
||||
await core.settings.setCompanionLayout(null, landscape: true);
|
||||
});
|
||||
|
||||
void connectMyWhoosh() {
|
||||
core.settings.setTrainerApp(MyWhoosh());
|
||||
core.settings.setKeyMap(MyWhoosh());
|
||||
core.settings.setLastTarget(Target.thisDevice);
|
||||
core.settings.setMyWhooshLinkEnabled(true);
|
||||
core.whooshLink.isConnected.value = true;
|
||||
addTearDown(() {
|
||||
core.whooshLink.isConnected.value = false;
|
||||
core.settings.setMyWhooshLinkEnabled(false);
|
||||
});
|
||||
}
|
||||
|
||||
/// A KICKR that BikeControl shifts itself, as with Rouvy over the bridge:
|
||||
/// no trainer app connection on this page at all.
|
||||
FitnessBikeDefinition connectVirtualShifting() {
|
||||
core.settings.setTrainerApp(Rouvy());
|
||||
core.settings.setKeyMap(Rouvy());
|
||||
final proxy =
|
||||
ProxyDevice(
|
||||
BleDevice(
|
||||
name: 'KICKR CORE',
|
||||
deviceId: '00:11:22:33:44:55',
|
||||
services: [FitnessBikeDefinition.FITNESS_MACHINE_SERVICE_UUID],
|
||||
),
|
||||
)
|
||||
..services = [BleService(FitnessBikeDefinition.FITNESS_MACHINE_SERVICE_UUID, [])]
|
||||
..isConnected = true;
|
||||
final definition = FitnessBikeDefinition(
|
||||
connectedDevice: proxy.scanResult,
|
||||
connectedDeviceServices: proxy.services!,
|
||||
data: ValueNotifier(''),
|
||||
)..setMaxGear(24);
|
||||
// As a live session has it: on the page's listenable and on the
|
||||
// emulator, where a controller's shift lands.
|
||||
proxy.debugAttachFitnessBike(definition);
|
||||
proxy.emulator.composite.attach(definition);
|
||||
core.connection.devices.add(proxy);
|
||||
addTearDown(() {
|
||||
proxy.emulator.composite.detach(definition);
|
||||
proxy.debugAttachFitnessBike(null);
|
||||
core.connection.devices.remove(proxy);
|
||||
});
|
||||
return definition;
|
||||
}
|
||||
|
||||
Future<void> render(
|
||||
WidgetTester tester, {
|
||||
String name = 'companion',
|
||||
double width = 414,
|
||||
double height = 860,
|
||||
bool fullScreen = false,
|
||||
Brightness brightness = Brightness.light,
|
||||
}) => captureWidget(
|
||||
tester,
|
||||
name: name,
|
||||
width: width,
|
||||
height: height,
|
||||
padding: EdgeInsets.zero,
|
||||
settle: false,
|
||||
brightness: brightness,
|
||||
outputDir: 'build/snapshots',
|
||||
builder: (_) => ButtonSimulator(startFullScreen: fullScreen),
|
||||
);
|
||||
|
||||
Finder pad(InGameAction action) =>
|
||||
find.ancestor(of: find.text(action.title).first, matching: find.byType(Button)).first;
|
||||
|
||||
testWidgets('with only virtual shifting, − and + shift its gears and the gear card shows', (tester) async {
|
||||
final definition = connectVirtualShifting();
|
||||
await render(tester, name: 'companion_vs');
|
||||
|
||||
expect(find.text(AppLocalizations.current.trainerControlsNoConnection), findsNothing);
|
||||
final before = definition.currentGear.value;
|
||||
await tester.tap(pad(InGameAction.shiftUp));
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
expect(definition.currentGear.value, before + 1);
|
||||
await tester.tap(pad(InGameAction.shiftDown));
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
expect(definition.currentGear.value, before);
|
||||
});
|
||||
|
||||
testWidgets('opened full screen from Ride: ride mode, no header, nothing else to tap', (tester) async {
|
||||
connectVirtualShifting();
|
||||
await render(tester, name: 'companion_ride_mode', fullScreen: true);
|
||||
|
||||
expect(find.byType(BkPageHeader), findsNothing);
|
||||
final up = tester.getRect(pad(InGameAction.shiftUp));
|
||||
final down = tester.getRect(pad(InGameAction.shiftDown));
|
||||
expect(up.bottom, lessThan(down.top), reason: '+ on top, − at the bottom');
|
||||
expect(up.height, greaterThan(250));
|
||||
final gear = tester.getRect(find.byKey(const ValueKey('companion-info-gear')));
|
||||
expect(gear.top, greaterThan(up.bottom));
|
||||
expect(gear.bottom, lessThan(down.top));
|
||||
expect(find.text('SIM'), findsNothing, reason: 'the mode is part of the gear label, never a switch');
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('companion-exit-full-screen')));
|
||||
await tester.pump();
|
||||
expect(find.byType(BkPageHeader), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('landscape ride mode: − left, + right, readings between', (tester) async {
|
||||
connectVirtualShifting();
|
||||
await render(tester, name: 'companion_ride_mode_landscape', width: 860, height: 414, fullScreen: true);
|
||||
final up = tester.getRect(pad(InGameAction.shiftUp));
|
||||
final down = tester.getRect(pad(InGameAction.shiftDown));
|
||||
final gear = tester.getRect(find.byKey(const ValueKey('companion-info-gear')));
|
||||
expect(down.right, lessThan(gear.left));
|
||||
expect(gear.right, lessThan(up.left));
|
||||
});
|
||||
|
||||
testWidgets('the full-screen button hides the page around the buttons', (tester) async {
|
||||
connectMyWhoosh();
|
||||
await render(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('companion-full-screen')));
|
||||
await tester.pump();
|
||||
expect(find.byType(BkPageHeader), findsNothing);
|
||||
expect(find.text(AppLocalizations.current.keyboardShortcuts), findsNothing);
|
||||
expect(pad(InGameAction.shiftUp), findsOneWidget);
|
||||
});
|
||||
|
||||
group('editing', () {
|
||||
CompanionLayout saved() =>
|
||||
CompanionLayout.tryParse(core.settings.getCompanionLayout(landscape: false)!, landscape: false)!;
|
||||
|
||||
String idOf(WidgetTester tester, InGameAction action) {
|
||||
final key = tester
|
||||
.widgetList(find.ancestor(of: find.text(action.title).first, matching: find.byType(Positioned)))
|
||||
.map((w) => w.key)
|
||||
.whereType<ValueKey<String>>()
|
||||
.firstWhere((k) => k.value.startsWith('companion-tile-'));
|
||||
return key.value.substring('companion-tile-'.length);
|
||||
}
|
||||
|
||||
testWidgets('a tile drags to a free spot, and the layout is saved', (tester) async {
|
||||
connectMyWhoosh();
|
||||
await render(tester, name: 'companion_editing');
|
||||
await tester.tap(find.byKey(const ValueKey('companion-edit')));
|
||||
await tester.pump();
|
||||
expect(find.text(AppLocalizations.current.companionEditHint), findsOneWidget);
|
||||
|
||||
final id = idOf(tester, InGameAction.tuck);
|
||||
final before = tester.getRect(find.byKey(ValueKey('companion-tile-$id')));
|
||||
// Down a few rows, onto the empty space under the grid.
|
||||
await tester.drag(find.byKey(ValueKey('companion-move-$id')), const Offset(0, 140));
|
||||
await tester.pump();
|
||||
final after = tester.getRect(find.byKey(ValueKey('companion-tile-$id')));
|
||||
expect(after.top, greaterThan(before.top));
|
||||
expect(saved().tile(id)!.row, greaterThan(0));
|
||||
});
|
||||
|
||||
testWidgets('dropping onto another tile leaves it where it was', (tester) async {
|
||||
connectMyWhoosh();
|
||||
await render(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('companion-edit')));
|
||||
await tester.pump();
|
||||
final id = idOf(tester, InGameAction.shiftDown);
|
||||
final before = tester.getRect(find.byKey(ValueKey('companion-tile-$id')));
|
||||
await tester.drag(find.byKey(ValueKey('companion-move-$id')), Offset(before.width / 2, 0));
|
||||
await tester.pump();
|
||||
expect(tester.getRect(find.byKey(ValueKey('companion-tile-$id'))), before);
|
||||
});
|
||||
|
||||
testWidgets('the corner handle resizes, the × removes', (tester) async {
|
||||
connectMyWhoosh();
|
||||
// Room under the tile to grow into.
|
||||
await core.settings.setCompanionLayout(
|
||||
CompanionLayout(
|
||||
landscape: false,
|
||||
tiles: const [
|
||||
CompanionTile(
|
||||
id: 'a',
|
||||
kind: CompanionTileKind.action,
|
||||
action: InGameAction.tuck,
|
||||
col: 0,
|
||||
row: 0,
|
||||
w: 4,
|
||||
h: 2,
|
||||
),
|
||||
],
|
||||
).toJsonString(),
|
||||
landscape: false,
|
||||
);
|
||||
await render(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('companion-edit')));
|
||||
await tester.pump();
|
||||
final id = idOf(tester, InGameAction.tuck);
|
||||
final before = tester.getRect(find.byKey(ValueKey('companion-tile-$id')));
|
||||
await tester.drag(find.byKey(ValueKey('companion-resize-$id')), const Offset(0, 120));
|
||||
await tester.pump();
|
||||
expect(tester.getRect(find.byKey(ValueKey('companion-tile-$id'))).height, greaterThan(before.height));
|
||||
|
||||
await tester.tap(find.byKey(ValueKey('companion-remove-$id')));
|
||||
await tester.pump();
|
||||
expect(find.byKey(ValueKey('companion-tile-$id')), findsNothing);
|
||||
expect(saved().tileFor(InGameAction.tuck), isNull);
|
||||
});
|
||||
|
||||
testWidgets('a removed button comes back from the add list', (tester) async {
|
||||
connectMyWhoosh();
|
||||
await render(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('companion-edit')));
|
||||
await tester.pump();
|
||||
final id = idOf(tester, InGameAction.tuck);
|
||||
await tester.tap(find.byKey(ValueKey('companion-remove-$id')));
|
||||
await tester.pump();
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('companion-add')));
|
||||
await tester.pumpAndSettle();
|
||||
// Ride data needs virtual shifting: listed, but it can't be added.
|
||||
expect(find.text(AppLocalizations.current.companionRideDataHint), findsOneWidget);
|
||||
await tester.tap(find.byKey(ValueKey('companion-add-${InGameAction.tuck.name}')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(saved().tileFor(InGameAction.tuck), isNotNull);
|
||||
});
|
||||
|
||||
testWidgets('ride data tiles are added while BikeControl shifts', (tester) async {
|
||||
connectVirtualShifting();
|
||||
await render(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('companion-edit')));
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const ValueKey('companion-add')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.ensureVisible(find.byKey(const ValueKey('companion-add-cadence')));
|
||||
await tester.tap(find.byKey(const ValueKey('companion-add-cadence')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(saved().tiles.where((t) => t.kind == CompanionTileKind.cadence), hasLength(1));
|
||||
expect(find.byKey(const ValueKey('companion-info-cadence')), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('a saved layout comes back next time', (tester) async {
|
||||
connectMyWhoosh();
|
||||
await core.settings.setCompanionLayout(
|
||||
CompanionLayout.rideMode(landscape: false, hasRideData: false).toJsonString(),
|
||||
landscape: false,
|
||||
);
|
||||
await render(tester);
|
||||
final up = tester.getRect(pad(InGameAction.shiftUp));
|
||||
final down = tester.getRect(pad(InGameAction.shiftDown));
|
||||
expect(up.bottom, lessThan(down.top));
|
||||
final tiles = find.byWidgetPredicate(
|
||||
(w) => w.key is ValueKey<String> && (w.key! as ValueKey<String>).value.startsWith('companion-tile-'),
|
||||
);
|
||||
expect(tiles, findsNWidgets(2), reason: 'only the saved − and +');
|
||||
});
|
||||
|
||||
testWidgets('dark, ride mode with data → PNG', (tester) async {
|
||||
connectVirtualShifting();
|
||||
await render(tester, name: 'companion_ride_mode_dark', fullScreen: true, brightness: Brightness.dark);
|
||||
expect(find.byKey(const ValueKey('companion-info-power')), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import 'package:bike_control/bluetooth/devices/zwift/zwift_play.dart';
|
||||
import 'package:bike_control/bluetooth/messages/notification.dart';
|
||||
import 'package:bike_control/gen/l10n.dart';
|
||||
import 'package:bike_control/main.dart' show OtherLocalizationsDelegate, screenshotMode;
|
||||
import 'package:bike_control/pages/button_simulator.dart';
|
||||
import 'package:bike_control/pages/controller_settings.dart';
|
||||
import 'package:bike_control/pages/home/home_page.dart';
|
||||
import 'package:bike_control/pages/proxy_device_details.dart';
|
||||
@@ -307,6 +308,22 @@ Future<void> main() async {
|
||||
expect(find.byType(VirtualShiftingSettingsPage), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a button on the settings line opens the companion page full screen', (tester) async {
|
||||
liveTrainer();
|
||||
await pumpRide(tester);
|
||||
|
||||
final line = find.byKey(const ValueKey('ride-vs-full-screen'));
|
||||
expect(find.descendant(of: find.byType(VirtualShiftingCard), matching: line), findsOneWidget);
|
||||
expect(tester.getSize(line).height, greaterThanOrEqualTo(48));
|
||||
await tester.ensureVisible(line);
|
||||
await tester.pump();
|
||||
await tester.tap(line);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
final page = tester.widget<ButtonSimulator>(find.byType(ButtonSimulator));
|
||||
expect(page.startFullScreen, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('the trainer name opens the trainer page', (tester) async {
|
||||
liveTrainer();
|
||||
await pumpRide(tester);
|
||||
|
||||
Reference in New Issue
Block a user