initial fixes

This commit is contained in:
Jonas Bark
2025-10-09 22:37:07 +02:00
parent 08e74b7680
commit 6ba266bf64
5 changed files with 113 additions and 210 deletions

View File

@@ -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<TouchAreaSetupPage> {
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<TouchAreaSetupPage> {
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<TouchAreaSetupPage> {
),
),
),
// 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;

View File

@@ -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<String, double> 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']

View File

@@ -9,10 +9,10 @@ import '../../main.dart';
import '../keymap/apps/custom_app.dart';
class Settings {
late final SharedPreferences _prefs;
late final SharedPreferences prefs;
Future<void> 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<void> reset() async {
await _prefs.clear();
await prefs.clear();
actionHandler.init(null);
}
Future<void> 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<String> 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<String>? getCustomAppKeymap(String profileName) {
return _prefs.getStringList('customapp_$profileName');
return prefs.getStringList('customapp_$profileName');
}
Future<void> 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<void> 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<bool> 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<String>.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<void> 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<void> setVibrationEnabled(bool enabled) async {
await _prefs.setBool('vibration_enabled', enabled);
await prefs.setBool('vibration_enabled', enabled);
}
Future<List<String>> _migrateToPercentageBased(List<String> keymapData, Size screenSize) async {
final migratedData = <String>[];
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<void> _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);
}
}
}
}
}

View File

@@ -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 = "";

View File

@@ -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);