An open-source cross-platform alternative to AirDrop
feat: respect system date and time formats (#3472)
Shlomo9529e915f438
diff --git a/app/lib/main.dart b/app/lib/main.dartindex cbcff393..b3caed80 100644--- a/app/lib/main.dart+++ b/app/lib/main.dart@@ -19,6 +19,7 @@ import 'package:localsend_isolates/isolate.dart';import 'package:refena_flutter/addons.dart';import 'package:refena_flutter/refena_flutter.dart';import 'package:routerino/routerino.dart';+import 'package:system_date_time_format/system_date_time_format.dart';Future<void> main(List<String> args) async {final RefenaContainer container;@@ -35,8 +36,10 @@ Future<void> main(List<String> args) async {runApp(RefenaScope.withContainer(container: container,- child: TranslationProvider(- child: const LocalSendApp(),+ child: SDTFScope(+ child: TranslationProvider(+ child: const LocalSendApp(),+ ),),),);diff --git a/app/lib/model/persistence/receive_history_entry.dart b/app/lib/model/persistence/receive_history_entry.dartindex 948e8412..f9637d06 100644--- a/app/lib/model/persistence/receive_history_entry.dart+++ b/app/lib/model/persistence/receive_history_entry.dart@@ -1,6 +1,6 @@import 'package:dart_mappable/dart_mappable.dart';-import 'package:intl/intl.dart';-import 'package:localsend_app/gen/strings.g.dart';+import 'package:flutter/widgets.dart';+import 'package:localsend_app/util/system_date_time_formatter.dart';import 'package:localsend_isolates/model/file_type.dart';part 'receive_history_entry.mapper.dart';@@ -36,12 +36,10 @@ class ReceiveHistoryEntry with ReceiveHistoryEntryMappable {required this.timestamp,});- /// Format string using the intl package.+ /// Format string using the system date and time format./// Because the raw timestamp is saved in UTC, we need to transform it to local time zone first.- String get timestampString {- final localTimestamp = timestamp.toLocal();- final languageTag = LocaleSettings.currentLocale.languageTag;- return '${DateFormat.yMd(languageTag).format(localTimestamp)} ${DateFormat.jm(languageTag).format(localTimestamp)}';+ String timestampString(BuildContext context) {+ return SystemDateTimeFormatter.dateTime(context, timestamp.toLocal());}static const fromJson = ReceiveHistoryEntryMapper.fromJson;diff --git a/app/lib/pages/device_details_page.dart b/app/lib/pages/device_details_page.dartindex c103d24d..343f13cb 100644--- a/app/lib/pages/device_details_page.dart+++ b/app/lib/pages/device_details_page.dart@@ -1,10 +1,10 @@import 'package:flutter/material.dart';-import 'package:intl/intl.dart';import 'package:localsend_app/gen/strings.g.dart';import 'package:localsend_app/model/persistence/favorite_device.dart';import 'package:localsend_app/pages/verify_page.dart';import 'package:localsend_app/provider/favorites_provider.dart';import 'package:localsend_app/util/favorites.dart';+import 'package:localsend_app/util/system_date_time_formatter.dart';import 'package:localsend_app/widget/big_button.dart';import 'package:localsend_app/widget/dialogs/favorite_delete_dialog.dart';import 'package:localsend_app/widget/dialogs/favorite_edit_dialog.dart';@@ -14,8 +14,6 @@ import 'package:localsend_isolates/model/device.dart';import 'package:refena_flutter/refena_flutter.dart';import 'package:routerino/routerino.dart';-final _timeFormat = DateFormat.jm(LocaleSettings.currentLocale.languageTag);-/// Shows the general information of a discovered device and/// the log of its retained discovery confirmations.class DeviceDetailsPage extends StatefulWidget {@@ -134,7 +132,7 @@ class _DeviceDetailsPageState extends State<DeviceDetailsPage> with Refena {child: Row(crossAxisAlignment: CrossAxisAlignment.start,children: [- Text('[${_timeFormat.format(log.timestamp)}]'),+ Text('[${SystemDateTimeFormatter.time(context, log.timestamp)}]'),const SizedBox(width: 4),Expanded(child: Text(log.description),diff --git a/app/lib/pages/receive_history_page.dart b/app/lib/pages/receive_history_page.dartindex 98274559..5b3dbe98 100644--- a/app/lib/pages/receive_history_page.dart+++ b/app/lib/pages/receive_history_page.dart@@ -187,7 +187,7 @@ class ReceiveHistoryPage extends StatelessWidget {softWrap: false,),Text(- '${entry.timestampString} - ${entry.fileSize.asReadableFileSize} - ${entry.senderAlias}',+ '${entry.timestampString(context)} - ${entry.fileSize.asReadableFileSize} - ${entry.senderAlias}',maxLines: 1,overflow: TextOverflow.fade,softWrap: false,diff --git a/app/lib/util/system_date_time_formatter.dart b/app/lib/util/system_date_time_formatter.dartnew file mode 100644index 00000000..c6a152b7--- /dev/null+++ b/app/lib/util/system_date_time_formatter.dart@@ -0,0 +1,65 @@+import 'package:flutter/widgets.dart';+import 'package:intl/intl.dart';+import 'package:localsend_app/gen/strings.g.dart';+import 'package:system_date_time_format/system_date_time_format.dart';++// TODO: Revisit this plugin when https://github.com/dart-lang/i18n/issues/67 is fixed.+// intl currently uses US date/time patterns for unsupported regional locales+// such as en_IL. Before returning to DateFormat.yMd/jm, verify those locales+// and user-selected system formats, which locale data alone may not reflect.++class SystemDateTimeFormatter {+ static String dateTime(BuildContext context, DateTime value) => '${date(context, value)} ${time(context, value)}';++ static String date(BuildContext context, DateTime value) {+ final pattern = SystemDateTimeFormat.of(context).datePattern;+ if (pattern == null || !_isSupported(pattern)) {+ // fallback to default formatting+ return DateFormat.yMd(_locale).format(value);+ }++ // use pattern supplied by OS+ return DateFormat(pattern, _locale).format(value);+ }++ static String time(BuildContext context, DateTime value) {+ final pattern = SystemDateTimeFormat.of(context).timePattern;+ if (pattern == null || !_isSupported(pattern)) {+ // fallback to default formatting+ return DateFormat.jm(_locale).format(value);+ }++ // use pattern supplied by OS+ return DateFormat(_withoutSeconds(pattern), _locale).format(value);+ }++ /// Fields intl mishandles: unknown letters (e.g. `B`) print literally, time zones (`v`, `z`, `Z`) print nothing,+ /// .NET-style `ddd` prints a padded day, `EEEEEE` throws.+ static final _unsupportedField = RegExp(r'(?![GyMkSEahKHcLQdDms])[A-Za-z]|d{3,}|E{6,}');++ static bool _isSupported(String pattern) {+ final parts = pattern.split("'");+ // Only even-indexed parts are outside quoted literals.+ for (var i = 0; i < parts.length; i += 2) {+ if (_unsupportedField.hasMatch(parts[i])) return false;+ }+ return true;+ }++ // On Linux, T_FMT may include seconds even where the UI uses minute precision.+ static String _withoutSeconds(String pattern) {+ final parts = pattern.split("'");+ // Only even-indexed parts are outside quoted literals.+ for (var i = 0; i < parts.length; i += 2) {+ parts[i] = parts[i].replaceFirst(RegExp(r'[:., ]?s+'), '');+ }+ return parts.join("'");+ }++ static String get _locale {+ return _verified(WidgetsBinding.instance.platformDispatcher.locale.toString()) ?? _verified(LocaleSettings.currentLocale.languageTag) ?? 'en';+ }++ /// Resolves e.g. `de_DE` to `de` and `pt-BR` to `pt`, or null if intl has no date symbols for the language.+ static String? _verified(String locale) => Intl.verifiedLocale(locale, DateFormat.localeExists, onFailure: (_) => null);+}diff --git a/app/lib/widget/dialogs/file_info_dialog.dart b/app/lib/widget/dialogs/file_info_dialog.dartindex bd78c5b5..569dc52b 100644--- a/app/lib/widget/dialogs/file_info_dialog.dart+++ b/app/lib/widget/dialogs/file_info_dialog.dart@@ -62,7 +62,7 @@ class FileInfoDialog extends StatelessWidget {children: [Text(t.dialogs.fileInfo.time),const SizedBox(width: 10),- SelectableText(entry.timestampString),+ SelectableText(entry.timestampString(context)),],),],diff --git a/app/linux/flutter/generated_plugin_registrant.cc b/app/linux/flutter/generated_plugin_registrant.ccindex a4a2aa39..2ed33099 100644--- a/app/linux/flutter/generated_plugin_registrant.cc+++ b/app/linux/flutter/generated_plugin_registrant.cc@@ -13,6 +13,7 @@#include <open_file_linux/open_file_linux_plugin.h>#include <pasteboard/pasteboard_plugin.h>#include <screen_retriever_linux/screen_retriever_linux_plugin.h>+#include <system_date_time_format/system_date_time_format_plugin.h>#include <tray_manager/tray_manager_plugin.h>#include <uri_content/uri_content_plugin.h>#include <url_launcher_linux/url_launcher_plugin.h>@@ -41,6 +42,9 @@ void fl_register_plugins(FlPluginRegistry* registry) {g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar =fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin");screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar);+ g_autoptr(FlPluginRegistrar) system_date_time_format_registrar =+ fl_plugin_registry_get_registrar_for_plugin(registry, "SystemDateTimeFormatPlugin");+ system_date_time_format_plugin_register_with_registrar(system_date_time_format_registrar);g_autoptr(FlPluginRegistrar) tray_manager_registrar =fl_plugin_registry_get_registrar_for_plugin(registry, "TrayManagerPlugin");tray_manager_plugin_register_with_registrar(tray_manager_registrar);diff --git a/app/linux/flutter/generated_plugins.cmake b/app/linux/flutter/generated_plugins.cmakeindex a6e141d9..dba4ed78 100644--- a/app/linux/flutter/generated_plugins.cmake+++ b/app/linux/flutter/generated_plugins.cmake@@ -10,6 +10,7 @@ list(APPEND FLUTTER_PLUGIN_LISTopen_file_linuxpasteboardscreen_retriever_linux+ system_date_time_formattray_manageruri_contenturl_launcher_linuxdiff --git a/app/macos/Flutter/GeneratedPluginRegistrant.swift b/app/macos/Flutter/GeneratedPluginRegistrant.swiftindex 05a22d56..a7d4219b 100644--- a/app/macos/Flutter/GeneratedPluginRegistrant.swift+++ b/app/macos/Flutter/GeneratedPluginRegistrant.swift@@ -20,6 +20,7 @@ import pasteboardimport photo_managerimport screen_retriever_macosimport shared_preferences_foundation+import system_date_time_formatimport tray_managerimport uri_contentimport url_launcher_macos@@ -43,6 +44,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {PhotoManagerPlugin.register(with: registry.registrar(forPlugin: "PhotoManagerPlugin"))ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))+ SystemDateTimeFormatPlugin.register(with: registry.registrar(forPlugin: "SystemDateTimeFormatPlugin"))TrayManagerPlugin.register(with: registry.registrar(forPlugin: "TrayManagerPlugin"))UriContentPlugin.register(with: registry.registrar(forPlugin: "UriContentPlugin"))UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))diff --git a/app/pubspec.yaml b/app/pubspec.yamlindex 56aa4deb..d41d4f0d 100644--- a/app/pubspec.yaml+++ b/app/pubspec.yaml@@ -60,6 +60,7 @@ dependencies:shared_preferences_platform_interface: anyslang: 4.19.0slang_flutter: 4.19.0+ system_date_time_format: ^1.4.0system_settings_2: 3.0.2tray_manager: 0.5.3uri_content: 3.1.1@@ -77,6 +78,8 @@ dev_dependencies:dart_mappable_builder: 4.8.0flutter_gen_runner: 5.15.0flutter_lints: 6.0.0+ flutter_test:+ sdk: flutterfreezed: 3.2.5mockito: anyrefena_inspector: 2.1.1diff --git a/app/test/unit/util/system_date_time_formatter_test.dart b/app/test/unit/util/system_date_time_formatter_test.dartnew file mode 100644index 00000000..411afeae--- /dev/null+++ b/app/test/unit/util/system_date_time_formatter_test.dart@@ -0,0 +1,143 @@+import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_localizations/flutter_localizations.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:localsend_app/gen/strings.g.dart';+import 'package:localsend_app/util/system_date_time_formatter.dart';+import 'package:system_date_time_format/system_date_time_format.dart';++void main() {+ // Loads the same date symbols as the app; intl's initializeDateFormatting() has more locales and hides fallback bugs.+ setUpAll(() => GlobalMaterialLocalizations.delegate.load(const Locale('en')));++ setUp(() => LocaleSettings.setLocale(AppLocale.en));++ testWidgets('Displayed dates and times follow the system patterns for an unsupported intl region', (tester) async {+ const channel = MethodChannel('system_date_time_format');+ var datePattern = 'dd/MM/y';+ var timePattern = 'HH:mm';+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async {+ return switch (call.method) {+ 'getDateFormat' => datePattern,+ 'getTimeFormat' => timePattern,+ _ => null,+ };+ });+ addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));+ tester.binding.platformDispatcher.localeTestValue = const Locale('en', 'IL');+ addTearDown(tester.binding.platformDispatcher.clearLocaleTestValue);++ final timestamp = DateTime(2026, 9, 27, 15, 54);++ await tester.pumpWidget(+ Directionality(+ textDirection: TextDirection.ltr,+ child: SDTFScope(+ child: Builder(+ builder: (context) => Text(SystemDateTimeFormatter.dateTime(context, timestamp)),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('27/09/2026 15:54'), findsOneWidget);++ datePattern = 'M/d/y';+ timePattern = 'h:mm a';+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pumpAndSettle();+ expect(find.text('9/27/2026 3:54 PM'), findsOneWidget);++ // Linux's T_FMT may yield HH:mm:ss; keep minute precision in the UI.+ timePattern = 'HH:mm:ss';+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pumpAndSettle();+ expect(find.text('9/27/2026 15:54'), findsOneWidget);++ timePattern = 'h:mm a:ss';+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pumpAndSettle();+ expect(find.text('9/27/2026 3:54 PM'), findsOneWidget);++ timePattern = "HH:mm 'seconds'";+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pumpAndSettle();+ expect(find.text('9/27/2026 15:54 seconds'), findsOneWidget);++ timePattern = "HH:mm 'm:ss'";+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await tester.pumpAndSettle();+ expect(find.text('9/27/2026 15:54 m:ss'), findsOneWidget);+ });++ testWidgets('Day period uses the device language', (tester) async {+ final text = await _format(tester, device: const Locale('zh', 'CN'), app: AppLocale.zhCn, datePattern: 'y/M/d', timePattern: 'ah:mm');+ expect(text, '2026/9/27 下午3:54');+ });++ testWidgets('Device language wins over the app language', (tester) async {+ final text = await _format(tester, device: const Locale('ko', 'KR'), app: AppLocale.en, datePattern: 'y. M. d.', timePattern: 'a h:mm');+ expect(text, '2026. 9. 27. 오후 3:54');+ });++ testWidgets('Without system patterns, a regional app locale is used', (tester) async {+ final text = await _format(tester, device: const Locale('xx'), app: AppLocale.ptBr);+ expect(text, '27/09/2026 15:54');+ });++ testWidgets('Flexible day period falls back to the locale default', (tester) async {+ final text = await _format(tester, device: const Locale('zh', 'TW'), app: AppLocale.zhTw, datePattern: 'y/M/d', timePattern: 'Bh:mm');+ expect(text, '2026/9/27 下午3:54');+ });++ testWidgets('.NET-style weekday falls back to the locale default', (tester) async {+ final text = await _format(tester, device: const Locale('en', 'GB'), app: AppLocale.en, datePattern: 'ddd dd/MM/yyyy', timePattern: 'HH:mm');+ expect(text, '27/09/2026 15:54');+ });++ testWidgets('Short weekday falls back to the locale default', (tester) async {+ final text = await _format(tester, device: const Locale('en', 'GB'), app: AppLocale.en, datePattern: 'EEEEEE dd/MM/yyyy', timePattern: 'HH:mm');+ expect(text, '27/09/2026 15:54');+ });++ testWidgets('Time zone falls back to the locale default', (tester) async {+ final text = await _format(tester, device: const Locale('en', 'GB'), app: AppLocale.en, datePattern: 'dd/MM/yyyy', timePattern: 'HH:mm z');+ expect(text, '27/09/2026 15:54');+ });+}++Future<String> _format(+ WidgetTester tester, {+ required Locale device,+ required AppLocale app,+ String? datePattern,+ String? timePattern,+}) async {+ const channel = MethodChannel('system_date_time_format');+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async {+ return switch (call.method) {+ 'getDateFormat' => datePattern,+ 'getTimeFormat' => timePattern,+ _ => null,+ };+ });+ addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));+ tester.binding.platformDispatcher.localeTestValue = device;+ addTearDown(tester.binding.platformDispatcher.clearLocaleTestValue);+ // Loading translations is real async work that never completes under the fake clock.+ await tester.runAsync(() => LocaleSettings.setLocale(app));++ late String text;+ await tester.pumpWidget(+ SDTFScope(+ child: Builder(+ builder: (context) {+ text = SystemDateTimeFormatter.dateTime(context, DateTime(2026, 9, 27, 15, 54));+ return const SizedBox();+ },+ ),+ ),+ );+ await tester.pumpAndSettle();+ return text;+}diff --git a/app/web/index.html b/app/web/index.htmlindex f38c62ea..bfa409d8 100644--- a/app/web/index.html+++ b/app/web/index.html@@ -37,6 +37,7 @@var serviceWorkerVersion = null;</script><!-- This script adds the flutter initialization JS code -->+ <script src="./assets/packages/system_date_time_format/web/system_date_time_format.min.js"></script><script src="flutter.js" defer></script></head><body>diff --git a/app/windows/flutter/generated_plugin_registrant.cc b/app/windows/flutter/generated_plugin_registrant.ccindex 2f9adc5b..df7b0ecc 100644--- a/app/windows/flutter/generated_plugin_registrant.cc+++ b/app/windows/flutter/generated_plugin_registrant.cc@@ -14,6 +14,7 @@#include <pasteboard/pasteboard_plugin.h>#include <permission_handler_windows/permission_handler_windows_plugin.h>#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>+#include <system_date_time_format/system_date_time_format_plugin_c_api.h>#include <tray_manager/tray_manager_plugin.h>#include <uri_content/uri_content_plugin_c_api.h>#include <url_launcher_windows/url_launcher_windows.h>@@ -37,6 +38,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar(registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi"));+ SystemDateTimeFormatPluginCApiRegisterWithRegistrar(+ registry->GetRegistrarForPlugin("SystemDateTimeFormatPluginCApi"));TrayManagerPluginRegisterWithRegistrar(registry->GetRegistrarForPlugin("TrayManagerPlugin"));UriContentPluginCApiRegisterWithRegistrar(diff --git a/app/windows/flutter/generated_plugins.cmake b/app/windows/flutter/generated_plugins.cmakeindex 130b2b99..79dd4547 100644--- a/app/windows/flutter/generated_plugins.cmake+++ b/app/windows/flutter/generated_plugins.cmake@@ -11,6 +11,7 @@ list(APPEND FLUTTER_PLUGIN_LISTpasteboardpermission_handler_windowsscreen_retriever_windows+ system_date_time_formattray_manageruri_contenturl_launcher_windowsdiff --git a/pubspec.lock b/pubspec.lockindex 633dba40..4cdb4f98 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -1660,6 +1660,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.4.1"+ system_date_time_format:+ dependency: transitive+ description:+ name: system_date_time_format+ sha256: ce491f93c7f8340f1763fd304acab53e8f884800c8da71020356258187671196+ url: "https://pub.dev"+ source: hosted+ version: "1.4.0"system_settings_2:dependency: transitivedescription: