From 4a2b3b1a9b7a0c68920959cdec8a3bed9ce08421 Mon Sep 17 00:00:00 2001 From: Jonas Bark Date: Sun, 30 Mar 2025 13:36:40 +0200 Subject: [PATCH] allow adding custom keymap and store it --- CHANGELOG.md | 3 + lib/main.dart | 2 + lib/pages/device.dart | 2 +- lib/pages/requirements.dart | 45 +++++---- lib/pages/scan.dart | 14 ++- lib/utils/keymap/keymap.dart | 43 ++++++-- lib/utils/requirements/multi.dart | 27 +++--- lib/utils/settings/settings.dart | 26 +++++ lib/widgets/custom_keymap_selector.dart | 97 +++++++++++++++++++ lib/widgets/menu.dart | 40 ++++++-- macos/Flutter/GeneratedPluginRegistrant.swift | 2 + macos/Podfile.lock | 7 ++ pubspec.lock | 96 ++++++++++++++++++ pubspec.yaml | 3 +- 14 files changed, 355 insertions(+), 52 deletions(-) create mode 100644 lib/utils/settings/settings.dart create mode 100644 lib/widgets/custom_keymap_selector.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index b2560609..1dc2d597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +### 1.0.7 (2025-03-30) +- Windows & macOS: allow setting custom keymap and store the setting + ### 1.0.6 (2025-03-29) - Another potential keyboard fix for Windows - Zwift Play: actually also use the dedicated shift buttons diff --git a/lib/main.dart b/lib/main.dart index fa9c90c4..1a56dc4b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -4,6 +4,7 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:swift_control/pages/requirements.dart'; import 'package:swift_control/theme.dart'; import 'package:swift_control/utils/connection.dart'; +import 'package:swift_control/utils/settings/settings.dart'; import 'utils/actions/base_actions.dart'; @@ -11,6 +12,7 @@ final connection = Connection(); final actionHandler = ActionHandler(); final accessibilityHandler = Accessibility(); final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); +final settings = Settings(); void main() { runApp(const SwiftPlayApp()); diff --git a/lib/pages/device.dart b/lib/pages/device.dart index e994e514..d719ce58 100644 --- a/lib/pages/device.dart +++ b/lib/pages/device.dart @@ -46,7 +46,7 @@ class _DevicePageState extends State { child: Scaffold( appBar: AppBar( title: Text('SwiftControl'), - actions: [MenuButton()], + actions: buildMenuButtons(), backgroundColor: Theme.of(context).colorScheme.inversePrimary, ), body: Padding( diff --git a/lib/pages/requirements.dart b/lib/pages/requirements.dart index 3bfdcb8b..bd182528 100644 --- a/lib/pages/requirements.dart +++ b/lib/pages/requirements.dart @@ -4,6 +4,7 @@ import 'package:dartx/dartx.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:swift_control/main.dart'; +import 'package:swift_control/utils/requirements/multi.dart'; import 'package:swift_control/utils/requirements/platform.dart'; import 'package:swift_control/widgets/menu.dart'; @@ -28,14 +29,16 @@ class _RequirementsPageState extends State with WidgetsBinding // call after first frame WidgetsBinding.instance.addPostFrameCallback((_) { - if (!kIsWeb && Platform.isMacOS) { - // add more delay due tu CBManagerStateUnknown - Future.delayed(const Duration(seconds: 2), () { + settings.init().then((_) { + if (!kIsWeb && Platform.isMacOS) { + // add more delay due tu CBManagerStateUnknown + Future.delayed(const Duration(seconds: 2), () { + _reloadRequirements(); + }); + } else { _reloadRequirements(); - }); - } else { - _reloadRequirements(); - } + } + }); }); connection.hasDevices.addListener(() { @@ -64,7 +67,7 @@ class _RequirementsPageState extends State with WidgetsBinding appBar: AppBar( title: Text('SwiftControl'), backgroundColor: Theme.of(context).colorScheme.inversePrimary, - actions: [MenuButton()], + actions: buildMenuButtons(), ), body: _requirements.isEmpty @@ -83,7 +86,7 @@ class _RequirementsPageState extends State with WidgetsBinding } : null, onStepTapped: (step) { - if (_requirements[step].status) { + if (_requirements[step].status && _requirements[step] is! KeymapRequirement) { return; } final hasEarlierIncomplete = _requirements.indexWhere((req) => !req.status) < step; @@ -100,16 +103,20 @@ class _RequirementsPageState extends State with WidgetsBinding .mapIndexed( (index, req) => Step( title: Text(req.name), - content: - (index == _currentStep - ? req.build(context, () { - _reloadRequirements(); - }) - : null) ?? - ElevatedButton( - onPressed: req.status ? null : () => _callRequirement(req), - child: Text(req.name), - ), + content: Container( + padding: const EdgeInsets.symmetric(vertical: 16.0), + alignment: Alignment.centerLeft, + child: + (index == _currentStep + ? req.build(context, () { + _reloadRequirements(); + }) + : null) ?? + ElevatedButton( + onPressed: req.status ? null : () => _callRequirement(req), + child: Text(req.name), + ), + ), state: req.status ? StepState.complete : StepState.indexed, ), ) diff --git a/lib/pages/scan.dart b/lib/pages/scan.dart index 8158548f..0b3670fc 100644 --- a/lib/pages/scan.dart +++ b/lib/pages/scan.dart @@ -57,11 +57,15 @@ class _ScanWidgetState extends State { ], ); } else { - return ElevatedButton( - onPressed: () { - connection.performScanning(); - }, - child: const Text("SCAN"), + return Row( + children: [ + ElevatedButton( + onPressed: () { + connection.performScanning(); + }, + child: const Text("SCAN"), + ), + ], ); } }, diff --git a/lib/utils/keymap/keymap.dart b/lib/utils/keymap/keymap.dart index e3933b81..5978388d 100644 --- a/lib/utils/keymap/keymap.dart +++ b/lib/utils/keymap/keymap.dart @@ -1,12 +1,41 @@ import 'package:flutter/services.dart'; -enum Keymap { - myWhoosh(increase: PhysicalKeyboardKey.keyK, decrease: PhysicalKeyboardKey.keyI), - indieVelo(increase: PhysicalKeyboardKey(0x70030), decrease: PhysicalKeyboardKey(0x70038)), - plusMinus(increase: PhysicalKeyboardKey(0x70030), decrease: PhysicalKeyboardKey(0x70038)); +class Keymap { + static Keymap myWhoosh = Keymap('MyWhoosh', increase: PhysicalKeyboardKey.keyK, decrease: PhysicalKeyboardKey.keyI); + static Keymap custom = Keymap('Custom', increase: null, decrease: null); - final PhysicalKeyboardKey increase; - final PhysicalKeyboardKey decrease; + static List values = [myWhoosh, custom]; - const Keymap({required this.increase, required this.decrease}); + PhysicalKeyboardKey? increase; + PhysicalKeyboardKey? decrease; + final String name; + + Keymap(this.name, {required this.increase, required this.decrease}); + + @override + String toString() { + if (increase == null && decrease == null) { + return name; + } + return "$name: ${increase?.debugName} + ${decrease?.debugName}"; + } + + List encode() { + // encode to save in preferences + return [name, increase?.usbHidUsage.toString() ?? '', decrease?.usbHidUsage.toString() ?? '']; + } + + static Keymap decode(List data) { + // decode from preferences + final name = data[0]; + final keymap = values.firstWhere((element) => element.name == name, orElse: () => custom); + + if (keymap.name != custom.name) { + return keymap; + } + + keymap.increase = data[1].isNotEmpty ? PhysicalKeyboardKey(int.parse(data[1])) : null; + keymap.decrease = data[2].isNotEmpty ? PhysicalKeyboardKey(int.parse(data[2])) : null; + return keymap; + } } diff --git a/lib/utils/requirements/multi.dart b/lib/utils/requirements/multi.dart index c34d3e73..c7c8869d 100644 --- a/lib/utils/requirements/multi.dart +++ b/lib/utils/requirements/multi.dart @@ -1,8 +1,8 @@ -import 'package:dartx/dartx.dart'; import 'package:flutter/material.dart'; import 'package:keypress_simulator/keypress_simulator.dart'; import 'package:swift_control/pages/scan.dart'; import 'package:swift_control/utils/requirements/platform.dart'; +import 'package:swift_control/widgets/custom_keymap_selector.dart'; import 'package:universal_ble/universal_ble.dart'; import '../../main.dart'; @@ -35,18 +35,19 @@ class KeymapRequirement extends PlatformRequirement { @override Widget? build(BuildContext context, VoidCallback onUpdate) { - return Padding( - padding: const EdgeInsets.symmetric(vertical: 16.0), - child: DropdownMenu( - dropdownMenuEntries: - Keymap.values.map((key) => DropdownMenuEntry(value: key, label: key.name.capitalize())).toList(), - onSelected: (keymap) { - actionHandler.init(keymap); - onUpdate(); - }, - initialSelection: null, - hintText: 'Keymap', - ), + return DropdownMenu( + dropdownMenuEntries: + Keymap.values.map((key) => DropdownMenuEntry(value: key, label: key.toString())).toList(), + onSelected: (keymap) async { + if (keymap!.name == Keymap.custom.name) { + keymap = await showCustomKeymapDialog(context, keymap: keymap); + } + actionHandler.init(keymap); + settings.setKeymap(keymap!); + onUpdate(); + }, + initialSelection: actionHandler.keymap, + hintText: 'Keymap', ); } } diff --git a/lib/utils/settings/settings.dart b/lib/utils/settings/settings.dart new file mode 100644 index 00000000..633016a4 --- /dev/null +++ b/lib/utils/settings/settings.dart @@ -0,0 +1,26 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../main.dart'; +import '../keymap/keymap.dart'; + +class Settings { + late final SharedPreferences _prefs; + + Future init() async { + _prefs = await SharedPreferences.getInstance(); + + try { + final keymapSetting = _prefs.getStringList("keymap"); + if (keymapSetting != null) { + actionHandler.init(Keymap.decode(keymapSetting)); + } + } catch (e) { + // couldn't decode, reset + await _prefs.clear(); + } + } + + void setKeymap(Keymap keymap) { + _prefs.setStringList("keymap", keymap.encode()); + } +} diff --git a/lib/widgets/custom_keymap_selector.dart b/lib/widgets/custom_keymap_selector.dart new file mode 100644 index 00000000..d4be63ac --- /dev/null +++ b/lib/widgets/custom_keymap_selector.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:swift_control/utils/keymap/keymap.dart'; + +Future showCustomKeymapDialog(BuildContext context, {required Keymap keymap}) { + return showDialog( + context: context, + builder: (context) { + return GearHotkeyDialog(keymap: keymap); + }, + ); +} + +class GearHotkeyDialog extends StatefulWidget { + final Keymap keymap; + const GearHotkeyDialog({super.key, required this.keymap}); + + @override + State createState() => _GearHotkeyDialogState(); +} + +class _GearHotkeyDialogState extends State { + final FocusNode _focusNode = FocusNode(); + final Set _pressedKeys = {}; + Set? _gearUpHotkey; + Set? _gearDownHotkey; + + String _mode = 'up'; // 'up' or 'down' + + @override + void initState() { + super.initState(); + _focusNode.requestFocus(); + } + + void _onKey(KeyEvent event) { + setState(() { + if (event is KeyDownEvent) { + _pressedKeys.add(event.physicalKey); + } else if (event is KeyUpEvent) { + if (_pressedKeys.isNotEmpty) { + if (_mode == 'up') { + _gearUpHotkey = {..._pressedKeys}; + _mode = 'down'; + } else { + _gearDownHotkey = {..._pressedKeys}; + widget.keymap.increase = _gearUpHotkey!.first; + widget.keymap.decrease = _gearDownHotkey!.first; + Navigator.of(context).pop(widget.keymap); + } + _pressedKeys.clear(); + } + } + }); + } + + String _formatKeys(Set? keys) { + if (keys == null || keys.isEmpty) return 'Not set'; + return keys.map((k) => k.debugName ?? k).join(' + '); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text('Set Gear Hotkeys'), + content: KeyboardListener( + focusNode: _focusNode, + autofocus: true, + onKeyEvent: _onKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text("Step 1: Press a hotkey for **Gear Up**."), + Text("Step 2: Press a hotkey for **Gear Down**."), + SizedBox(height: 20), + ListTile( + leading: Icon(Icons.arrow_upward), + title: Text("Gear Up Hotkey"), + subtitle: Text(_formatKeys(_gearUpHotkey)), + ), + ListTile( + leading: Icon(Icons.arrow_downward), + title: Text("Gear Down Hotkey"), + subtitle: Text(_formatKeys(_gearDownHotkey)), + ), + if (_pressedKeys.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8.0), + child: Text("Recording: ${_formatKeys(_pressedKeys)}", style: TextStyle(color: Colors.blue)), + ), + ], + ), + ), + actions: [TextButton(onPressed: () => Navigator.of(context).pop(null), child: Text("Cancel"))], + ); + } +} diff --git a/lib/widgets/menu.dart b/lib/widgets/menu.dart index 27426184..f70025c9 100644 --- a/lib/widgets/menu.dart +++ b/lib/widgets/menu.dart @@ -1,6 +1,21 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:swift_control/main.dart'; import 'package:url_launcher/url_launcher_string.dart'; +List buildMenuButtons() { + return [ + TextButton( + onPressed: () { + launchUrlString('https://paypal.me/boni'); + }, + child: Text('Donate ♥'), + ), + const MenuButton(), + SizedBox(width: 8), + ]; +} + class MenuButton extends StatelessWidget { const MenuButton({super.key}); @@ -9,18 +24,31 @@ class MenuButton extends StatelessWidget { return PopupMenuButton( itemBuilder: (c) => [ + if (kDebugMode) ...[ + PopupMenuItem( + child: Text('Gear up'), + onTap: () { + Future.delayed(Duration(seconds: 2)).then((_) { + actionHandler.increaseGear(); + }); + }, + ), + PopupMenuItem( + child: Text('Gear down'), + onTap: () { + Future.delayed(Duration(seconds: 2)).then((_) { + actionHandler.decreaseGear(); + }); + }, + ), + PopupMenuItem(child: PopupMenuDivider()), + ], PopupMenuItem( child: Text('Feedback'), onTap: () { launchUrlString('https://github.com/jonasbark/swiftcontrol/issues'); }, ), - PopupMenuItem( - child: Text('Donate 🫶'), - onTap: () { - launchUrlString('https://paypal.me/boni'); - }, - ), PopupMenuItem( child: Text('License'), onTap: () { diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index fe1f8d99..870916df 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -7,12 +7,14 @@ import Foundation import flutter_local_notifications import keypress_simulator_macos +import shared_preferences_foundation import universal_ble import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) KeypressSimulatorMacosPlugin.register(with: registry.registrar(forPlugin: "KeypressSimulatorMacosPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) UniversalBlePlugin.register(with: registry.registrar(forPlugin: "UniversalBlePlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) } diff --git a/macos/Podfile.lock b/macos/Podfile.lock index 0b10f2f8..7ee9c59d 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -4,6 +4,9 @@ PODS: - FlutterMacOS (1.0.0) - keypress_simulator_macos (0.0.1): - FlutterMacOS + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS - universal_ble (0.0.1): - Flutter - FlutterMacOS @@ -14,6 +17,7 @@ DEPENDENCIES: - flutter_local_notifications (from `Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos`) - FlutterMacOS (from `Flutter/ephemeral`) - keypress_simulator_macos (from `Flutter/ephemeral/.symlinks/plugins/keypress_simulator_macos/macos`) + - shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`) - universal_ble (from `Flutter/ephemeral/.symlinks/plugins/universal_ble/darwin`) - url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`) @@ -24,6 +28,8 @@ EXTERNAL SOURCES: :path: Flutter/ephemeral keypress_simulator_macos: :path: Flutter/ephemeral/.symlinks/plugins/keypress_simulator_macos/macos + shared_preferences_foundation: + :path: Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin universal_ble: :path: Flutter/ephemeral/.symlinks/plugins/universal_ble/darwin url_launcher_macos: @@ -33,6 +39,7 @@ SPEC CHECKSUMS: flutter_local_notifications: 4ccab5b7a22835214a6672e3f9c5e8ae207dab36 FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 keypress_simulator_macos: f8556f9101f9f2f175652e0bceddf0fe82a4c6b2 + shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78 universal_ble: cf52a7b3fd2e7c14d6d7262e9fdadb72ab6b88a6 url_launcher_macos: c82c93949963e55b228a30115bd219499a6fe404 diff --git a/pubspec.lock b/pubspec.lock index ed0c85f5..f9ccc7f0 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -136,6 +136,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.4" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" fixnum: dependency: transitive description: @@ -367,6 +375,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" permission_handler: dependency: "direct main" description: @@ -423,6 +455,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" plugin_platform_interface: dependency: transitive description: @@ -455,6 +495,62 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + url: "https://pub.dev" + source: hosted + version: "2.5.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "3ec7210872c4ba945e3244982918e502fa2bfb5230dff6832459ca0e1879b7ad" + url: "https://pub.dev" + source: hosted + version: "2.4.8" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" sky_engine: dependency: transitive description: flutter diff --git a/pubspec.yaml b/pubspec.yaml index da5790b2..5096fed3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: swift_control description: "SwiftControl - Control your virtual riding" publish_to: 'none' # Remove this line if you wish to publish to pub.dev -version: 1.0.6+0 +version: 1.0.7+0 environment: sdk: ^3.7.0 @@ -18,6 +18,7 @@ dependencies: dartx: any pointycastle: any keypress_simulator: ^0.2.0 + shared_preferences: ^2.5.3 flex_color_scheme: ^8.2.0 accessibility: path: accessibility