From c8a3e70c38f55becb66b413ad51152371a862870 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Thu, 3 Dec 2026 13:34:24 -0600 Subject: [PATCH 1/4] feat(amounts): give the device's number format a key of its own Util.getSymbolsFor looks a locale string up in intl, falling back to its language. Where the device writes numbers otherwise, as English with a German region does (intl has no en_DE, so it falls back to en and gives "."), amounts are typed and shown with the wrong decimal separator while the system's number keyboard offers ",". Util.deviceNumberFormat takes the separators the device reports and returns the key getSymbolsFor gives them by: the locale itself where intl already has those separators, else a key of its own. A locale asked for by name, like the canonical "en_US", keeps intl's separators. --- lib/utilities/util.dart | 63 +++++++++ .../util_device_number_format_test.dart | 131 ++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 test/utilities/util_device_number_format_test.dart diff --git a/lib/utilities/util.dart b/lib/utilities/util.dart index e5a38eafe..a4e2a515c 100644 --- a/lib/utilities/util.dart +++ b/lib/utilities/util.dart @@ -35,7 +35,70 @@ abstract class Util { static double? screenWidth; static bool? isIpad; + /// The device's number formats that intl has under no locale, by the key + /// [deviceNumberFormat] gave them. + static final Map _deviceNumberSymbols = {}; + + /// The key [getSymbolsFor] takes for the number format the device reports: + /// [locale] itself where intl writes numbers there with the same + /// separators, and otherwise a key of its own, as for English with a German + /// region (intl has no en_DE and falls back to en) or separators customized + /// in the system settings. A locale asked for by name, like "en_US", keeps + /// intl's separators either way. + /// + /// A separator that is null takes the locale's. An empty + /// [groupingSeparator] writes numbers ungrouped, as does one that would be + /// the same as the decimal separator. + static String deviceNumberFormat({ + String? locale, + String? decimalSeparator, + String? groupingSeparator, + }) { + final name = locale == null || locale.isEmpty ? "en_US" : locale; + final base = + getSymbolsFor(locale: name) ?? + numberFormatSymbols["en_US"] as NumberSymbols; + final decimal = decimalSeparator == null || decimalSeparator.isEmpty + ? base.DECIMAL_SEP + : decimalSeparator; + String group = groupingSeparator ?? base.GROUP_SEP; + if (group == decimal) { + group = ""; + } + if (decimal == base.DECIMAL_SEP && group == base.GROUP_SEP) { + return name; + } + + final key = "$name@decimal=$decimal;group=$group"; + _deviceNumberSymbols.putIfAbsent( + key, + () => NumberSymbols( + NAME: base.NAME, + DECIMAL_SEP: decimal, + GROUP_SEP: group, + PERCENT: base.PERCENT, + ZERO_DIGIT: base.ZERO_DIGIT, + PLUS_SIGN: base.PLUS_SIGN, + MINUS_SIGN: base.MINUS_SIGN, + EXP_SYMBOL: base.EXP_SYMBOL, + PERMILL: base.PERMILL, + INFINITY: base.INFINITY, + NAN: base.NAN, + DECIMAL_PATTERN: base.DECIMAL_PATTERN, + SCIENTIFIC_PATTERN: base.SCIENTIFIC_PATTERN, + PERCENT_PATTERN: base.PERCENT_PATTERN, + CURRENCY_PATTERN: base.CURRENCY_PATTERN, + DEF_CURRENCY_CODE: base.DEF_CURRENCY_CODE, + ), + ); + return key; + } + static NumberSymbols? getSymbolsFor({required String locale}) { + final device = _deviceNumberSymbols[locale]; + if (device != null) { + return device; + } return _numberSymbolsCache.putIfAbsent(locale, () { final exactSymbols = numberFormatSymbols[locale]; if (exactSymbols is NumberSymbols) { diff --git a/test/utilities/util_device_number_format_test.dart b/test/utilities/util_device_number_format_test.dart new file mode 100644 index 000000000..c4602e13b --- /dev/null +++ b/test/utilities/util_device_number_format_test.dart @@ -0,0 +1,131 @@ +import 'package:decimal/decimal.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/util.dart'; + +void main() { + group("Util.deviceNumberFormat", () { + test("is the locale where intl has the device's separators", () { + expect( + Util.deviceNumberFormat( + locale: "en_US", + decimalSeparator: ".", + groupingSeparator: ",", + ), + "en_US", + ); + expect( + Util.deviceNumberFormat( + locale: "de_DE", + decimalSeparator: ",", + groupingSeparator: ".", + ), + "de_DE", + ); + expect(Util.deviceNumberFormat(locale: "fr_FR"), "fr_FR"); + expect(Util.deviceNumberFormat(), "en_US"); + }); + + test("has a key of its own for a region intl doesn't know", () { + // English with a German region: intl has no en_DE and falls back to en. + final key = Util.deviceNumberFormat( + locale: "en_DE", + decimalSeparator: ",", + groupingSeparator: ".", + ); + + expect(key, isNot("en_DE")); + expect(Util.getSymbolsFor(locale: key)?.DECIMAL_SEP, ","); + expect(Util.getSymbolsFor(locale: key)?.GROUP_SEP, "."); + expect(Util.getSymbolsFor(locale: "en_DE")?.DECIMAL_SEP, "."); + }); + + test("leaves a locale asked for by name as intl has it", () { + // Separators customized in the system settings. + final key = Util.deviceNumberFormat( + locale: "en_US", + decimalSeparator: ",", + groupingSeparator: ".", + ); + + expect(key, isNot("en_US")); + expect(Util.getSymbolsFor(locale: key)?.DECIMAL_SEP, ","); + expect(Util.getSymbolsFor(locale: "en_US")?.DECIMAL_SEP, "."); + expect(Util.getSymbolsFor(locale: "en_US")?.GROUP_SEP, ","); + }); + + test("gives the same key for the same separators", () { + String key() => Util.deviceNumberFormat( + locale: "en_NL", + decimalSeparator: ",", + groupingSeparator: ".", + ); + + expect(key(), key()); + expect( + Util.deviceNumberFormat( + locale: "en_NL", + decimalSeparator: ",", + groupingSeparator: " ", + ), + isNot(key()), + ); + }); + + test("writes numbers ungrouped where the device does", () { + final key = Util.deviceNumberFormat( + locale: "en_US", + decimalSeparator: ".", + groupingSeparator: "", + ); + + expect(Util.getSymbolsFor(locale: key)?.GROUP_SEP, ""); + }); + + test("doesn't group with the decimal separator", () { + final key = Util.deviceNumberFormat( + locale: "en_US", + decimalSeparator: ",", + groupingSeparator: ",", + ); + + expect(Util.getSymbolsFor(locale: key)?.DECIMAL_SEP, ","); + expect(Util.getSymbolsFor(locale: key)?.GROUP_SEP, ""); + }); + + test("gives a language intl doesn't know the device's separators", () { + final key = Util.deviceNumberFormat( + locale: "yo_NG", + decimalSeparator: ",", + groupingSeparator: ".", + ); + + expect(Util.getSymbolsFor(locale: key)?.DECIMAL_SEP, ","); + }); + + test("is what amounts are typed and shown with", () { + final key = Util.deviceNumberFormat( + locale: "en_DE", + decimalSeparator: ",", + groupingSeparator: ".", + ); + + expect( + Amount.tryParseEditableAmount("1,5", locale: key, fractionDigits: 8), + Amount.fromDecimal(Decimal.parse("1.5"), fractionDigits: 8), + ); + expect( + Amount.tryParseEditableAmount("1.5", locale: key, fractionDigits: 8), + isNull, + ); + expect( + Amount.formatFixedDecimal( + Decimal.parse("1.5"), + fractionDigits: 2, + locale: key, + ), + "1,50", + ); + }); + }); +} From 03cce1b8ee46364eab3784fad3fc5c51af7cf5db Mon Sep 17 00:00:00 2001 From: sneurlax Date: Thu, 3 Dec 2026 13:34:24 -0600 Subject: [PATCH 2/4] feat(locale): read the device's locale settings with cs_locale devicelocale gives a locale name, from which the decimal separator was looked up in intl. On iOS an app that declares only English gets English as its language, so a German iPhone reports en_DE and amounts took "." while the decimal pad shows ",". In an iOS 27 simulator that happened for en_DE, en_FR, en_NL, de_DE and separators customized apart from the region; cs_locale matched the decimal pad in each. Windows was fixed to en_US. LocaleService now reads the separators from the system with cs_locale on every platform, and keys them with Util.deviceNumberFormat. It also follows the system's announcements, so a number format changed on its own, which Flutter doesn't report, reaches the amount fields too. cs_locale is pinned to the 0.1.0 release commit until it is on pub.dev; 0.0.1 fails to configure under this app's Android Gradle plugin. --- lib/main.dart | 1 + lib/services/locale_service.dart | 60 ++++++++- pubspec.lock | 17 +-- .../ios/Runner.xcodeproj/project.pbxproj | 5 - .../macos/Runner.xcodeproj/project.pbxproj | 3 - .../templates/pubspec.template.yaml | 7 +- test/services/locale_service_test.dart | 121 ++++++++++++++++++ 7 files changed, 192 insertions(+), 22 deletions(-) create mode 100644 test/services/locale_service_test.dart diff --git a/lib/main.dart b/lib/main.dart index e96cccd99..1bee639b0 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -534,6 +534,7 @@ class _MaterialAppWithThemeState extends ConsumerState ref .read(localeServiceChangeNotifierProvider.notifier) .loadLocale(notify: false); + ref.read(localeServiceChangeNotifierProvider.notifier).follow(); WidgetsBinding.instance.addPostFrameCallback((_) async { //Add themes path to provider diff --git a/lib/services/locale_service.dart b/lib/services/locale_service.dart index 8cfb6f765..40c723f08 100644 --- a/lib/services/locale_service.dart +++ b/lib/services/locale_service.dart @@ -8,22 +8,72 @@ * */ -import 'dart:io'; +import 'dart:async'; -import 'package:devicelocale/devicelocale.dart'; +import 'package:cs_locale/cs_locale.dart'; import 'package:flutter/material.dart'; +import '../utilities/logger.dart'; +import '../utilities/util.dart'; + class LocaleService extends ChangeNotifier { + LocaleService({this._csLocale = const CsLocale()}); + + final CsLocale _csLocale; + StreamSubscription? _subscription; + String _locale = "en_US"; // use default + /// The device's number format, as the key [Util.getSymbolsFor] takes. See + /// [Util.deviceNumberFormat]. String get locale => _locale; Future loadLocale({bool notify = true}) async { - _locale = Platform.isWindows - ? "en_US" - : (await Devicelocale.currentAsLocale)?.toString() ?? "en_US"; + final LocaleSettings settings; + try { + settings = await _csLocale.current(); + } catch (e, s) { + Logging.instance.w( + "Could not read the device's locale settings", + error: e, + stackTrace: s, + ); + return; + } + _apply(settings, notify: notify); + } + + /// Follows the device's locale settings from now on, including a number + /// format changed apart from the languages, which Flutter doesn't report. + void follow() { + _subscription ??= _csLocale.settings.listen( + (settings) => _apply(settings, notify: true), + onError: (Object e, StackTrace s) => Logging.instance.w( + "Could not follow the device's locale settings", + error: e, + stackTrace: s, + ), + ); + } + + void _apply(LocaleSettings settings, {required bool notify}) { + final locale = Util.deviceNumberFormat( + locale: settings.locale?.toString(), + decimalSeparator: settings.decimalSeparator, + groupingSeparator: settings.groupingSeparator, + ); + if (locale == _locale) { + return; + } + _locale = locale; if (notify) { notifyListeners(); } } + + @override + void dispose() { + _subscription?.cancel(); + super.dispose(); + } } diff --git a/pubspec.lock b/pubspec.lock index 1a56118de..3d96ecf1b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -427,6 +427,15 @@ packages: url: "https://pub.dev" source: hosted version: "2.9.0" + cs_locale: + dependency: "direct main" + description: + path: "." + ref: cf9eae01b49b7b812df48723ccdc1f0852a9ff95 + resolved-ref: cf9eae01b49b7b812df48723ccdc1f0852a9ff95 + url: "https://github.com/sneurlax/cs_locale.git" + source: git + version: "0.1.0" cs_monero: dependency: "direct main" description: @@ -804,14 +813,6 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.3" - devicelocale: - dependency: "direct main" - description: - name: devicelocale - sha256: f38dd07265ddd5ede22253d99c7beabb09e0b5b3d36f1f785086b8ca28c27673 - url: "https://pub.dev" - source: hosted - version: "0.9.1" digest_auth: dependency: "direct main" description: diff --git a/scripts/app_config/templates/ios/Runner.xcodeproj/project.pbxproj b/scripts/app_config/templates/ios/Runner.xcodeproj/project.pbxproj index baf3d0e79..9784be95d 100644 --- a/scripts/app_config/templates/ios/Runner.xcodeproj/project.pbxproj +++ b/scripts/app_config/templates/ios/Runner.xcodeproj/project.pbxproj @@ -304,7 +304,6 @@ "${PODS_ROOT}/../.symlinks/plugins/cs_salvium_flutter_libs_ios/ios/Frameworks/SalviumWallet.framework", "${BUILT_PRODUCTS_DIR}/cs_salvium_flutter_libs_ios/cs_salvium_flutter_libs_ios.framework", "${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework", - "${BUILT_PRODUCTS_DIR}/devicelocale/devicelocale.framework", "${BUILT_PRODUCTS_DIR}/file_picker/file_picker.framework", "${PODS_ROOT}/../.symlinks/plugins/flutter_libsparkmobile/ios/flutter_libsparkmobile.framework", "${BUILT_PRODUCTS_DIR}/flutter_local_notifications/flutter_local_notifications.framework", @@ -342,7 +341,6 @@ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SalviumWallet.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/cs_salvium_flutter_libs_ios.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/devicelocale.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/file_picker.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_libsparkmobile.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_local_notifications.framework", @@ -479,7 +477,6 @@ "\"${PODS_CONFIGURATION_BUILD_DIR}/barcode_scan2/barcode_scan2.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/connectivity/connectivity.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/cryptography_flutter/cryptography_flutter.framework/Headers\"", - "\"${PODS_CONFIGURATION_BUILD_DIR}/devicelocale/devicelocale.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_libmonero/flutter_libmonero.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_local_notifications/flutter_local_notifications.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_native_splash/flutter_native_splash.framework/Headers\"", @@ -656,7 +653,6 @@ "\"${PODS_CONFIGURATION_BUILD_DIR}/barcode_scan2/barcode_scan2.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/connectivity/connectivity.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/cryptography_flutter/cryptography_flutter.framework/Headers\"", - "\"${PODS_CONFIGURATION_BUILD_DIR}/devicelocale/devicelocale.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_libmonero/flutter_libmonero.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_local_notifications/flutter_local_notifications.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_native_splash/flutter_native_splash.framework/Headers\"", @@ -725,7 +721,6 @@ "\"${PODS_CONFIGURATION_BUILD_DIR}/barcode_scan2/barcode_scan2.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/connectivity/connectivity.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/cryptography_flutter/cryptography_flutter.framework/Headers\"", - "\"${PODS_CONFIGURATION_BUILD_DIR}/devicelocale/devicelocale.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_libmonero/flutter_libmonero.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_local_notifications/flutter_local_notifications.framework/Headers\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_native_splash/flutter_native_splash.framework/Headers\"", diff --git a/scripts/app_config/templates/macos/Runner.xcodeproj/project.pbxproj b/scripts/app_config/templates/macos/Runner.xcodeproj/project.pbxproj index 254347f27..ac48391d4 100644 --- a/scripts/app_config/templates/macos/Runner.xcodeproj/project.pbxproj +++ b/scripts/app_config/templates/macos/Runner.xcodeproj/project.pbxproj @@ -569,7 +569,6 @@ "\"${PODS_CONFIGURATION_BUILD_DIR}/connectivity_plus\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/desktop_drop\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/device_info_plus\"", - "\"${PODS_CONFIGURATION_BUILD_DIR}/devicelocale\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_local_notifications\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_secure_storage_macos\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/package_info_plus\"", @@ -720,7 +719,6 @@ "\"${PODS_CONFIGURATION_BUILD_DIR}/connectivity_plus\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/desktop_drop\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/device_info_plus\"", - "\"${PODS_CONFIGURATION_BUILD_DIR}/devicelocale\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_local_notifications\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_secure_storage_macos\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/package_info_plus\"", @@ -762,7 +760,6 @@ "\"${PODS_CONFIGURATION_BUILD_DIR}/connectivity_plus\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/desktop_drop\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/device_info_plus\"", - "\"${PODS_CONFIGURATION_BUILD_DIR}/devicelocale\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_local_notifications\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/flutter_secure_storage_macos\"", "\"${PODS_CONFIGURATION_BUILD_DIR}/package_info_plus\"", diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index b02fa80fc..f4848872d 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -179,7 +179,12 @@ dependencies: wakelock_plus: ^1.2.8 intl: ^0.19.0 html: ^0.15.6 - devicelocale: 0.9.1 + # Until cs_locale 0.1.0 is on pub.dev (cypherstack/cs_locale#4); 0.0.1 + # fails to configure under this app's Android Gradle plugin. + cs_locale: + git: + url: https://github.com/sneurlax/cs_locale.git + ref: cf9eae01b49b7b812df48723ccdc1f0852a9ff95 # 0.1.0 device_info_plus: ^12.4.0 keyboard_dismisser: ^3.0.0 another_flushbar: ^1.10.28 diff --git a/test/services/locale_service_test.dart b/test/services/locale_service_test.dart new file mode 100644 index 000000000..d69404b96 --- /dev/null +++ b/test/services/locale_service_test.dart @@ -0,0 +1,121 @@ +import 'dart:async'; + +import 'package:cs_locale/cs_locale.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/services/locale_service.dart'; +import 'package:stackwallet/utilities/util.dart'; + +const _american = LocaleSettings( + locale: Locale("en", "US"), + decimalSeparator: ".", + groupingSeparator: ",", +); + +/// A device whose settings the test sets and announces. +class _Device extends CsLocale { + LocaleSettings now = _american; + Object? failure; + final _changes = StreamController.broadcast(); + + void change(LocaleSettings settings) { + now = settings; + _changes.add(settings); + } + + @override + Future current() async { + if (failure != null) { + throw failure!; + } + return now; + } + + @override + Stream get settings => Stream.multi((listener) { + listener.add(now); + final subscription = _changes.stream.listen(listener.add); + listener.onCancel = subscription.cancel; + }); +} + +void main() { + late _Device device; + late LocaleService service; + late int notified; + + setUp(() { + device = _Device(); + service = LocaleService(csLocale: device); + notified = 0; + service.addListener(() => notified++); + }); + + tearDown(() => service.dispose()); + + test("reads the device's number format", () async { + device.now = const LocaleSettings( + locale: Locale("en", "DE"), + decimalSeparator: ",", + groupingSeparator: ".", + ); + + await service.loadLocale(); + + expect(Util.getSymbolsFor(locale: service.locale)?.DECIMAL_SEP, ","); + expect(notified, 1); + }); + + test("keeps intl's name where it has the device's separators", () async { + device.now = const LocaleSettings( + locale: Locale("de", "DE"), + decimalSeparator: ",", + groupingSeparator: ".", + ); + + await service.loadLocale(notify: false); + + expect(service.locale, "de_DE"); + expect(notified, 0); + }); + + test("keeps its locale where the device can't be read", () async { + device.failure = Exception("no native side"); + + await service.loadLocale(); + + expect(service.locale, "en_US"); + expect(notified, 0); + }); + + test("follows separators changed apart from the language", () async { + service.follow(); + await pumpEventQueue(); + expect(service.locale, "en_US"); + expect(notified, 0); + + device.change( + const LocaleSettings( + locale: Locale("en", "US"), + decimalSeparator: ",", + groupingSeparator: ".", + ), + ); + await pumpEventQueue(); + + expect(Util.getSymbolsFor(locale: service.locale)?.DECIMAL_SEP, ","); + expect(notified, 1); + + // The same format again changes nothing. + device.change( + const LocaleSettings( + locale: Locale("en", "US"), + decimalSeparator: ",", + groupingSeparator: ".", + ), + ); + await pumpEventQueue(); + + expect(notified, 1); + }); +} From 72a34fa482a6208b42960cb65252e5255e961407 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Thu, 3 Dec 2026 14:39:15 -0600 Subject: [PATCH 3/4] fix(locale): address number format regressions --- .../stack_backup_views/auto_backup_view.dart | 4 +- .../my_stack_view/wallet_summary_table.dart | 4 +- .../amount/amount_input_formatter.dart | 49 +++++++++++- pubspec.lock | 9 +-- .../templates/pubspec.template.yaml | 7 +- .../auto_backup_view_locale_test.dart | 75 ++++++++++++++++++ .../wallet_summary_table_locale_test.dart | 77 +++++++++++++++++++ test/utilities/amount/amount_unit_test.dart | 59 ++++++++++++-- 8 files changed, 263 insertions(+), 21 deletions(-) create mode 100644 test/pages/settings_views/auto_backup_view_locale_test.dart create mode 100644 test/pages_desktop_specific/wallet_summary_table_locale_test.dart diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart index 849f10be0..10842a760 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart @@ -73,9 +73,7 @@ class _AutoBackupViewState extends ConsumerState { postfix = "days"; } else { // if greater than a week return the actual date - return DateFormat.yMMMMd( - ref.read(localeServiceChangeNotifierProvider).locale, - ).format(time); + return DateFormat.yMMMMd('en_US').format(time); } if (value == 1) { diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart b/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart index 45b5d710e..73d9b05f0 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart @@ -292,7 +292,9 @@ class TablePriceInfo extends ConsumerWidget { price.value, fractionDigits: 2, ).fiatString( - locale: ref.watch(localeServiceChangeNotifierProvider.notifier).locale, + locale: ref.watch( + localeServiceChangeNotifierProvider.select((value) => value.locale), + ), ); var percentChangedColor = diff --git a/lib/utilities/amount/amount_input_formatter.dart b/lib/utilities/amount/amount_input_formatter.dart index 24271ca1a..4ba2eeff8 100644 --- a/lib/utilities/amount/amount_input_formatter.dart +++ b/lib/utilities/amount/amount_input_formatter.dart @@ -109,12 +109,22 @@ class AmountInputFormatter extends TextInputFormatter { return newValue; } + final recovery = _activeRecovery; + if (recovery != null && _continuesActiveComposition(recovery, oldValue)) { + final normalized = _normalizeDecimalKey(recovery.value, newValue); + if (_validPattern.hasMatch(normalized.text)) { + _clearRecovery(); + return normalized; + } + } + + newValue = _normalizeDecimalKey(oldValue, newValue); + if (_validPattern.hasMatch(newValue.text)) { _clearRecovery(); return newValue; } - final recovery = _activeRecovery; if (recovery != null && _continuesActiveComposition(recovery, oldValue)) { _clearRecovery(); return recovery.value; @@ -144,6 +154,43 @@ class AmountInputFormatter extends TextInputFormatter { return _validPrefix(newValue); } + TextEditingValue _normalizeDecimalKey( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { + // Android numeric keyboards do not all offer the locale's separator. + // Normalize one newly typed decimal key, but keep rejecting pasted or + // grouped input so that "1.234" is never silently reinterpreted. + if (_maximumFractionDigits == 0 || + (_decimalSeparator != "." && _decimalSeparator != ",") || + !_validPattern.hasMatch(oldValue.text) || + newValue.text.length != oldValue.text.length + 1) { + return newValue; + } + + int insertedAt = 0; + while (insertedAt < oldValue.text.length && + oldValue.text.codeUnitAt(insertedAt) == + newValue.text.codeUnitAt(insertedAt)) { + insertedAt++; + } + final inserted = newValue.text[insertedAt]; + if ((inserted != "." && inserted != ",") || + inserted == _decimalSeparator || + newValue.text.replaceRange(insertedAt, insertedAt + 1, "") != + oldValue.text) { + return newValue; + } + + return newValue.copyWith( + text: newValue.text.replaceRange( + insertedAt, + insertedAt + 1, + _decimalSeparator, + ), + ); + } + TextEditingValue _validPrefix(TextEditingValue value) { const asciiZeroCodeUnit = 0x30; const asciiNineCodeUnit = 0x39; diff --git a/pubspec.lock b/pubspec.lock index 3d96ecf1b..3eaafd905 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -430,11 +430,10 @@ packages: cs_locale: dependency: "direct main" description: - path: "." - ref: cf9eae01b49b7b812df48723ccdc1f0852a9ff95 - resolved-ref: cf9eae01b49b7b812df48723ccdc1f0852a9ff95 - url: "https://github.com/sneurlax/cs_locale.git" - source: git + name: cs_locale + sha256: "2578bce60b2bd009c8c18865a4b958a55429a4bba12bb1c083c3544e62104166" + url: "https://pub.dev" + source: hosted version: "0.1.0" cs_monero: dependency: "direct main" diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index f4848872d..11b5bddce 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -179,12 +179,7 @@ dependencies: wakelock_plus: ^1.2.8 intl: ^0.19.0 html: ^0.15.6 - # Until cs_locale 0.1.0 is on pub.dev (cypherstack/cs_locale#4); 0.0.1 - # fails to configure under this app's Android Gradle plugin. - cs_locale: - git: - url: https://github.com/sneurlax/cs_locale.git - ref: cf9eae01b49b7b812df48723ccdc1f0852a9ff95 # 0.1.0 + cs_locale: ^0.1.0 device_info_plus: ^12.4.0 keyboard_dismisser: ^3.0.0 another_flushbar: ^1.10.28 diff --git a/test/pages/settings_views/auto_backup_view_locale_test.dart b/test/pages/settings_views/auto_backup_view_locale_test.dart new file mode 100644 index 000000000..77af265d6 --- /dev/null +++ b/test/pages/settings_views/auto_backup_view_locale_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart'; +import 'package:stackwallet/providers/global/locale_provider.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/services/locale_service.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/enums/backup_frequency_type.dart'; +import 'package:stackwallet/utilities/prefs.dart'; + +import '../../sample_data/theme_json.dart'; + +class _Locale extends LocaleService { + @override + String get locale => 'en_US@decimal=,;group=.'; +} + +class _Prefs extends ChangeNotifier implements Prefs { + @override + bool get isAutoBackupEnabled => true; + + @override + String? get autoBackupLocation => '/tmp/backup.swb'; + + @override + BackupFrequencyType get backupFrequencyType => + BackupFrequencyType.everyAppStart; + + @override + DateTime? get lastAutoBackup => DateTime(2024); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + testWidgets('custom number formats do not break the backup date', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final container = ProviderContainer( + overrides: [ + prefsChangeNotifierProvider.overrideWithValue(_Prefs()), + localeServiceChangeNotifierProvider.overrideWithValue(_Locale()), + themeProvider.overrideWithProvider( + StateProvider((ref) => theme), + ), + ], + ); + addTearDown(container.dispose); + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const AutoBackupView(), + ), + ), + ); + + expect(tester.takeException(), isNull); + expect(find.textContaining('Backed up'), findsOneWidget); + }); +} diff --git a/test/pages_desktop_specific/wallet_summary_table_locale_test.dart b/test/pages_desktop_specific/wallet_summary_table_locale_test.dart new file mode 100644 index 000000000..e41491fde --- /dev/null +++ b/test/pages_desktop_specific/wallet_summary_table_locale_test.dart @@ -0,0 +1,77 @@ +import 'package:decimal/decimal.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_summary_table.dart'; +import 'package:stackwallet/providers/global/locale_provider.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/services/locale_service.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/prefs.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; + +import '../sample_data/theme_json.dart'; + +class _Locale extends LocaleService { + String value = 'en_US'; + + @override + String get locale => value; + + void change(String next) { + value = next; + notifyListeners(); + } +} + +class _Prefs extends ChangeNotifier implements Prefs { + @override + String get currency => 'USD'; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + testWidgets('fiat prices rebuild when the number format changes', ( + tester, + ) async { + final locale = _Locale(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + prefsChangeNotifierProvider.overrideWithValue(_Prefs()), + localeServiceChangeNotifierProvider.overrideWithValue(locale), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: TablePriceInfo( + coin: Bitcoin(CryptoCurrencyNetwork.main), + price: (value: Decimal.parse('1.23'), change24h: 0), + ), + ), + ), + ), + ); + + expect(find.text('1.23 USD/BTC'), findsOneWidget); + + locale.change( + Util.deviceNumberFormat( + locale: 'en_US', + decimalSeparator: ',', + groupingSeparator: '.', + ), + ); + await tester.pump(); + + expect(find.text('1,23 USD/BTC'), findsOneWidget); + }); +} diff --git a/test/utilities/amount/amount_unit_test.dart b/test/utilities/amount/amount_unit_test.dart index f8ec1e9cf..9ea2b15a1 100644 --- a/test/utilities/amount/amount_unit_test.dart +++ b/test/utilities/amount/amount_unit_test.dart @@ -302,7 +302,7 @@ void main() { ); }); - test("formatter rejects non-decimal separators", () { + test("formatter rejects grouped input", () { TextEditingValue edit( AmountInputFormatter formatter, String oldText, @@ -325,8 +325,6 @@ void main() { decimals: 8, locale: "de_DE", ); - expect(edit(de, "1", "1.").text, "1"); - expect(edit(de, "1", "1,").text, "1,"); expect(edit(de, "", "1.200").text, ""); expect(edit(de, "", "1.200,5").text, ""); @@ -335,12 +333,63 @@ void main() { decimals: 8, locale: "en_US", ); - expect(edit(us, "1", "1,").text, "1"); - expect(edit(us, "1", "1.").text, "1."); expect(edit(us, "", "1,200").text, ""); expect(edit(us, "", "1,200.5").text, ""); }); + test("formatter normalizes the other decimal key", () { + TextEditingValue edit(String locale, String oldText, String newText) { + return AmountInputFormatter( + controller: testController(), + decimals: 8, + locale: locale, + ).formatEditUpdate( + TextEditingValue( + text: oldText, + selection: TextSelection.collapsed(offset: oldText.length), + ), + TextEditingValue( + text: newText, + selection: TextSelection.collapsed(offset: newText.length), + ), + ); + } + + expect(edit("de_DE", "1", "1.").text, "1,"); + expect(edit("en_US", "1", "1,").text, "1."); + }); + + test("formatter normalizes a composed decimal key when it commits", () { + const valid = TextEditingValue( + text: "1", + selection: TextSelection.collapsed(offset: 1), + ); + const composing = TextEditingValue( + text: "1.", + selection: TextSelection.collapsed(offset: 2), + composing: TextRange(start: 1, end: 2), + ); + const committed = TextEditingValue( + text: "1.", + selection: TextSelection.collapsed(offset: 2), + ); + final controller = testController(); + + final beforeRebuild = AmountInputFormatter( + controller: controller, + decimals: 8, + locale: "de_DE", + ); + expect(beforeRebuild.formatEditUpdate(valid, composing), composing); + + final afterRebuild = AmountInputFormatter( + controller: controller, + decimals: 8, + locale: "de_DE", + ); + expect(afterRebuild.formatEditUpdate(composing, committed).text, "1,"); + }); + test("canonical and token parsing preserve exact precision", () { final canonical = Amount.tryParseCanonicalAmount( "1.234567", From b17bd97129f762ab4d574cb54133287f2071cafe Mon Sep 17 00:00:00 2001 From: sneurlax Date: Thu, 3 Dec 2026 14:42:19 -0600 Subject: [PATCH 4/4] style: format locale view changes --- .../stack_backup_views/auto_backup_view.dart | 74 ++++++----- .../my_stack_view/wallet_summary_table.dart | 115 +++++++++--------- 2 files changed, 93 insertions(+), 96 deletions(-) diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart index 10842a760..959633a08 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/auto_backup_view.dart @@ -93,15 +93,15 @@ class _AutoBackupViewState extends ConsumerState { title: "Enable Auto Backup", message: "To enable Auto Backup, you need to create a backup file.", leftButton: TextButton( - style: Theme.of( - context, - ).extension()!.getSecondaryEnabledButtonStyle(context), + style: Theme.of(context) + .extension()! + .getSecondaryEnabledButtonStyle(context), child: Text( "Back", style: STextStyles.button(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), ), onPressed: () { @@ -109,9 +109,9 @@ class _AutoBackupViewState extends ConsumerState { }, ), rightButton: TextButton( - style: Theme.of( - context, - ).extension()!.getPrimaryEnabledButtonStyle(context), + style: Theme.of(context) + .extension()! + .getPrimaryEnabledButtonStyle(context), child: Text("Continue", style: STextStyles.button(context)), onPressed: () { Navigator.of(context).pop(true); @@ -122,15 +122,15 @@ class _AutoBackupViewState extends ConsumerState { ); if (mounted) { if (result is bool && result) { - Navigator.of(context).pushNamed(CreateAutoBackupView.routeName).then(( - _, - ) { - // set toggle to correct state - if (_toggle != - ref.read(prefsChangeNotifierProvider).isAutoBackupEnabled) { - toggleController.activate?.call(); - } - }); + Navigator.of(context) + .pushNamed(CreateAutoBackupView.routeName) + .then((_) { + // set toggle to correct state + if (_toggle != + ref.read(prefsChangeNotifierProvider).isAutoBackupEnabled) { + toggleController.activate?.call(); + } + }); } else { toggleController.activate?.call(); } @@ -145,18 +145,17 @@ class _AutoBackupViewState extends ConsumerState { builder: (context) { return StackDialog( title: "Disable Auto Backup", - message: - "You are turning off Auto Backup. You can turn it back on at any time. Your previous Auto Backup file will not be deleted. Remember to backup your wallets manually so you don't lose important information.", + message: "You are turning off Auto Backup. You can turn it back on at any time. Your previous Auto Backup file will not be deleted. Remember to backup your wallets manually so you don't lose important information.", leftButton: TextButton( - style: Theme.of( - context, - ).extension()!.getSecondaryEnabledButtonStyle(context), + style: Theme.of(context) + .extension()! + .getSecondaryEnabledButtonStyle(context), child: Text( "Back", style: STextStyles.button(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), ), onPressed: () { @@ -164,9 +163,9 @@ class _AutoBackupViewState extends ConsumerState { }, ), rightButton: TextButton( - style: Theme.of( - context, - ).extension()!.getPrimaryEnabledButtonStyle(context), + style: Theme.of(context) + .extension()! + .getPrimaryEnabledButtonStyle(context), child: Text("Disable", style: STextStyles.button(context)), onPressed: () { Navigator.of(context).pop(true); @@ -178,9 +177,8 @@ class _AutoBackupViewState extends ConsumerState { if (mounted) { if (result is bool && result) { ref.read(prefsChangeNotifierProvider).isAutoBackupEnabled = false; - Navigator.of( - context, - ).popUntil(ModalRoute.withName(AutoBackupView.routeName)); + Navigator.of(context) + .popUntil(ModalRoute.withName(AutoBackupView.routeName)); } else { toggleController.activate?.call(); } @@ -430,9 +428,10 @@ class _AutoBackupViewState extends ConsumerState { controller: frequencyController, enabled: false, style: STextStyles.field(context).copyWith( - color: Theme.of( - context, - ).extension()!.textDark.withOpacity(0.5), + color: Theme.of(context) + .extension()! + .textDark + .withOpacity(0.5), ), toolbarOptions: const ToolbarOptions( copy: true, @@ -446,9 +445,8 @@ class _AutoBackupViewState extends ConsumerState { child: CustomTextButton( text: "Edit Auto Backup", onTap: () async { - Navigator.of( - context, - ).pushNamed(EditAutoBackupView.routeName); + Navigator.of(context) + .pushNamed(EditAutoBackupView.routeName); }, ), ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart b/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart index 73d9b05f0..35018d917 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart @@ -54,11 +54,8 @@ class _WalletTableState extends ConsumerState { return ConditionalParent( condition: index + 1 == walletsByCoin.length, - builder: - (child) => Padding( - padding: const EdgeInsets.only(bottom: 16), - child: child, - ), + builder: (child) => + Padding(padding: const EdgeInsets.only(bottom: 16), child: child), child: DesktopWalletSummaryRow( key: Key("DesktopWalletSummaryRow_key_${coin.identifier}"), coin: coin, @@ -174,41 +171,40 @@ class _DesktopWalletSummaryRowState if (mounted) { await showDialog( context: context, - builder: - (_) => DesktopDialog( - maxHeight: 600, - maxWidth: 700, - child: Column( + builder: (_) => DesktopDialog( + maxHeight: 600, + maxWidth: 700, + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Padding( - padding: const EdgeInsets.only(left: 32), - child: Text( - "${widget.coin.prettyName} (${widget.coin.ticker}) wallets", - style: STextStyles.desktopH3(context), - ), - ), - const DesktopDialogCloseButton(), - ], - ), - Expanded( - child: Padding( - padding: const EdgeInsets.only( - left: 32, - right: 32, - bottom: 32, - ), - child: WalletsOverview( - coin: widget.coin, - navigatorState: Navigator.of(context), - ), + Padding( + padding: const EdgeInsets.only(left: 32), + child: Text( + "${widget.coin.prettyName} (${widget.coin.ticker}) wallets", + style: STextStyles.desktopH3(context), ), ), + const DesktopDialogCloseButton(), ], ), - ), + Expanded( + child: Padding( + padding: const EdgeInsets.only( + left: 32, + right: 32, + bottom: 32, + ), + child: WalletsOverview( + coin: widget.coin, + navigatorState: Navigator.of(context), + ), + ), + ), + ], + ), + ), ); } } finally { @@ -228,8 +224,9 @@ class _DesktopWalletSummaryRowState child: RoundedWhiteContainer( padding: const EdgeInsets.all(20), hoverColor: Colors.transparent, - onPressed: - goStraightIntoWallet ? _onPressedSingleWalletDesktop : _onPressed, + onPressed: goStraightIntoWallet + ? _onPressedSingleWalletDesktop + : _onPressed, child: Row( children: [ Expanded( @@ -245,8 +242,9 @@ class _DesktopWalletSummaryRowState Text( widget.coin.prettyName, style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: - Theme.of(context).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ], @@ -259,8 +257,9 @@ class _DesktopWalletSummaryRowState ? "${widget.walletCount} wallet" : "${widget.walletCount} wallets", style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: - Theme.of(context).extension()!.textSubtitle1, + color: Theme.of(context) + .extension()! + .textSubtitle1, ), ), ), @@ -288,23 +287,24 @@ class TablePriceInfo extends ConsumerWidget { prefsChangeNotifierProvider.select((value) => value.currency), ); - final priceString = Amount.fromDecimal( - price.value, - fractionDigits: 2, - ).fiatString( - locale: ref.watch( - localeServiceChangeNotifierProvider.select((value) => value.locale), - ), - ); + final priceString = Amount.fromDecimal(price.value, fractionDigits: 2) + .fiatString( + locale: ref.watch( + localeServiceChangeNotifierProvider.select((value) => value.locale), + ), + ); - var percentChangedColor = - Theme.of(context).extension()!.textDark; + var percentChangedColor = Theme.of(context) + .extension()! + .textDark; if (price.change24h > 0) { - percentChangedColor = - Theme.of(context).extension()!.accentColorGreen; + percentChangedColor = Theme.of(context) + .extension()! + .accentColorGreen; } else if (price.change24h < 0) { - percentChangedColor = - Theme.of(context).extension()!.accentColorRed; + percentChangedColor = Theme.of(context) + .extension()! + .accentColorRed; } return Row( @@ -318,9 +318,8 @@ class TablePriceInfo extends ConsumerWidget { ), Text( "${price.change24h.toStringAsFixed(2)}%", - style: STextStyles.desktopTextExtraSmall( - context, - ).copyWith(color: percentChangedColor), + style: STextStyles.desktopTextExtraSmall(context) + .copyWith(color: percentChangedColor), ), ], );