From 6ba266bf64c8fce28970e84fe224e27e43bdff51 Mon Sep 17 00:00:00 2001 From: Jonas Bark Date: Thu, 9 Oct 2025 22:37:07 +0200 Subject: [PATCH] initial fixes --- lib/pages/touch_area.dart | 62 +++++----- lib/utils/keymap/keymap.dart | 69 ++--------- lib/utils/settings/settings.dart | 162 ++++++++++--------------- macos/Runner.xcodeproj/project.pbxproj | 11 +- test/percentage_keymap_test.dart | 19 +-- 5 files changed, 113 insertions(+), 210 deletions(-) diff --git a/lib/pages/touch_area.dart b/lib/pages/touch_area.dart index d16be10b..a341d6d6 100644 --- a/lib/pages/touch_area.dart +++ b/lib/pages/touch_area.dart @@ -9,7 +9,6 @@ import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; import 'package:keypress_simulator/keypress_simulator.dart'; import 'package:swift_control/main.dart'; -import 'package:swift_control/utils/actions/remote.dart'; import 'package:swift_control/widgets/keymap_explanation.dart'; import 'package:swift_control/widgets/menu.dart'; import 'package:swift_control/widgets/testbed.dart'; @@ -45,33 +44,29 @@ class _TouchAreaSetupPageState extends State { final picker = ImagePicker(); final result = await picker.pickImage(source: ImageSource.gallery); if (result != null) { - setState(() { - _backgroundImage = File(result.path); + final image = File(result.path); - // need to decode image to get its size so we can have a percentage mapping - if (actionHandler is RemoteActions) { - decodeImageFromList(_backgroundImage!.readAsBytesSync()).then((decodedImage) { - // calculate image rectangle in the current screen, given it's boxfit contain - final screenSize = MediaQuery.sizeOf(context); - final imageAspectRatio = decodedImage.width / decodedImage.height; - final screenAspectRatio = screenSize.width / screenSize.height; - if (imageAspectRatio > screenAspectRatio) { - // image is wider than screen - final width = screenSize.width; - final height = width / imageAspectRatio; - final top = (screenSize.height - height) / 2; - _imageRect = Rect.fromLTWH(0, top, width, height); - } else { - // image is taller than screen - final height = screenSize.height; - final width = height * imageAspectRatio; - final left = (screenSize.width - width) / 2; - _imageRect = Rect.fromLTWH(left, 0, width, height); - } - setState(() {}); - }); - } - }); + // need to decode image to get its size so we can have a percentage mapping + final decodedImage = await decodeImageFromList(image.readAsBytesSync()); + // calculate image rectangle in the current screen, given it's boxfit contain + final screenSize = MediaQuery.sizeOf(context); + final imageAspectRatio = decodedImage.width / decodedImage.height; + final screenAspectRatio = screenSize.width / screenSize.height; + if (imageAspectRatio > screenAspectRatio) { + // image is wider than screen + final width = screenSize.width; + final height = width / imageAspectRatio; + final top = (screenSize.height - height) / 2; + _imageRect = Rect.fromLTWH(0, top, width, height); + } else { + // image is taller than screen + final height = screenSize.height; + final width = height * imageAspectRatio; + final left = (screenSize.width - width) / 2; + _imageRect = Rect.fromLTWH(left, 0, width, height); + } + _backgroundImage = image; + setState(() {}); } } @@ -101,6 +96,11 @@ class _TouchAreaSetupPageState extends State { void initState() { super.initState(); + // initialize _imageRect by using Flutter view size + final flutterView = WidgetsBinding.instance.platformDispatcher.views.first; + final size = flutterView.physicalSize / flutterView.devicePixelRatio; + _imageRect = Rect.fromLTWH(0, 0, size.width, size.height); + // Force landscape orientation during keymap editing SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]); @@ -385,14 +385,8 @@ class _TouchAreaSetupPageState extends State { ), ), ), - // draw image rect for debugging - if (_imageRect != null && _backgroundImage != null) - Positioned.fromRect( - rect: _imageRect!, - child: Container(decoration: BoxDecoration(border: Border.all(color: Colors.green, width: 2))), - ), - if (actionHandler is! RemoteActions || _imageRect != null) + if (_imageRect != null) ...?actionHandler.supportedApp?.keymap.keyPairs.map((keyPair) { final Offset offset; diff --git a/lib/utils/keymap/keymap.dart b/lib/utils/keymap/keymap.dart index b5797b9c..71a6ef85 100644 --- a/lib/utils/keymap/keymap.dart +++ b/lib/utils/keymap/keymap.dart @@ -1,10 +1,8 @@ import 'dart:convert'; -import 'dart:ui'; import 'package:dartx/dartx.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; import 'package:swift_control/utils/keymap/buttons.dart'; class Keymap { @@ -90,39 +88,14 @@ class KeyPair { // encode to save in preferences // Always store as percentages for better compatibility across devices final Map touchPosData; - + if (touchPosition == Offset.zero) { // Special case: zero position means no touch (e.g., keyboard shortcut only) - touchPosData = { - 'x_percent': 0.0, - 'y_percent': 0.0, - }; + touchPosData = {'x': 0.0, 'y': 0.0}; } else { - // Get screen size for conversion - Size? screenSize; - try { - final view = WidgetsBinding.instance.platformDispatcher.views.first; - screenSize = view.physicalSize / view.devicePixelRatio; - } catch (e) { - // Fallback: if no screen size available, use a reasonable default (1920x1080) - screenSize = null; - } - - if (screenSize != null) { - // Normal case: convert pixels to percentages - touchPosData = { - 'x_percent': touchPosition.dx / screenSize.width, - 'y_percent': touchPosition.dy / screenSize.height, - }; - } else { - // Fallback to default screen size - touchPosData = { - 'x_percent': touchPosition.dx / 1920.0, - 'y_percent': touchPosition.dy / 1080.0, - }; - } + touchPosData = {'x': touchPosition.dx, 'y': touchPosition.dy}; } - + return jsonEncode({ 'actions': buttons.map((e) => e.name).toList(), 'logicalKey': logicalKey?.keyId.toString() ?? '0', @@ -138,39 +111,11 @@ class KeyPair { if (decoded['actions'] == null || decoded['logicalKey'] == null || decoded['physicalKey'] == null) { return null; } - + // Support both percentage-based (new) and pixel-based (old) formats for backward compatibility final touchPosData = decoded['touchPosition']; - final Offset touchPosition; - - if (touchPosData.containsKey('x_percent') && touchPosData.containsKey('y_percent')) { - // New percentage-based format - convert to pixels - Size? screenSize; - try { - final view = WidgetsBinding.instance.platformDispatcher.views.first; - screenSize = view.physicalSize / view.devicePixelRatio; - } catch (e) { - screenSize = null; - } - - if (screenSize != null) { - touchPosition = Offset( - touchPosData['x_percent'] * screenSize.width, - touchPosData['y_percent'] * screenSize.height, - ); - } else { - // Fallback if no screen size available - touchPosition = Offset.zero; - } - } else { - // Old pixel-based format - read the pixels directly - // These will be converted to percentages when saved next time - touchPosition = Offset( - (touchPosData['x'] as num).toDouble(), - (touchPosData['y'] as num).toDouble(), - ); - } - + final Offset touchPosition = Offset((touchPosData['x'] as num).toDouble(), (touchPosData['y'] as num).toDouble()); + return KeyPair( buttons: decoded['actions'] diff --git a/lib/utils/settings/settings.dart b/lib/utils/settings/settings.dart index c58515b6..cf3bb79e 100644 --- a/lib/utils/settings/settings.dart +++ b/lib/utils/settings/settings.dart @@ -9,10 +9,10 @@ import '../../main.dart'; import '../keymap/apps/custom_app.dart'; class Settings { - late final SharedPreferences _prefs; + late final SharedPreferences prefs; Future init() async { - _prefs = await SharedPreferences.getInstance(); + prefs = await SharedPreferences.getInstance(); try { // Get screen size for migrations @@ -25,32 +25,29 @@ class Settings { } // Handle migration from old "customapp" key to new "customapp_Custom" key - if (_prefs.containsKey('customapp') && !_prefs.containsKey('customapp_Custom')) { - final oldCustomApp = _prefs.getStringList('customapp'); + if (prefs.containsKey('customapp') && !prefs.containsKey('customapp_Custom')) { + final oldCustomApp = prefs.getStringList('customapp'); if (oldCustomApp != null) { // Migrate pixel-based to percentage-based if screen size available if (screenSize != null) { final migratedData = await _migrateToPercentageBased(oldCustomApp, screenSize); - await _prefs.setStringList('customapp_Custom', migratedData); + await prefs.setStringList('customapp_Custom', migratedData); } else { - await _prefs.setStringList('customapp_Custom', oldCustomApp); + await prefs.setStringList('customapp_Custom', oldCustomApp); } - await _prefs.remove('customapp'); + await prefs.remove('customapp'); } } - - // Migrate all existing custom profiles to percentage-based format - await _migrateAllProfilesToPercentageBased(screenSize); - - final appName = _prefs.getString('app'); + + final appName = prefs.getString('app'); if (appName == null) { return; } - + // Check if it's a custom app with a profile name - if (appName.startsWith('Custom') || _prefs.containsKey('customapp_$appName')) { + if (appName.startsWith('Custom') || prefs.containsKey('customapp_$appName')) { final customApp = CustomApp(profileName: appName); - final appSetting = _prefs.getStringList('customapp_$appName'); + final appSetting = prefs.getStringList('customapp_$appName'); if (appSetting != null) { customApp.decodeKeymap(appSetting); } @@ -61,74 +58,70 @@ class Settings { } } catch (e) { // couldn't decode, reset - await _prefs.clear(); + await prefs.clear(); rethrow; } } Future reset() async { - await _prefs.clear(); + await prefs.clear(); actionHandler.init(null); } Future setApp(SupportedApp app) async { if (app is CustomApp) { - await _prefs.setStringList('customapp_${app.profileName}', app.encodeKeymap()); + await prefs.setStringList('customapp_${app.profileName}', app.encodeKeymap()); } - await _prefs.setString('app', app.name); + await prefs.setString('app', app.name); } - + List getCustomAppProfiles() { // Get all keys starting with 'customapp_' - final keys = _prefs.getKeys().where((key) => key.startsWith('customapp_')).toList(); + final keys = prefs.getKeys().where((key) => key.startsWith('customapp_')).toList(); return keys.map((key) => key.replaceFirst('customapp_', '')).toList(); } - + List? getCustomAppKeymap(String profileName) { - return _prefs.getStringList('customapp_$profileName'); + return prefs.getStringList('customapp_$profileName'); } - + Future deleteCustomAppProfile(String profileName) async { - await _prefs.remove('customapp_$profileName'); + await prefs.remove('customapp_$profileName'); // If the current app is the one being deleted, reset - if (_prefs.getString('app') == profileName) { + if (prefs.getString('app') == profileName) { actionHandler.init(null); - await _prefs.remove('app'); + await prefs.remove('app'); } } - + Future duplicateCustomAppProfile(String sourceProfileName, String newProfileName) async { - final sourceData = _prefs.getStringList('customapp_$sourceProfileName'); + final sourceData = prefs.getStringList('customapp_$sourceProfileName'); if (sourceData != null) { - await _prefs.setStringList('customapp_$newProfileName', sourceData); + await prefs.setStringList('customapp_$newProfileName', sourceData); } } - + String? exportCustomAppProfile(String profileName) { - final data = _prefs.getStringList('customapp_$profileName'); + final data = prefs.getStringList('customapp_$profileName'); if (data == null) return null; - + // Export as JSON with metadata - return jsonEncode({ - 'version': 1, - 'profileName': profileName, - 'keymap': data, - }); + return jsonEncode({'version': 1, 'profileName': profileName, 'keymap': data}); } - + Future importCustomAppProfile(String jsonData, {String? newProfileName}) async { try { final decoded = jsonDecode(jsonData); - + // Validate the structure if (decoded['version'] == null || decoded['keymap'] == null) { return false; } - + final profileName = newProfileName ?? decoded['profileName'] ?? 'Imported'; final keymap = List.from(decoded['keymap']); - - await _prefs.setStringList('customapp_$profileName', keymap); + + await prefs.setStringList('customapp_$profileName', keymap); return true; } catch (e) { return false; @@ -136,81 +129,54 @@ class Settings { } String? getLastSeenVersion() { - return _prefs.getString('last_seen_version'); + return prefs.getString('last_seen_version'); } Future setLastSeenVersion(String version) async { - await _prefs.setString('last_seen_version', version); + await prefs.setString('last_seen_version', version); } bool getVibrationEnabled() { - return _prefs.getBool('vibration_enabled') ?? true; + return prefs.getBool('vibration_enabled') ?? true; } Future setVibrationEnabled(bool enabled) async { - await _prefs.setBool('vibration_enabled', enabled); + await prefs.setBool('vibration_enabled', enabled); } Future> _migrateToPercentageBased(List keymapData, Size screenSize) async { final migratedData = []; - - for (final encodedKeyPair in keymapData) { - try { - final decoded = jsonDecode(encodedKeyPair); + + final needMigrations = keymapData.associateWith((encodedKeyPair) { + final decoded = jsonDecode(encodedKeyPair); + final touchPosData = decoded['touchPosition']; + + // Convert pixel-based to percentage-based + final x = (touchPosData['x'] as num).toDouble(); + final y = (touchPosData['y'] as num).toDouble(); + return x > 1.0 || y > 1.0; + }); + + for (final entry in needMigrations.entries) { + if (entry.value) { + final decoded = jsonDecode(entry.key); final touchPosData = decoded['touchPosition']; - - // Check if already percentage-based - if (touchPosData.containsKey('x_percent') && touchPosData.containsKey('y_percent')) { - migratedData.add(encodedKeyPair); - continue; - } - + // Convert pixel-based to percentage-based final x = (touchPosData['x'] as num).toDouble(); final y = (touchPosData['y'] as num).toDouble(); - - decoded['touchPosition'] = { - 'x_percent': x / screenSize.width, - 'y_percent': y / screenSize.height, - }; - + final newX = (x / screenSize.width).clamp(0.0, 1.0); + final newY = (y / screenSize.height).clamp(0.0, 1.0); + + // Update the JSON structure + decoded['touchPosition'] = {'x': newX, 'y': newY}; + migratedData.add(jsonEncode(decoded)); - } catch (e) { - // If can't decode, keep original - migratedData.add(encodedKeyPair); + } else { + migratedData.add(entry.key); } } - + return migratedData; } - - Future _migrateAllProfilesToPercentageBased(Size? screenSize) async { - if (screenSize == null) return; - - final profiles = getCustomAppProfiles(); - for (final profile in profiles) { - final keymap = _prefs.getStringList('customapp_$profile'); - if (keymap != null) { - // Check if migration is needed - bool needsMigration = false; - for (final encodedKeyPair in keymap) { - try { - final decoded = jsonDecode(encodedKeyPair); - final touchPosData = decoded['touchPosition']; - if (!touchPosData.containsKey('x_percent') || !touchPosData.containsKey('y_percent')) { - needsMigration = true; - break; - } - } catch (e) { - // Skip if can't decode - } - } - - if (needsMigration) { - final migratedData = await _migrateToPercentageBased(keymap, screenSize); - await _prefs.setStringList('customapp_$profile', migratedData); - } - } - } - } } diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj index 7895e371..1f7e034e 100755 --- a/macos/Runner.xcodeproj/project.pbxproj +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -712,11 +712,9 @@ CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; - "CODE_SIGN_IDENTITY[sdk=macosx*]" = "3rd Party Mac Developer Application"; - CODE_SIGN_STYLE = Manual; + CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - DEVELOPMENT_TEAM = ""; - "DEVELOPMENT_TEAM[sdk=macosx*]" = UZRHKPVWN9; + DEVELOPMENT_TEAM = UZRHKPVWN9; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = SwiftControl; @@ -727,7 +725,6 @@ ); PRODUCT_BUNDLE_IDENTIFIER = de.jonasbark.swiftcontrol.darwin; PROVISIONING_PROFILE_SPECIFIER = ""; - "PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = "mac app store"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; }; @@ -740,8 +737,8 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; - CODE_SIGN_IDENTITY = "Apple Distribution"; - "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Distribution: JONAS TASSILO BARK (UZRHKPVWN9)"; + CODE_SIGN_IDENTITY = "Apple Development"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "3rd Party Mac Developer Application"; CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; DEVELOPMENT_TEAM = ""; diff --git a/test/percentage_keymap_test.dart b/test/percentage_keymap_test.dart index 74cc9291..27718f22 100644 --- a/test/percentage_keymap_test.dart +++ b/test/percentage_keymap_test.dart @@ -1,5 +1,3 @@ -import 'dart:ui'; - import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:swift_control/utils/keymap/buttons.dart'; @@ -9,7 +7,7 @@ void main() { group('Percentage-based Keymap Tests', () { test('Should encode touch position as percentage using fallback screen size', () { final keyPair = KeyPair( - buttons: [ZwiftButton.leftButton], + buttons: [ZwiftButton.paddleRight], physicalKey: null, logicalKey: null, touchPosition: Offset(960, 540), // Center of 1920x1080 fallback @@ -24,7 +22,7 @@ void main() { test('Should encode touch position as percentages with fallback when screen size not available', () { final keyPair = KeyPair( - buttons: [ZwiftButton.leftButton], + buttons: [ZwiftButton.paddleRight], physicalKey: null, logicalKey: null, touchPosition: Offset(960, 540), // Center of 1920x1080 fallback @@ -38,7 +36,8 @@ void main() { }); test('Should decode percentage-based touch position correctly', () { - final encoded = '{"actions":["leftButton"],"logicalKey":"0","physicalKey":"0","touchPosition":{"x_percent":0.5,"y_percent":0.5},"isLongPress":false}'; + final encoded = + '{"actions":["leftButton"],"logicalKey":"0","physicalKey":"0","touchPosition":{"x_percent":0.5,"y_percent":0.5},"isLongPress":false}'; final keyPair = KeyPair.decode(encoded); expect(keyPair, isNotNull); @@ -47,7 +46,8 @@ void main() { }); test('Should decode pixel-based touch position correctly (backward compatibility)', () { - final encoded = '{"actions":["leftButton"],"logicalKey":"0","physicalKey":"0","touchPosition":{"x":300,"y":600},"isLongPress":false}'; + final encoded = + '{"actions":["leftButton"],"logicalKey":"0","physicalKey":"0","touchPosition":{"x":300,"y":600},"isLongPress":false}'; final keyPair = KeyPair.decode(encoded); expect(keyPair, isNotNull); @@ -57,7 +57,7 @@ void main() { test('Should handle zero touch position correctly', () { final keyPair = KeyPair( - buttons: [ZwiftButton.leftButton], + buttons: [ZwiftButton.paddleRight], physicalKey: PhysicalKeyboardKey.keyA, logicalKey: LogicalKeyboardKey.keyA, touchPosition: Offset.zero, @@ -72,7 +72,7 @@ void main() { test('Should encode and decode with fallback screen size', () { final keyPair = KeyPair( - buttons: [ZwiftButton.leftButton], + buttons: [ZwiftButton.paddleRight], physicalKey: null, logicalKey: null, touchPosition: Offset(480, 270), // 25% of 1920x1080 @@ -89,7 +89,8 @@ void main() { }); test('Should handle decoding when no screen size available', () { - final encoded = '{"actions":["leftButton"],"logicalKey":"0","physicalKey":"0","touchPosition":{"x_percent":0.5,"y_percent":0.5},"isLongPress":false}'; + final encoded = + '{"actions":["leftButton"],"logicalKey":"0","physicalKey":"0","touchPosition":{"x_percent":0.5,"y_percent":0.5},"isLongPress":false}'; final keyPair = KeyPair.decode(encoded); expect(keyPair, isNotNull);