From 7bb9def62804de81217a23dd989d97d77ef7e5c1 Mon Sep 17 00:00:00 2001 From: Juraj Bednar Date: Wed, 18 Nov 2026 14:31:35 +0100 Subject: [PATCH 01/50] Keep the background service running when the app leaves the screen flutter_foreground_task's stopWithTask option (9.2 to 11.0) does not wait for the task to be removed: it registers activity lifecycle callbacks and stops the service on the first onActivityPaused with no resumed activity. So the "MeshCore background" service stopped every time the app went to the background or the screen turned off. Android then cached and froze the process, the Bluetooth link dropped and the low-memory killer ended the app a few hours later. Usage stats on a Pixel show FOREGROUND_SERVICE_STOP in the same second as every ACTIVITY_STOPPED. Drop the option. android:stopWithTask="true" in the manifest still stops the service when the app is swiped away, which is what the option was meant to do. --- lib/services/background_service.dart | 32 +++++++++++++++------- test/services/background_service_test.dart | 15 ++++++++++ 2 files changed, 37 insertions(+), 10 deletions(-) create mode 100644 test/services/background_service_test.dart diff --git a/lib/services/background_service.dart b/lib/services/background_service.dart index c8a83656..ccc084c3 100644 --- a/lib/services/background_service.dart +++ b/lib/services/background_service.dart @@ -6,6 +6,27 @@ import '../l10n/locale_tag.dart'; import '../utils/platform_info.dart'; class BackgroundService { + /// Options for the service that keeps the radio link alive in the + /// background. + /// + /// The radio link lives in the app process; once the user swipes the app + /// away it is gone, so a lingering "connected" notification (or an + /// automatic restart) would only be misleading. Swiping away stops the + /// service through `android:stopWithTask="true"` in AndroidManifest.xml. + /// + /// `stopWithTask` must stay unset here: in flutter_foreground_task (9.2 to + /// 11.0 at least) the option does not watch the task but stops the service + /// as soon as no activity is resumed, which is every time the app goes to + /// the background or the screen turns off. Android then caches and freezes + /// the process, the Bluetooth link drops and the low-memory killer ends it. + @visibleForTesting + static final ForegroundTaskOptions taskOptions = ForegroundTaskOptions( + eventAction: ForegroundTaskEventAction.repeat(5000), + autoRunOnBoot: false, + allowWifiLock: false, + allowAutoRestart: false, + ); + bool _initialized = false; String? Function()? _languageOverrideProvider; @@ -30,16 +51,7 @@ class BackgroundService { showNotification: false, playSound: false, ), - foregroundTaskOptions: ForegroundTaskOptions( - eventAction: ForegroundTaskEventAction.repeat(5000), - autoRunOnBoot: false, - allowWifiLock: false, - // The radio link lives in the app process; once the user swipes the - // app away it is gone, so a lingering "connected" notification (or - // an automatic restart) would only be misleading. - allowAutoRestart: false, - stopWithTask: true, - ), + foregroundTaskOptions: taskOptions, ); _initialized = true; } diff --git a/test/services/background_service_test.dart b/test/services/background_service_test.dart new file mode 100644 index 00000000..06912993 --- /dev/null +++ b/test/services/background_service_test.dart @@ -0,0 +1,15 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/background_service.dart'; + +void main() { + test('the foreground service does not stop when the app goes to the ' + 'background', () { + // flutter_foreground_task's stopWithTask option stops the service on the + // first activity pause, not on task removal. Swipe-away is handled by + // android:stopWithTask in the manifest instead. + final options = BackgroundService.taskOptions; + expect(options.stopWithTask, isNull); + expect(options.toJson().containsKey('stopWithTask'), isFalse); + expect(options.allowAutoRestart, isFalse); + }); +} From a1604af4d46eea1881d172705b3c5a1e75e13f73 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 21:43:49 +0000 Subject: [PATCH 02/50] Fix manual path search ranking, hash matching, and layout Rank name prefixes ahead of other substring matches, match hop hashes in the path builder and contact search, and keep the hop list and hex field on screen while the keyboard is open. Co-authored-by: zjs81 --- documentation/contacts.md | 2 +- documentation/design.md | 6 +- documentation/routing-paths.md | 4 + lib/l10n/app_bg.arb | 2 +- lib/l10n/app_cs.arb | 2 +- lib/l10n/app_de.arb | 2 +- lib/l10n/app_en.arb | 11 +- lib/l10n/app_es.arb | 2 +- lib/l10n/app_fr.arb | 2 +- lib/l10n/app_hu.arb | 2 +- lib/l10n/app_it.arb | 2 +- lib/l10n/app_ja.arb | 2 +- lib/l10n/app_ko.arb | 2 +- lib/l10n/app_localizations.dart | 6 +- lib/l10n/app_localizations_bg.dart | 5 +- lib/l10n/app_localizations_cs.dart | 4 +- lib/l10n/app_localizations_de.dart | 5 +- lib/l10n/app_localizations_en.dart | 7 +- lib/l10n/app_localizations_es.dart | 5 +- lib/l10n/app_localizations_fr.dart | 5 +- lib/l10n/app_localizations_hu.dart | 5 +- lib/l10n/app_localizations_it.dart | 5 +- lib/l10n/app_localizations_ja.dart | 4 +- lib/l10n/app_localizations_ko.dart | 4 +- lib/l10n/app_localizations_nl.dart | 5 +- lib/l10n/app_localizations_pl.dart | 5 +- lib/l10n/app_localizations_pt.dart | 10 +- lib/l10n/app_localizations_ru.dart | 5 +- lib/l10n/app_localizations_sk.dart | 5 +- lib/l10n/app_localizations_sl.dart | 5 +- lib/l10n/app_localizations_sv.dart | 5 +- lib/l10n/app_localizations_uk.dart | 5 +- lib/l10n/app_localizations_zh.dart | 4 +- lib/l10n/app_nl.arb | 2 +- lib/l10n/app_pl.arb | 2 +- lib/l10n/app_pt.arb | 2 +- lib/l10n/app_pt_PT.arb | 2 +- lib/l10n/app_ru.arb | 2 +- lib/l10n/app_sk.arb | 2 +- lib/l10n/app_sl.arb | 2 +- lib/l10n/app_sv.arb | 2 +- lib/l10n/app_uk.arb | 2 +- lib/l10n/app_zh.arb | 2 +- lib/screens/contacts_screen.dart | 43 +- lib/screens/discovery_screen.dart | 37 +- lib/screens/map_screen.dart | 56 +-- lib/utils/contact_search.dart | 56 ++- lib/widgets/path_editor_sheet.dart | 535 +++++++++++++++-------- lib/widgets/share_contact_sheet.dart | 9 +- test/utils/contact_search_test.dart | 109 +++++ test/widgets/path_editor_sheet_test.dart | 199 +++++++++ 51 files changed, 882 insertions(+), 327 deletions(-) create mode 100644 test/utils/contact_search_test.dart create mode 100644 test/widgets/path_editor_sheet_test.dart diff --git a/documentation/contacts.md b/documentation/contacts.md index 69559665..fba26ed9 100644 --- a/documentation/contacts.md +++ b/documentation/contacts.md @@ -40,7 +40,7 @@ Pull-to-refresh re-fetches the full contact list from the device. Telemetry loca A toolbar at the top provides: -**Search**: Matches contact name (case-insensitive) or public key hex prefix. Debounced at 300ms. +**Search**: Matches contact name (case-insensitive) or public key hex prefix. Names that start with the query are listed before other name matches, then key-prefix matches. Within each group the selected sort still applies. Debounced at 300ms. **Sort options**: - Latest Messages (by most recent message) diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..dee9c2ce 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -154,7 +154,7 @@ What the code does: | Container | Call | Used for | Examples | |---|---|---|---| | Bottom sheet | `showMeshSheet` + `BottomSheetHeader` (28 calls in 17 files) | Choosing from a list, an item's actions, quick tools tied to the current screen | Language picker, notification mode, add contact/channel options, emoji and GIF pickers, node info, share contact, image actions | -| Draggable sheet | `showModalBottomSheet` + `DraggableScrollableSheet` | Tall, scrollable panels that need a drag size | `ContactRoutingSheet` (`routing_sheet.dart`), path editor, image send preview | +| Draggable sheet | `showModalBottomSheet` + `DraggableScrollableSheet` | Tall, scrollable panels that need a drag size | `ContactRoutingSheet` (`routing_sheet.dart`), image send preview | | Dialog | `showDialog` + `AlertDialog` (72 calls in 35 files) | Confirming an action, a short input (one to three fields), a short message | Disconnect (`showDisconnectDialog`), clear (`showConfirmClearDialog`), unsaved changes, edit node name, rename point | | Page | `Navigator.push(MaterialPageRoute(...))` | Anything with sections, many fields, its own save, or that the user stays in | App Settings, Repeater Settings, Themes, Theme editor, Message filter, Region management | @@ -165,6 +165,8 @@ Rules for new UI: 3. **Forms with sections, live remote values, or anything that needs Save/Discard → page.** Guard unsaved changes with `PopScope` and a discard dialog, as `repeater_settings_screen.dart` does. 4. Never stack a dialog on a sheet on a dialog. Close the sheet first, or move the flow to a page. +The manual path editor (`path_editor_sheet.dart`) is a fixed-height sheet, not a draggable one. The hop list and the hex path field stay pinned above a scrolling repeater list, including while the keyboard is open. The sheet uses the full height above the keyboard so a newly added hop is not scrolled under the title. + ## 7. App bars - Title: a plain localized string, ellipsized on one line. Use `AppBarTitle` on top-level and settings screens; it adds the connected node name as a subtitle and battery/SNR indicators when there is room, dropping them in that order on narrow widths. Use `AdaptiveAppBarTitle` for a plain one-line title. @@ -244,7 +246,7 @@ The current code does not yet follow this page everywhere: - **Large forms in dialogs.** `RadioSettingsDialog` (`widgets/radio_settings_dialog.dart`, nine inputs) and the contact settings dialog in `chat_screen.dart` are dialogs although they behave like forms. - **Dialog buttons.** `showDisconnectDialog` (`utils/dialog_utils.dart`) uses two `TextButton`s with no emphasis; `showConfirmClearDialog` uses a red `FilledButton`. - **Snackbars.** A few places still call `ScaffoldMessenger.showSnackBar` directly (`discovery_screen.dart`, `app_settings_screen.dart`, `message_filter_settings_screen.dart`, `region_management_screen.dart`, `helpers/image_send_flow.dart`) and so miss tap-to-dismiss and replace-instead-of-queue. -- **Small tap targets.** `FeatureToggleRow` refresh (32px) and 40px buttons in `chat_screen.dart`, `channel_chat_screen.dart`, `reaction_chips.dart`, `snr_indicator.dart`, `path_map_ui.dart`; 44px in `routing_sheet.dart`, `path_editor_sheet.dart`. +- **Small tap targets.** `FeatureToggleRow` refresh (32px) and 40px buttons in `chat_screen.dart`, `channel_chat_screen.dart`, `reaction_chips.dart`, `snr_indicator.dart`, `path_map_ui.dart`; 44px in `routing_sheet.dart`. - **Unknown placeholders.** Repeater and companion stats screens use `—`; `line_of_sight_map_screen.dart` uses `--`. - **Missing tooltip.** The Contacts FAB (`contacts_screen.dart`) has no tooltip; about 18 of 111 `IconButton`s have no tooltip nearby. - **Stale doc comments.** `SectionHeader` is described as "mono" but uses the sans `accentLabel`; the `StatusChip` comment sits above `meshContrastRatio`. diff --git a/documentation/routing-paths.md b/documentation/routing-paths.md index 74548258..90202fc4 100644 --- a/documentation/routing-paths.md +++ b/documentation/routing-paths.md @@ -62,4 +62,8 @@ Contacts/messages persist hop count, path bytes, and width. Legacy contact recor `resolvePathSelection` uses a route picked from history even when the radio itself holds no path for the contact, so repeater logins and commands use proven routes instead of flooding. +## Building a path by hand + +Chat → Routing → Manual opens the Build Path sheet. The hops you have added stay pinned at the top, including while the keyboard is open, and the one just added is highlighted. Under that list is the hex field, so a path can be typed without scrolling past every repeater. Search matches repeater and room names and hop hashes (the public-key prefix). Names that start with the query are listed before other substring matches, then hash-only matches. + For message-path actions, trace maps, and retry behavior, see [chat](chat-and-messaging.md), [channels](channels.md), and [map](map-and-location.md). diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 913a0815..5135e0e4 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -2625,7 +2625,7 @@ "pathEditor_searchRepeaters": "Търсене на повторители", "pathEditor_advancedHex": "Разширено: суров шестнадесетичен път", "pathEditor_hexLabel": "Шестнадесетични префикси", - "pathEditor_hexHelper": "Два шестнадесетични идентификатора на скок, разделени със запетаи", + "pathEditor_hexHelper": "{count} шестнадесетични идентификатора на скок, разделени със запетаи", "pathEditor_invalidTokens": "Невалидни: {tokens}", "routing_lastWorked": "последно работил {when}", "routing_deliveryCounts": "{successes} доставени, {failures} неуспешни", diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index f72e9821..2e05031a 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -1243,7 +1243,7 @@ "pathEditor_searchRepeaters": "Hledat opakovače", "pathEditor_advancedHex": "Pokročilé: surová hex cesta", "pathEditor_hexLabel": "Hex prefixy", - "pathEditor_hexHelper": "Dva hex znaky na skok, oddělené čárkami", + "pathEditor_hexHelper": "{count} hex znaky na skok, oddělené čárkami", "pathEditor_invalidTokens": "Neplatné: {tokens}", "@pathEditor_invalidTokens": { "placeholders": { diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 40d00f84..1b568750 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -2791,7 +2791,7 @@ "pathEditor_searchRepeaters": "Repeater suchen", "pathEditor_advancedHex": "Erweitert: roher Hex-Pfad", "pathEditor_hexLabel": "Hex-Präfixe", - "pathEditor_hexHelper": "Zwei Hex-Zeichen pro Sprung, durch Kommas getrennt", + "pathEditor_hexHelper": "{count} Hex-Zeichen pro Sprung, durch Kommas getrennt", "pathEditor_invalidTokens": "Ungültig: {tokens}", "pathEditor_tooManyHops": "Maximal 64 Sprünge", "pathEditor_usePath": "Diesen Pfad verwenden", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..c2ed54a6 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1391,10 +1391,17 @@ }, "pathEditor_noHops": "No hops yet. Tap repeaters below to add them in order, or save with no hops to send direct.", "pathEditor_addHops": "Add hops in order", - "pathEditor_searchRepeaters": "Search repeaters", + "pathEditor_searchRepeaters": "Search name or hash", "pathEditor_advancedHex": "Advanced: raw hex path", "pathEditor_hexLabel": "Hex prefixes", - "pathEditor_hexHelper": "Two hex characters per hop, separated by commas", + "pathEditor_hexHelper": "{count} hex characters per hop, separated by commas", + "@pathEditor_hexHelper": { + "placeholders": { + "count": { + "type": "int" + } + } + }, "pathEditor_invalidTokens": "Invalid: {tokens}", "@pathEditor_invalidTokens": { "placeholders": { diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 1b0ddb11..a7c49503 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -2675,7 +2675,7 @@ "pathEditor_searchRepeaters": "Buscar repetidores", "pathEditor_advancedHex": "Avanzado: ruta hexadecimal sin procesar", "pathEditor_hexLabel": "Prefijos hexadecimales", - "pathEditor_hexHelper": "Dos caracteres hexadecimales por salto, separados por comas.", + "pathEditor_hexHelper": "{count} caracteres hexadecimales por salto, separados por comas.", "pathEditor_invalidTokens": "Inválido: {tokens}", "pathEditor_tooManyHops": "Máximo 64 saltos", "pathEditor_usePath": "Usar esta ruta", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index de3c1be3..9aa4daa1 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2675,7 +2675,7 @@ "pathEditor_searchRepeaters": "Rechercher des répétiteurs", "pathEditor_advancedHex": "Avancé : chemin hexadécimal brut", "pathEditor_hexLabel": "Préfixes hexadécimaux", - "pathEditor_hexHelper": "Deux caractères hexadécimaux par saut, séparés par des virgules.", + "pathEditor_hexHelper": "{count} caractères hexadécimaux par saut, séparés par des virgules.", "pathEditor_invalidTokens": "Invalide : {tokens}", "pathEditor_tooManyHops": "Maximum 64 sauts", "pathEditor_usePath": "Utiliser ce chemin", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index ba73a0d6..f079dce3 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -2663,7 +2663,7 @@ "pathEditor_searchRepeaters": "Ismétlő keresése", "pathEditor_advancedHex": "Haladó: nyers hexadecimális útvonal", "pathEditor_hexLabel": "Hexadecimális előtagok", - "pathEditor_hexHelper": "Két hexadecimális karakter ugrásonként, vesszővel elválasztva", + "pathEditor_hexHelper": "{count} hexadecimális karakter ugrásonként, vesszővel elválasztva", "pathEditor_invalidTokens": "Érvénytelen: {tokens}", "routing_lastWorked": "dolgozott {when}", "routing_deliveryCounts": "{successes} kézbesítve, {failures} sikertelen", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 8d6bd2ec..9e0393bf 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -2680,7 +2680,7 @@ "pathEditor_searchRepeaters": "Cerca ripetitori", "pathEditor_advancedHex": "Avanzato: percorso esadecimale grezzo", "pathEditor_hexLabel": "Prefissi esadecimali", - "pathEditor_hexHelper": "Due caratteri esadecimali per ogni salto, separati da virgole.", + "pathEditor_hexHelper": "{count} caratteri esadecimali per ogni salto, separati da virgole.", "pathEditor_invalidTokens": "Non valido: {tokens}", "routing_lastWorked": "ha funzionato {when}", "pathEditor_tooManyHops": "Massimo 64 salti", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 0a3b8931..a7682fd6 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -2675,7 +2675,7 @@ "pathEditor_searchRepeaters": "リピータを検索", "pathEditor_advancedHex": "詳細: 生の 16 進経路", "pathEditor_hexLabel": "16 進接頭辞", - "pathEditor_hexHelper": "ホップごとに 16 進数 2 文字をカンマ区切りで入力します", + "pathEditor_hexHelper": "ホップごとに 16 進数 {count} 文字をカンマ区切りで入力します", "pathEditor_invalidTokens": "無効: {tokens}", "pathEditor_tooManyHops": "最大 64 ホップ", "pathEditor_usePath": "この経路を使用", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index dcaf27a3..1fcb9980 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -2579,7 +2579,7 @@ "pathEditor_searchRepeaters": "리피터 검색", "pathEditor_advancedHex": "고급: 원시 HEX 경로", "pathEditor_hexLabel": "HEX 접두사", - "pathEditor_hexHelper": "각 홉마다 2개의 16진수 바이트, 쉼표로 구분", + "pathEditor_hexHelper": "각 홉마다 {count}개의 16진수 문자, 쉼표로 구분", "pathEditor_invalidTokens": "유효하지 않음: {tokens}", "pathEditor_tooManyHops": "최대 64개의 홉", "pathEditor_usePath": "이 경로 사용", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..800269da 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -4720,7 +4720,7 @@ abstract class AppLocalizations { /// No description provided for @pathEditor_searchRepeaters. /// /// In en, this message translates to: - /// **'Search repeaters'** + /// **'Search name or hash'** String get pathEditor_searchRepeaters; /// No description provided for @pathEditor_advancedHex. @@ -4738,8 +4738,8 @@ abstract class AppLocalizations { /// No description provided for @pathEditor_hexHelper. /// /// In en, this message translates to: - /// **'Two hex characters per hop, separated by commas'** - String get pathEditor_hexHelper; + /// **'{count} hex characters per hop, separated by commas'** + String pathEditor_hexHelper(int count); /// No description provided for @pathEditor_invalidTokens. /// diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..b89785cf 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -2714,8 +2714,9 @@ class AppLocalizationsBg extends AppLocalizations { String get pathEditor_hexLabel => 'Шестнадесетични префикси'; @override - String get pathEditor_hexHelper => - 'Два шестнадесетични идентификатора на скок, разделени със запетаи'; + String pathEditor_hexHelper(int count) { + return '$count шестнадесетични идентификатора на скок, разделени със запетаи'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..112ad4fd 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -2706,7 +2706,9 @@ class AppLocalizationsCs extends AppLocalizations { String get pathEditor_hexLabel => 'Hex prefixy'; @override - String get pathEditor_hexHelper => 'Dva hex znaky na skok, oddělené čárkami'; + String pathEditor_hexHelper(int count) { + return '$count hex znaky na skok, oddělené čárkami'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..f9b79f7c 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2717,8 +2717,9 @@ class AppLocalizationsDe extends AppLocalizations { String get pathEditor_hexLabel => 'Hex-Präfixe'; @override - String get pathEditor_hexHelper => - 'Zwei Hex-Zeichen pro Sprung, durch Kommas getrennt'; + String pathEditor_hexHelper(int count) { + return '$count Hex-Zeichen pro Sprung, durch Kommas getrennt'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..bba7e7e8 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2661,7 +2661,7 @@ class AppLocalizationsEn extends AppLocalizations { String get pathEditor_addHops => 'Add hops in order'; @override - String get pathEditor_searchRepeaters => 'Search repeaters'; + String get pathEditor_searchRepeaters => 'Search name or hash'; @override String get pathEditor_advancedHex => 'Advanced: raw hex path'; @@ -2670,8 +2670,9 @@ class AppLocalizationsEn extends AppLocalizations { String get pathEditor_hexLabel => 'Hex prefixes'; @override - String get pathEditor_hexHelper => - 'Two hex characters per hop, separated by commas'; + String pathEditor_hexHelper(int count) { + return '$count hex characters per hop, separated by commas'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..37cf28c6 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2707,8 +2707,9 @@ class AppLocalizationsEs extends AppLocalizations { String get pathEditor_hexLabel => 'Prefijos hexadecimales'; @override - String get pathEditor_hexHelper => - 'Dos caracteres hexadecimales por salto, separados por comas.'; + String pathEditor_hexHelper(int count) { + return '$count caracteres hexadecimales por salto, separados por comas.'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..2ef6d2fc 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2711,8 +2711,9 @@ class AppLocalizationsFr extends AppLocalizations { String get pathEditor_hexLabel => 'Préfixes hexadécimaux'; @override - String get pathEditor_hexHelper => - 'Deux caractères hexadécimaux par saut, séparés par des virgules.'; + String pathEditor_hexHelper(int count) { + return '$count caractères hexadécimaux par saut, séparés par des virgules.'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..0cafc066 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -2704,8 +2704,9 @@ class AppLocalizationsHu extends AppLocalizations { String get pathEditor_hexLabel => 'Hexadecimális előtagok'; @override - String get pathEditor_hexHelper => - 'Két hexadecimális karakter ugrásonként, vesszővel elválasztva'; + String pathEditor_hexHelper(int count) { + return '$count hexadecimális karakter ugrásonként, vesszővel elválasztva'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..f0352798 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2711,8 +2711,9 @@ class AppLocalizationsIt extends AppLocalizations { String get pathEditor_hexLabel => 'Prefissi esadecimali'; @override - String get pathEditor_hexHelper => - 'Due caratteri esadecimali per ogni salto, separati da virgole.'; + String pathEditor_hexHelper(int count) { + return '$count caratteri esadecimali per ogni salto, separati da virgole.'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..0aaef47b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2587,7 +2587,9 @@ class AppLocalizationsJa extends AppLocalizations { String get pathEditor_hexLabel => '16 進接頭辞'; @override - String get pathEditor_hexHelper => 'ホップごとに 16 進数 2 文字をカンマ区切りで入力します'; + String pathEditor_hexHelper(int count) { + return 'ホップごとに 16 進数 $count 文字をカンマ区切りで入力します'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..5b99499f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2590,7 +2590,9 @@ class AppLocalizationsKo extends AppLocalizations { String get pathEditor_hexLabel => 'HEX 접두사'; @override - String get pathEditor_hexHelper => '각 홉마다 2개의 16진수 바이트, 쉼표로 구분'; + String pathEditor_hexHelper(int count) { + return '각 홉마다 $count개의 16진수 문자, 쉼표로 구분'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..6d854004 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -2696,8 +2696,9 @@ class AppLocalizationsNl extends AppLocalizations { String get pathEditor_hexLabel => 'Hex-prefixen'; @override - String get pathEditor_hexHelper => - 'Twee hex-tekens per hop, gescheiden door komma\'s'; + String pathEditor_hexHelper(int count) { + return '$count hex-tekens per hop, gescheiden door komma\'s'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..04bf7d6c 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -2738,8 +2738,9 @@ class AppLocalizationsPl extends AppLocalizations { String get pathEditor_hexLabel => 'Prefiksy heksadecymalne'; @override - String get pathEditor_hexHelper => - 'Dwa znaki szesnastkowe na każdym kroku, oddzielone przecinkami'; + String pathEditor_hexHelper(int count) { + return '$count znaki szesnastkowe na każdym kroku, oddzielone przecinkami'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..feb15cdc 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2706,8 +2706,9 @@ class AppLocalizationsPt extends AppLocalizations { String get pathEditor_hexLabel => 'Prefixos hexadecimais'; @override - String get pathEditor_hexHelper => - 'Dois caracteres hexadecimais por salto, separados por vírgulas.'; + String pathEditor_hexHelper(int count) { + return '$count caracteres hexadecimais por salto, separados por vírgulas.'; + } @override String pathEditor_invalidTokens(String tokens) { @@ -10231,8 +10232,9 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { String get pathEditor_hexLabel => 'Prefixos hex'; @override - String get pathEditor_hexHelper => - 'Dois caracteres hex por hop, separados por vírgulas'; + String pathEditor_hexHelper(int count) { + return '$count caracteres hex por hop, separados por vírgulas'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..d0d031c4 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2717,8 +2717,9 @@ class AppLocalizationsRu extends AppLocalizations { String get pathEditor_hexLabel => 'Префиксы шестнадцатеричной системы'; @override - String get pathEditor_hexHelper => - 'Два шестнадцатеричных символа на каждом шаге, разделенные запятыми.'; + String pathEditor_hexHelper(int count) { + return '$count шестнадцатеричных символа на каждом шаге, разделенные запятыми.'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..deec1017 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -2708,8 +2708,9 @@ class AppLocalizationsSk extends AppLocalizations { String get pathEditor_hexLabel => 'Prefiksy pre hexadecimálne čísla'; @override - String get pathEditor_hexHelper => - 'Dve hexové čísla na každý krok, oddelené čiarkami'; + String pathEditor_hexHelper(int count) { + return '$count hexové čísla na každý krok, oddelené čiarkami'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..573c0cd4 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -2705,8 +2705,9 @@ class AppLocalizationsSl extends AppLocalizations { String get pathEditor_hexLabel => 'Predfiks za heksadecimalno šifro'; @override - String get pathEditor_hexHelper => - 'Dva šestbitna znaka na vsak skok, ločena z vejico'; + String pathEditor_hexHelper(int count) { + return '$count šestnajstiških znakov na vsak skok, ločenih z vejico'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..fc3c7539 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -2684,8 +2684,9 @@ class AppLocalizationsSv extends AppLocalizations { String get pathEditor_hexLabel => 'Hex-prefikser'; @override - String get pathEditor_hexHelper => - 'Två hextecken per hopp, separerade med kommatecken'; + String pathEditor_hexHelper(int count) { + return '$count hextecken per hopp, separerade med kommatecken'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..c0b66621 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -2715,8 +2715,9 @@ class AppLocalizationsUk extends AppLocalizations { 'Префікси для шестнадцяткової системи числення'; @override - String get pathEditor_hexHelper => - 'Два шестизначні символи на кожний крок, розділені комами'; + String pathEditor_hexHelper(int count) { + return '$count шістнадцяткові символи на кожний крок, розділені комами'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..d1e28290 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2546,7 +2546,9 @@ class AppLocalizationsZh extends AppLocalizations { String get pathEditor_hexLabel => '十六进制前缀'; @override - String get pathEditor_hexHelper => '每跳使用两个十六进制字符,用逗号分隔。'; + String pathEditor_hexHelper(int count) { + return '每跳使用$count个十六进制字符,用逗号分隔。'; + } @override String pathEditor_invalidTokens(String tokens) { diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 2f192869..93f61445 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -2682,7 +2682,7 @@ "pathEditor_searchRepeaters": "Repeaters zoeken", "pathEditor_advancedHex": "Geavanceerd: ruwe hex-pad", "pathEditor_hexLabel": "Hex-prefixen", - "pathEditor_hexHelper": "Twee hex-tekens per hop, gescheiden door komma's", + "pathEditor_hexHelper": "{count} hex-tekens per hop, gescheiden door komma's", "pathEditor_invalidTokens": "Ongeldig: {tokens}", "pathEditor_tooManyHops": "Maximaal 64 hops", "pathEditor_usePath": "Dit pad gebruiken", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index af3783a1..e4850bd4 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -2658,7 +2658,7 @@ "pathEditor_searchRepeaters": "Funkcje powtarzania", "pathEditor_advancedHex": "Zaawansowane: ścieżka w formacie szesnastkowym", "pathEditor_hexLabel": "Prefiksy heksadecymalne", - "pathEditor_hexHelper": "Dwa znaki szesnastkowe na każdym kroku, oddzielone przecinkami", + "pathEditor_hexHelper": "{count} znaki szesnastkowe na każdym kroku, oddzielone przecinkami", "pathEditor_invalidTokens": "Nieprawidłowe: {tokens}", "pathEditor_tooManyHops": "Maksymalnie 64 hopów", "pathEditor_usePath": "Użyj tej ścieżki.", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index ad24e07a..51dbc222 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -2540,7 +2540,7 @@ "pathEditor_searchRepeaters": "Encontrar repetidores", "pathEditor_advancedHex": "Avançado: caminho hexadecimal bruto", "pathEditor_hexLabel": "Prefixos hexadecimais", - "pathEditor_hexHelper": "Dois caracteres hexadecimais por salto, separados por vírgulas.", + "pathEditor_hexHelper": "{count} caracteres hexadecimais por salto, separados por vírgulas.", "pathEditor_invalidTokens": "Inválido: {tokens}", "routing_lastWorked": "funcionou {when}", "pathEditor_tooManyHops": "Máximo de 64 saltos", diff --git a/lib/l10n/app_pt_PT.arb b/lib/l10n/app_pt_PT.arb index 80218599..7f093675 100644 --- a/lib/l10n/app_pt_PT.arb +++ b/lib/l10n/app_pt_PT.arb @@ -758,7 +758,7 @@ "pathEditor_searchRepeaters": "Pesquisar repetidores", "pathEditor_advancedHex": "Avançado: caminho hex em bruto", "pathEditor_hexLabel": "Prefixos hex", - "pathEditor_hexHelper": "Dois caracteres hex por hop, separados por vírgulas", + "pathEditor_hexHelper": "{count} caracteres hex por hop, separados por vírgulas", "pathEditor_invalidTokens": "Inválido: {tokens}", "pathEditor_tooManyHops": "Máximo de 64 hops", "pathEditor_usePath": "Usar este caminho", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index f5ff336c..c15c5e40 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -1922,7 +1922,7 @@ "pathEditor_searchRepeaters": "Поиск повторителей", "pathEditor_advancedHex": "Продвинутый уровень: прямой путь в шестнадцатеричном формате", "pathEditor_hexLabel": "Префиксы шестнадцатеричной системы", - "pathEditor_hexHelper": "Два шестнадцатеричных символа на каждом шаге, разделенные запятыми.", + "pathEditor_hexHelper": "{count} шестнадцатеричных символа на каждом шаге, разделенные запятыми.", "pathEditor_invalidTokens": "Неверно: {tokens}", "routing_lastWorked": "работал {when}", "routing_deliveryCounts": "{successes} доставлено, {failures} не доставлено", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index c582c8f4..ea09a446 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -2625,7 +2625,7 @@ "pathEditor_searchRepeaters": "Hľadať opakované", "pathEditor_advancedHex": "Pokročilé: pôvodná hexová cesta", "pathEditor_hexLabel": "Prefiksy pre hexadecimálne čísla", - "pathEditor_hexHelper": "Dve hexové čísla na každý krok, oddelené čiarkami", + "pathEditor_hexHelper": "{count} hexové čísla na každý krok, oddelené čiarkami", "routing_lastWorked": "fungovala {when}", "pathEditor_invalidTokens": "Neplatné: {tokens}", "routing_deliveryCounts": "{successes} doručených, {failures} neúspešných", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 3dcbeb94..40fb0b5b 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -2534,7 +2534,7 @@ "pathEditor_searchRepeaters": "Iskanje ponovitev", "pathEditor_advancedHex": "Napredno: surovi šestnajstni pot", "pathEditor_hexLabel": "Predfiks za heksadecimalno šifro", - "pathEditor_hexHelper": "Dva šestbitna znaka na vsak skok, ločena z vejico", + "pathEditor_hexHelper": "{count} šestnajstiških znakov na vsak skok, ločenih z vejico", "pathEditor_invalidTokens": "Neveljaven: {tokens}", "pathEditor_tooManyHops": "Največ 64 hopov", "pathEditor_usePath": "Uporabite to poto", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 7ec4e120..7fc55b2e 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -2529,7 +2529,7 @@ "pathEditor_searchRepeaters": "Sök repeaters", "pathEditor_advancedHex": "Avancerat: rå rutt i hexformat", "pathEditor_hexLabel": "Hex-prefikser", - "pathEditor_hexHelper": "Två hextecken per hopp, separerade med kommatecken", + "pathEditor_hexHelper": "{count} hextecken per hopp, separerade med kommatecken", "pathEditor_invalidTokens": "Ogiltigt: {tokens}", "pathEditor_tooManyHops": "Maximalt 64 hopp", "pathEditor_usePath": "Använd den här rutten", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 16d0ca20..e1d60645 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -2598,7 +2598,7 @@ "pathEditor_searchRepeaters": "Пошук повторювачів", "pathEditor_advancedHex": "Просунутий рівень: пряма шлях у форматі шестнадцяткової системи.", "pathEditor_hexLabel": "Префікси для шестнадцяткової системи числення", - "pathEditor_hexHelper": "Два шестизначні символи на кожний крок, розділені комами", + "pathEditor_hexHelper": "{count} шістнадцяткові символи на кожний крок, розділені комами", "pathEditor_invalidTokens": "Неправильно: {tokens}", "routing_lastWorked": "працював {when}", "routing_deliveryCounts": "{successes} доставлено, {failures} не доставлено", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6b70ddb0..ce2a3aa8 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2538,7 +2538,7 @@ "pathEditor_searchRepeaters": "重复搜索", "pathEditor_advancedHex": "高级:原始十六进制路径", "pathEditor_hexLabel": "十六进制前缀", - "pathEditor_hexHelper": "每跳使用两个十六进制字符,用逗号分隔。", + "pathEditor_hexHelper": "每跳使用{count}个十六进制字符,用逗号分隔。", "pathEditor_invalidTokens": "无效:{tokens}", "pathEditor_tooManyHops": "最多 64 跳", "pathEditor_usePath": "请使用此路径", diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 2d60dd3a..97c439a9 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -1201,26 +1201,26 @@ class _ContactsScreenState extends State { }).toList(); } - switch (viewState.contactsSortOption) { - case ContactSortOption.lastSeen: - filtered.sort( - (a, b) => - resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)), - ); - break; - case ContactSortOption.recentMessages: - final lastMessageAt = { - for (final c in filtered) c: _lastMessageTime(connector, c), - }; - filtered.sort((a, b) => lastMessageAt[b]!.compareTo(lastMessageAt[a]!)); - break; - case ContactSortOption.name: - filtered.sort( - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), - ); - break; + final lastMessageAt = + viewState.contactsSortOption == ContactSortOption.recentMessages + ? {for (final c in filtered) c: _lastMessageTime(connector, c)} + : null; + int tieBreak(Contact a, Contact b) { + switch (viewState.contactsSortOption) { + case ContactSortOption.lastSeen: + return resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)); + case ContactSortOption.recentMessages: + return lastMessageAt![b]!.compareTo(lastMessageAt[a]!); + case ContactSortOption.name: + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + } } + filtered.sort( + (a, b) => + compareContactQueryRank(a, b, viewState.contactsSearchText, tieBreak), + ); + return filtered; } @@ -1409,11 +1409,14 @@ class _ContactsScreenState extends State { builder: (builderContext, setDialogState) { final filteredContacts = filterQuery.isEmpty ? sortedContacts - : sortedContacts + : (sortedContacts .where( (contact) => matchesContactQuery(contact, filterQuery), ) - .toList(); + .toList() + ..sort( + (a, b) => compareContactQueryRank(a, b, filterQuery), + )); return AlertDialog( title: Text( isEditing diff --git a/lib/screens/discovery_screen.dart b/lib/screens/discovery_screen.dart index 24506563..5c5ad42a 100644 --- a/lib/screens/discovery_screen.dart +++ b/lib/screens/discovery_screen.dart @@ -662,17 +662,32 @@ class _DiscoveryScreenState extends State { return _matchesTypeFilter(contact); }).toList(); - switch (sortOption) { - case ContactSortOption.lastSeen: - filtered.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); - break; - case ContactSortOption.name: - filtered.sort( - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), - ); - break; - default: - break; + int tieBreak(Contact a, Contact b) { + switch (sortOption) { + case ContactSortOption.lastSeen: + return b.lastSeen.compareTo(a.lastSeen); + case ContactSortOption.name: + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + default: + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + } + } + + if (searchQuery.trim().isEmpty) { + switch (sortOption) { + case ContactSortOption.lastSeen: + filtered.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); + case ContactSortOption.name: + filtered.sort( + (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), + ); + default: + break; + } + } else { + filtered.sort( + (a, b) => compareContactQueryRank(a, b, searchQuery, tieBreak), + ); } return filtered; diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 018b7ec8..5715fb16 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -2292,13 +2292,14 @@ class _MapScreenState extends State with WidgetsBindingObserver { ) { final query = _searchQuery.trim().toLowerCase(); final matches = - allContacts.where((c) => matchesContactQuery(c, query)).toList() - ..sort((a, b) { + allContacts.where((c) => matchesContactQuery(c, query)).toList()..sort( + (a, b) => compareContactQueryRank(a, b, query, (a, b) { if (a.hasLocation != b.hasLocation) { return a.hasLocation ? -1 : 1; } return b.lastHeard.compareTo(a.lastHeard); - }); + }), + ); final results = matches.take(8).toList(); return Container( margin: const EdgeInsets.only(top: 6), @@ -3464,6 +3465,15 @@ class _MapScreenState extends State with WidgetsBindingObserver { contact.type != advTypeRoom, ) .toList(); + final people = allContacts + .where( + (contact) => + query.isEmpty || matchesContactQuery(contact, query), + ) + .toList(); + if (query.isNotEmpty) { + people.sort((a, b) => compareContactQueryRank(a, b, query)); + } return SafeArea( child: SingleChildScrollView( child: Column( @@ -3499,29 +3509,23 @@ class _MapScreenState extends State with WidgetsBindingObserver { }, ), ), - ...allContacts - .where( - (contact) => - query.isEmpty || - matchesContactQuery(contact, query), - ) - .map((contact) { - return ListTile( - leading: const Icon(Icons.person), - title: Text(contact.name), - onTap: () { - Navigator.pop(sheetContext); - if (!_markerFits( - context, - markerText, - maxContactMessageBytes(), - )) { - return; - } - liveConnector.sendMessage(contact, markerText); - }, - ); - }), + ...people.map((contact) { + return ListTile( + leading: const Icon(Icons.person), + title: Text(contact.name), + onTap: () { + Navigator.pop(sheetContext); + if (!_markerFits( + context, + markerText, + maxContactMessageBytes(), + )) { + return; + } + liveConnector.sendMessage(contact, markerText); + }, + ); + }), Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), child: Text( diff --git a/lib/utils/contact_search.dart b/lib/utils/contact_search.dart index 7a82c53a..eaad99c2 100644 --- a/lib/utils/contact_search.dart +++ b/lib/utils/contact_search.dart @@ -2,31 +2,55 @@ import '../models/contact.dart'; export 'contact_filter_types.dart'; -bool matchesContactQuery(Contact contact, String query) { - final normalizedQuery = query.trim().toLowerCase(); - if (normalizedQuery.isEmpty) return true; +/// How closely a contact matches a search query. Lower ranks sort first. +enum ContactQueryRank { namePrefix, nameContains, keyPrefix } - if (contact.name.toLowerCase().contains(normalizedQuery)) { - return true; +/// Rank for [query], or null when the contact does not match. +/// +/// Names that start with the query come before other substring matches. +/// A public-key / hop-hash prefix matches only when the name does not. +ContactQueryRank? rankContactQuery(Contact contact, String query) { + final normalized = query.trim().toLowerCase(); + if (normalized.isEmpty) return ContactQueryRank.namePrefix; + + final name = contact.name.toLowerCase(); + if (name.startsWith(normalized)) return ContactQueryRank.namePrefix; + if (name.contains(normalized)) return ContactQueryRank.nameContains; + if (_publicKeyPrefixMatches(contact, normalized)) { + return ContactQueryRank.keyPrefix; } + return null; +} - final hexPrefix = _extractHexPrefix(normalizedQuery); - if (hexPrefix == null) return false; - - return contact.publicKeyHex.toLowerCase().startsWith(hexPrefix); +bool matchesContactQuery(Contact contact, String query) { + return rankContactQuery(contact, query) != null; } bool matchesDiscoveryContactQuery(Contact contact, String query) { - final normalizedQuery = query.trim().toLowerCase(); - if (normalizedQuery.isEmpty) return true; + return matchesContactQuery(contact, query); +} - if (contact.name.toLowerCase().contains(normalizedQuery)) { - return true; - } +/// Sorts prefix matches ahead of other substring matches, then key matches. +/// +/// [tieBreak] orders contacts that share a rank. With an empty query every +/// contact shares the top rank, so [tieBreak] is the whole order. +int compareContactQueryRank( + Contact a, + Contact b, + String query, [ + int Function(Contact a, Contact b)? tieBreak, +]) { + final left = rankContactQuery(a, query); + final right = rankContactQuery(b, query); + final byRank = (left?.index ?? 3).compareTo(right?.index ?? 3); + if (byRank != 0) return byRank; + return tieBreak?.call(a, b) ?? + a.name.toLowerCase().compareTo(b.name.toLowerCase()); +} +bool _publicKeyPrefixMatches(Contact contact, String normalizedQuery) { final hexPrefix = _extractHexPrefix(normalizedQuery); - if (hexPrefix == null) return false; - + if (hexPrefix == null || contact.publicKey.isEmpty) return false; return contact.publicKeyHex.toLowerCase().startsWith(hexPrefix); } diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index f20aad1c..73a34b31 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -1,12 +1,16 @@ -import 'dart:typed_data'; +import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/path_helper.dart'; import '../l10n/contact_localization.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; +import '../theme/mesh_theme.dart'; +import '../utils/contact_search.dart'; class PathEditorSheet extends StatefulWidget { final List availableContacts; @@ -30,19 +34,25 @@ class PathEditorSheet extends StatefulWidget { context: context, isScrollControlled: true, useSafeArea: true, - builder: (context) => Padding( - padding: EdgeInsets.only( - bottom: MediaQuery.of(context).viewInsets.bottom, - ), - child: FractionallySizedBox( - heightFactor: 0.9, - child: PathEditorSheet( - availableContacts: availableContacts, - initialPath: initialPath, - pathHashByteWidth: pathHashByteWidth, + builder: (context) { + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + return Padding( + padding: EdgeInsets.only(bottom: keyboard), + child: Align( + alignment: Alignment.bottomCenter, + child: FractionallySizedBox( + // The keyboard already shrinks the sheet. Use the full band + // above it so the hop list is not clipped under the title. + heightFactor: keyboard > 0 ? 1 : 0.92, + child: PathEditorSheet( + availableContacts: availableContacts, + initialPath: initialPath, + pathHashByteWidth: pathHashByteWidth, + ), + ), ), - ), - ), + ); + }, ); } @@ -62,10 +72,13 @@ class _PathEditorSheetState extends State { final List<_Hop> _hops = []; final _hexController = TextEditingController(); + final _hopScroll = ScrollController(); String? _hexError; bool _syncingHex = false; String _search = ''; int _nextHopId = 0; + int? _highlightedHopId; + Timer? _highlightTimer; @override void initState() { @@ -81,18 +94,25 @@ class _PathEditorSheetState extends State { @override void dispose() { + _highlightTimer?.cancel(); + _hopScroll.dispose(); _hexController.dispose(); super.dispose(); } + int get _hashChars { + final width = widget.pathHashByteWidth.clamp(1, pubKeySize).toInt(); + return width * 2; + } + List get _repeaters { - final query = _search.trim().toLowerCase(); + final query = _search.trim(); return widget.availableContacts .where((c) => c.type == advTypeRepeater || c.type == advTypeRoom) .where((c) => c.publicKey.isNotEmpty) - .where((c) => query.isEmpty || c.name.toLowerCase().contains(query)) + .where((c) => rankContactQuery(c, query) != null) .toList() - ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + ..sort((a, b) => compareContactQueryRank(a, b, query)); } void _syncHexFromHops() { @@ -129,6 +149,7 @@ class _PathEditorSheetState extends State { return; } _hexError = null; + final previous = _hops.length; _hops ..clear() ..addAll( @@ -140,6 +161,9 @@ class _PathEditorSheetState extends State { return _Hop(_nextHopId++, Uint8List.fromList(bytes)); }), ); + if (_hops.length > previous && _hops.isNotEmpty) { + _markHopAdded(_hops.last.id); + } }); } @@ -148,14 +172,38 @@ class _PathEditorSheetState extends State { final width = widget.pathHashByteWidth .clamp(1, contact.publicKey.length) .toInt(); + HapticFeedback.selectionClick(); setState(() { - _hops.add( - _Hop( - _nextHopId++, - Uint8List.fromList(contact.publicKey.sublist(0, width)), - ), + final hop = _Hop( + _nextHopId++, + Uint8List.fromList(contact.publicKey.sublist(0, width)), ); + _hops.add(hop); _syncHexFromHops(); + _markHopAdded(hop.id); + }); + } + + void _markHopAdded(int id) { + _highlightedHopId = id; + _highlightTimer?.cancel(); + _highlightTimer = Timer(const Duration(milliseconds: 1400), () { + if (!mounted) return; + setState(() { + if (_highlightedHopId == id) _highlightedHopId = null; + }); + }); + _revealLatestHop(); + } + + void _revealLatestHop() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !_hopScroll.hasClients) return; + _hopScroll.animateTo( + _hopScroll.position.maxScrollExtent, + duration: const Duration(milliseconds: 180), + curve: Curves.easeOut, + ); }); } @@ -182,7 +230,14 @@ class _PathEditorSheetState extends State { Navigator.pop(context, Uint8List.fromList(bytes)); } - Widget _hopTile(BuildContext context, int index) { + String _contactHopHex(Contact contact) { + final width = widget.pathHashByteWidth + .clamp(1, contact.publicKey.length) + .toInt(); + return PathHelper.formatHopHex(contact.publicKey.sublist(0, width)); + } + + Widget _hopTile(BuildContext context, int index, {required bool singleLine}) { final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; final hop = _hops[index]; @@ -200,41 +255,61 @@ class _PathEditorSheetState extends State { : matches.length == 1 ? matches.first.name : matches.map((c) => c.name).join(' | '); + final highlighted = hop.id == _highlightedHopId; - return ListTile( + final label = name ?? l10n.pathEditor_unknownHop; + final hash = Text(hex, style: MeshTheme.mono(fontSize: 12)); + return Material( key: ValueKey(hop.id), - contentPadding: EdgeInsets.zero, - leading: CircleAvatar( - radius: 14, - backgroundColor: scheme.primaryContainer, - child: Text( - '${index + 1}', - style: TextStyle(fontSize: 12, color: scheme.onPrimaryContainer), + color: highlighted ? scheme.primaryContainer : scheme.surfaceContainerLow, + child: ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + visualDensity: singleLine + ? VisualDensity.compact + : VisualDensity.standard, + minVerticalPadding: singleLine ? 0 : 4, + leading: CircleAvatar( + radius: 16, + backgroundColor: scheme.primary, + child: Text( + '${index + 1}', + style: TextStyle(fontSize: 12, color: scheme.onPrimary), + ), ), - ), - title: Text( - name ?? l10n.pathEditor_unknownHop, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - subtitle: Text(hex), - trailing: Row( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - icon: const Icon(Icons.remove_circle_outline), - tooltip: l10n.pathEditor_removeHop, - constraints: const BoxConstraints(minWidth: 44, minHeight: 44), - onPressed: () => _removeHop(index), - ), - ReorderableDragStartListener( - index: index, - child: const Padding( - padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12), - child: Icon(Icons.drag_handle), + title: singleLine + ? Row( + children: [ + Expanded( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 8), + hash, + ], + ) + : Text(label, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: singleLine ? null : hash, + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.remove_circle_outline), + tooltip: l10n.pathEditor_removeHop, + onPressed: () => _removeHop(index), ), - ), - ], + ReorderableDragStartListener( + index: index, + child: const SizedBox( + width: 48, + height: 48, + child: Icon(Icons.drag_handle), + ), + ), + ], + ), ), ); } @@ -246,16 +321,16 @@ class _PathEditorSheetState extends State { final full = _hops.length >= _maxHops; return ListTile( - contentPadding: EdgeInsets.zero, + contentPadding: const EdgeInsets.symmetric(vertical: 4), enabled: !full, leading: CircleAvatar( - radius: 16, + radius: 18, backgroundColor: isRepeater ? scheme.primaryContainer : scheme.secondaryContainer, child: Icon( isRepeater ? Icons.router : Icons.meeting_room, - size: 16, + size: 18, color: isRepeater ? scheme.onPrimaryContainer : scheme.onSecondaryContainer, @@ -263,13 +338,36 @@ class _PathEditorSheetState extends State { ), title: Text(contact.name, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text( - '${contact.typeLabel(l10n)} • ${PathHelper.formatHopHex(contact.publicKey.sublist(0, widget.pathHashByteWidth.clamp(1, contact.publicKey.length).toInt()))}', + '${contact.typeLabel(l10n)} • ${_contactHopHex(contact)}', + style: MeshTheme.mono(fontSize: 12), + ), + trailing: Icon( + Icons.add_circle_outline, + color: full ? scheme.outline : scheme.primary, ), - trailing: const Icon(Icons.add_circle_outline), onTap: full ? null : () => _addHop(contact), ); } + double _hopViewportHeight(double maxHeight, bool tight) { + if (_hops.isEmpty) return 0; + final scaler = MediaQuery.textScalerOf(context); + final rowExtent = tight + ? scaler.scale(56).clamp(56.0, 80.0) + : scaler.scale(76).clamp(72.0, 132.0); + final visibleRows = math.min(_hops.length, tight ? 2 : 3); + final wanted = visibleRows * rowExtent + 4; + // Header, hex field, search field, and the action row stay on screen. + // The hop viewport takes what is left, and never pushes the buttons + // up over the repeater list. + final chrome = tight ? 210.0 : 430.0; + final available = maxHeight - chrome; + if (available >= rowExtent) { + return math.min(wanted, available); + } + return math.max(0.0, available); + } + @override Widget build(BuildContext context) { final l10n = context.l10n; @@ -277,139 +375,208 @@ class _PathEditorSheetState extends State { final scheme = theme.colorScheme; final repeaters = _repeaters; - return Column( - children: [ - const SizedBox(height: 8), - Container( - width: 32, - height: 4, - decoration: BoxDecoration( - color: scheme.outlineVariant, - borderRadius: BorderRadius.circular(2), - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(l10n.pathEditor_title, style: theme.textTheme.titleLarge), - Text( - l10n.pathEditor_hopCounter(_hops.length), - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Expanded( - child: ListView( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), - children: [ - if (_hops.isEmpty) - Padding( - padding: const EdgeInsets.symmetric(vertical: 12), - child: Text( - l10n.pathEditor_noHops, - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ) - else - ReorderableListView.builder( - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - buildDefaultDragHandles: false, - itemCount: _hops.length, - onReorderItem: _reorderHop, - itemBuilder: _hopTile, - ), - const Divider(), - const SizedBox(height: 8), - Text(l10n.pathEditor_addHops, style: theme.textTheme.titleSmall), - const SizedBox(height: 8), - TextField( - onChanged: (value) => setState(() => _search = value), - decoration: InputDecoration( - labelText: l10n.pathEditor_searchRepeaters, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: true, - ), - ), - const SizedBox(height: 4), - if (repeaters.isEmpty) - Padding( - padding: const EdgeInsets.symmetric(vertical: 12), - child: Text( - l10n.path_noRepeatersFound, - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ) - else - ...repeaters.map((c) => _repeaterTile(context, c)), - ExpansionTile( - tilePadding: EdgeInsets.zero, - title: Text( - l10n.pathEditor_advancedHex, - style: theme.textTheme.titleSmall, - ), + return LayoutBuilder( + builder: (context, constraints) { + final maxHeight = constraints.maxHeight.isFinite + ? constraints.maxHeight + : 640.0; + // Phone sheets and a keyboard-shrunk window use the shorter hop rows + // so the action buttons stay below the repeater list. + final compact = maxHeight < 680; + final hopHeight = _hopViewportHeight(maxHeight, compact); + + return Column( + children: [ + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 10, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding( - padding: const EdgeInsets.only(bottom: 12), - child: TextField( - controller: _hexController, - onChanged: _onHexChanged, - textCapitalization: TextCapitalization.characters, - decoration: InputDecoration( - labelText: l10n.pathEditor_hexLabel, - helperText: _hexError == null - ? l10n.pathEditor_hexHelper - : null, - errorText: _hexError, - border: const OutlineInputBorder(), + Center( + child: Container( + width: 36, + height: 4, + decoration: BoxDecoration( + color: scheme.outline, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + SizedBox(height: compact ? 4 : 12), + Text( + l10n.pathEditor_title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w700, + letterSpacing: -0.2, + ), + ), + Semantics( + liveRegion: true, + child: Text( + l10n.pathEditor_hopCounter(_hops.length), + style: theme.textTheme.bodySmall?.copyWith( + color: scheme.onSurfaceVariant, ), ), ), ], ), - ], - ), - ), - SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: Row( - children: [ - Expanded( - child: TextButton( - style: TextButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_cancel), - ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - style: FilledButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: _hexError != null ? null : _save, - child: Text(l10n.pathEditor_usePath), - ), - ), - ], ), - ), - ), - ], + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 4 : 10, 16, 0), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: scheme.outlineVariant), + ), + child: _hops.isEmpty + ? Padding( + padding: const EdgeInsets.all(12), + child: Text( + l10n.pathEditor_noHops, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ) + : SizedBox( + height: hopHeight, + child: ReorderableListView.builder( + scrollController: _hopScroll, + buildDefaultDragHandles: false, + padding: EdgeInsets.symmetric( + vertical: compact ? 0 : 4, + ), + itemCount: _hops.length, + onReorderItem: _reorderHop, + itemBuilder: (context, index) => + _hopTile(context, index, singleLine: compact), + ), + ), + ), + ), + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 16, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!compact) ...[ + Text( + l10n.pathEditor_advancedHex, + style: theme.textTheme.titleSmall, + ), + const SizedBox(height: 8), + ], + TextField( + key: const Key('path-editor-hex-field'), + controller: _hexController, + onChanged: _onHexChanged, + textCapitalization: TextCapitalization.characters, + style: MeshTheme.mono(fontSize: 14), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_hexLabel, + helperText: compact || _hexError != null + ? null + : l10n.pathEditor_hexHelper(_hashChars), + helperMaxLines: 3, + errorText: _hexError, + errorMaxLines: 3, + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], + ), + ), + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 14, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!compact) ...[ + Text( + l10n.pathEditor_addHops, + style: theme.textTheme.titleSmall, + ), + const SizedBox(height: 8), + ], + TextField( + key: const Key('path-editor-search-field'), + onChanged: (value) => setState(() => _search = value), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_searchRepeaters, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], + ), + ), + Expanded( + child: repeaters.isEmpty + ? Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Align( + alignment: Alignment.topLeft, + child: Text( + l10n.path_noRepeatersFound, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ) + : ListView.builder( + key: const Key('path-editor-repeater-list'), + keyboardDismissBehavior: + ScrollViewKeyboardDismissBehavior.onDrag, + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + itemCount: repeaters.length, + itemBuilder: (context, index) => + _repeaterTile(context, repeaters[index]), + ), + ), + SafeArea( + top: false, + child: Padding( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 4 : 8, + 16, + compact ? 4 : 16, + ), + child: Row( + children: [ + Expanded( + child: TextButton( + style: TextButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: _hexError != null ? null : _save, + child: Text(l10n.pathEditor_usePath), + ), + ), + ], + ), + ), + ), + ], + ); + }, ); } } diff --git a/lib/widgets/share_contact_sheet.dart b/lib/widgets/share_contact_sheet.dart index df0549d7..c38c48d1 100644 --- a/lib/widgets/share_contact_sheet.dart +++ b/lib/widgets/share_contact_sheet.dart @@ -7,6 +7,7 @@ import '../l10n/contact_localization.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../theme/mesh_theme.dart'; +import '../utils/contact_search.dart'; import 'mesh_ui.dart'; /// Lets the user pick a saved contact (or themself) and appends the encoded @@ -50,14 +51,10 @@ class _ShareContactSheetState extends State<_ShareContactSheet> { final contacts = connector.contacts .where( - (c) => - c.publicKey.length == 32 && - (needle.isEmpty || c.name.toLowerCase().contains(needle)), + (c) => c.publicKey.length == 32 && matchesContactQuery(c, needle), ) .toList() - ..sort( - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), - ); + ..sort((a, b) => compareContactQueryRank(a, b, needle)); final selfName = connector.selfName ?? ''; final showSelf = selfKey != null && diff --git a/test/utils/contact_search_test.dart b/test/utils/contact_search_test.dart new file mode 100644 index 00000000..d2d1cff4 --- /dev/null +++ b/test/utils/contact_search_test.dart @@ -0,0 +1,109 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/utils/contact_search.dart'; + +Contact _contact( + String name, + List key, { + int type = advTypeRepeater, + DateTime? lastSeen, +}) { + return Contact( + publicKey: Uint8List.fromList(key), + name: name, + type: type, + pathLength: -1, + path: Uint8List(0), + lastSeen: lastSeen ?? DateTime.fromMillisecondsSinceEpoch(0), + ); +} + +List _ranked(List contacts, String query) { + final matches = contacts.where((c) => matchesContactQuery(c, query)).toList() + ..sort((a, b) => compareContactQueryRank(a, b, query)); + return matches.map((c) => c.name).toList(); +} + +void main() { + final contacts = [ + _contact('100 Acre', [0x11, 0x22, 0x33, 0x44]), + _contact('Acreage North', [0x33, 0x44, 0x55, 0x66]), + _contact('My Acre Site', [0x55, 0x66, 0x77, 0x88]), + _contact('2E0HQR-R', [0x2E, 0x0A, 0x1B, 0x2C]), + _contact('CR1', [0x60, 0x60, 0xAB, 0xCD]), + _contact('Node 6060', [0x01, 0x02, 0x03, 0x04]), + _contact('6060 Hub', [0x0A, 0x0B, 0x0C, 0x0D]), + ]; + + test('name prefixes rank before other substring matches', () { + expect(_ranked(contacts, 'acre'), [ + 'Acreage North', + '100 Acre', + 'My Acre Site', + ]); + }); + + test('prefix matches stay alphabetical among themselves', () { + final extra = [ + _contact('Acreage North', [0x01]), + _contact('Acre Beacon', [0x02]), + ]; + expect(_ranked(extra, 'acre'), ['Acre Beacon', 'Acreage North']); + }); + + test('a hop hash matches when the name does not', () { + expect(matchesContactQuery(contacts[4], '6060'), isTrue); + expect(matchesContactQuery(contacts[4], '60'), isTrue); + expect(matchesContactQuery(contacts[4], '6060abcd'), isTrue); + expect(matchesContactQuery(contacts[4], '6061'), isFalse); + expect(_ranked(contacts, '6060'), ['6060 Hub', 'Node 6060', 'CR1']); + }); + + test('hash search accepts 0x, spaces, and angle brackets', () { + expect(_ranked(contacts, '0x6060'), ['CR1']); + expect(_ranked(contacts, '60 60'), ['CR1']); + expect(_ranked(contacts, '<6060>'), ['CR1']); + }); + + test('a single hex digit does not match every key', () { + expect(matchesContactQuery(contacts[4], '6'), isFalse); + }); + + test('an empty query matches every contact and keeps the tie-break', () { + final timed = [ + _contact('B', [0x01], lastSeen: DateTime.utc(2024, 1, 2)), + _contact('A', [0x02], lastSeen: DateTime.utc(2024, 1, 3)), + ]; + timed.sort( + (a, b) => compareContactQueryRank( + a, + b, + '', + (a, b) => b.lastSeen.compareTo(a.lastSeen), + ), + ); + expect(timed.map((c) => c.name), ['A', 'B']); + }); + + test('tie-break applies inside a rank, not across ranks', () { + final olderPrefix = _contact('Acre Older', [ + 0x01, + ], lastSeen: DateTime.utc(2020)); + final newerSubstring = _contact('My Acre', [ + 0x02, + ], lastSeen: DateTime.utc(2024)); + final ranked = [newerSubstring, olderPrefix] + ..sort( + (a, b) => compareContactQueryRank( + a, + b, + 'acre', + (a, b) => b.lastSeen.compareTo(a.lastSeen), + ), + ); + expect(ranked.map((c) => c.name), ['Acre Older', 'My Acre']); + }); +} diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart new file mode 100644 index 00000000..79ecf6af --- /dev/null +++ b/test/widgets/path_editor_sheet_test.dart @@ -0,0 +1,199 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/widgets/path_editor_sheet.dart'; + +Contact _repeater(String name, List prefix) { + final key = Uint8List(32); + for (var i = 0; i < prefix.length; i++) { + key[i] = prefix[i]; + } + return Contact( + publicKey: key, + name: name, + type: advTypeRepeater, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); +} + +final _contacts = [ + _repeater('100 Acre', [0x11, 0x22]), + _repeater('Acreage North', [0x33, 0x44]), + _repeater('My Acre Site', [0x55, 0x66]), + _repeater('2E0HQR-R', [0x2E, 0x0A]), + _repeater('CR1', [0x60, 0x60]), + for (var i = 0; i < 24; i++) _repeater('Repeater $i', [0xA0, i]), +]; + +Future _pumpSheet( + WidgetTester tester, { + Size size = const Size(400, 700), + double keyboard = 0, + List initialPath = const [], +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: MediaQuery( + data: MediaQueryData( + size: size, + viewInsets: EdgeInsets.only(bottom: keyboard), + ), + child: Scaffold( + body: SizedBox( + width: size.width, + height: size.height - keyboard, + child: PathEditorSheet( + availableContacts: _contacts, + initialPath: initialPath, + pathHashByteWidth: 2, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +List _repeaterNames(WidgetTester tester) { + return tester + .widgetList( + find.descendant( + of: find.byKey(const Key('path-editor-repeater-list')), + matching: find.byType(Text), + ), + ) + .map((text) => text.data) + .whereType() + .where((text) => !text.contains('•')) + .toList(); +} + +void main() { + testWidgets('prefix matches are listed before other substring matches', ( + tester, + ) async { + await _pumpSheet(tester); + await tester.enterText( + find.byKey(const Key('path-editor-search-field')), + 'acre', + ); + await tester.pumpAndSettle(); + + final visible = _repeaterNames(tester); + expect(visible.first, 'Acreage North'); + expect(visible[1], '100 Acre'); + await tester.scrollUntilVisible( + find.text('My Acre Site'), + 80, + scrollable: find.descendant( + of: find.byKey(const Key('path-editor-repeater-list')), + matching: find.byType(Scrollable), + ), + ); + expect(find.text('My Acre Site'), findsOneWidget); + }); + + testWidgets('search matches a hop hash the name does not contain', ( + tester, + ) async { + await _pumpSheet(tester); + await tester.enterText( + find.byKey(const Key('path-editor-search-field')), + '6060', + ); + await tester.pumpAndSettle(); + + expect(find.text('No repeaters or room servers found.'), findsNothing); + expect(_repeaterNames(tester), ['CR1']); + }); + + testWidgets('hex entry is reachable without scrolling the repeater list', ( + tester, + ) async { + await _pumpSheet(tester, size: const Size(400, 900)); + expect( + find.byKey(const Key('path-editor-hex-field')).hitTestable(), + findsOneWidget, + ); + expect(find.text('Hex prefixes'), findsOneWidget); + expect( + find.text('4 hex characters per hop, separated by commas'), + findsOneWidget, + ); + }); + + testWidgets('an added hop stays fully visible with the keyboard open', ( + tester, + ) async { + await _pumpSheet( + tester, + size: const Size(390, 640), + keyboard: 320, + initialPath: [0x60, 0x60], + ); + + final tile = find.ancestor( + of: find.byIcon(Icons.remove_circle_outline), + matching: find.byType(ListTile), + ); + expect(tile.hitTestable(), findsOneWidget); + final title = tester.getRect(find.text('Build Path')); + final hopRect = tester.getRect(tile); + final sheet = tester.getRect(find.byType(PathEditorSheet)); + expect(hopRect.top, greaterThanOrEqualTo(title.bottom)); + expect(hopRect.bottom, lessThanOrEqualTo(sheet.bottom)); + expect(hopRect.height, greaterThanOrEqualTo(48)); + expect(find.text('CR1').hitTestable(), findsWidgets); + expect(find.text('6060').hitTestable(), findsWidgets); + expect( + find.byKey(const Key('path-editor-hex-field')).hitTestable(), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('action buttons stay below the repeater list on a short sheet', ( + tester, + ) async { + await _pumpSheet( + tester, + size: const Size(400, 560), + initialPath: [0x60, 0x60, 0x11, 0x22], + ); + + expect(tester.takeException(), isNull); + final button = tester.getRect(find.text('Use this path')); + final list = tester.getRect( + find.byKey(const Key('path-editor-repeater-list')), + ); + expect(button.top, greaterThanOrEqualTo(list.bottom - 1)); + }); + + testWidgets('tapping a repeater adds a visible hop', (tester) async { + await _pumpSheet(tester); + await tester.enterText( + find.byKey(const Key('path-editor-search-field')), + '6060', + ); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(ListTile, 'CR1')); + await tester.pumpAndSettle(); + + expect(find.text('1 of 64 hops'), findsOneWidget); + expect(find.byIcon(Icons.remove_circle_outline), findsOneWidget); + expect(find.text('CR1').hitTestable(), findsWidgets); + }); +} From 3e1c71162de4a0667fbaea8246c030f4d4c64a7f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 21:48:17 +0000 Subject: [PATCH 03/50] Shrink the path hop list when hex validation grows An invalid hex path adds error lines under the field. The hop viewport now gives that space back, and a long error scrolls inside its own box instead of overflowing the sheet. Co-authored-by: zjs81 --- lib/widgets/path_editor_sheet.dart | 337 ++++++++++++++--------- test/widgets/path_editor_sheet_test.dart | 26 ++ 2 files changed, 234 insertions(+), 129 deletions(-) diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 73a34b31..1a57678e 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -349,23 +349,59 @@ class _PathEditorSheetState extends State { ); } - double _hopViewportHeight(double maxHeight, bool tight) { - if (_hops.isEmpty) return 0; + /// Heights for the hop list, hex field, and search field inside the + /// measured band between the title and the action buttons. + /// + /// An invalid hex path grows the error text. That growth comes out of the + /// hop viewport first, keeping one row when it fits, and the error itself + /// scrolls inside its own box instead of overflowing the sheet. + ({double hop, double hex, double search}) _middleBudget( + double space, + bool compact, + ) { final scaler = MediaQuery.textScalerOf(context); - final rowExtent = tight - ? scaler.scale(56).clamp(56.0, 80.0) - : scaler.scale(76).clamp(72.0, 132.0); - final visibleRows = math.min(_hops.length, tight ? 2 : 3); - final wanted = visibleRows * rowExtent + 4; - // Header, hex field, search field, and the action row stay on screen. - // The hop viewport takes what is left, and never pushes the buttons - // up over the repeater list. - final chrome = tight ? 210.0 : 430.0; - final available = maxHeight - chrome; - if (available >= rowExtent) { - return math.min(wanted, available); + final row = compact + ? scaler.scale(56).clamp(56.0, 96.0) + : scaler.scale(76).clamp(72.0, 140.0); + final gaps = compact ? 16.0 : 40.0; + final searchH = scaler.scale(compact ? 48 : 56) + 20; + final baseHex = scaler.scale(compact ? 48 : 64) + (compact ? 16 : 44); + final errorExtra = _hexError == null + ? 0.0 + : scaler.scale(compact ? 36 : 48); + final wantedHop = _hops.isEmpty + ? math.min(scaler.scale(compact ? 64 : 80), 140.0) + : math.min(_hops.length, compact ? 2 : 3) * row + 4; + final minHop = _hops.isEmpty + ? 0.0 + : math.min(row, math.max(0.0, space - gaps)); + + var hopH = wantedHop; + var hexH = baseHex + errorExtra; + final used = hopH + hexH + searchH + gaps; + if (used > space) { + var overflow = used - space; + final hopCut = math.min(overflow, math.max(0.0, hopH - minHop)); + hopH -= hopCut; + overflow -= hopCut; + if (overflow > 0) { + final hexFloor = math.min( + baseHex, + math.max(0.0, space - searchH - gaps - hopH), + ); + final hexCut = math.min(overflow, math.max(0.0, hexH - hexFloor)); + hexH -= hexCut; + overflow -= hexCut; + } + if (overflow > 0) { + hopH = math.max(0.0, hopH - overflow); + } } - return math.max(0.0, available); + return ( + hop: math.max(0.0, hopH), + hex: math.max(0.0, hexH), + search: searchH, + ); } @override @@ -383,7 +419,6 @@ class _PathEditorSheetState extends State { // Phone sheets and a keyboard-shrunk window use the shorter hop rows // so the action buttons stay below the repeater list. final compact = maxHeight < 680; - final hopHeight = _hopViewportHeight(maxHeight, compact); return Column( children: [ @@ -422,123 +457,167 @@ class _PathEditorSheetState extends State { ], ), ), - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 4 : 10, 16, 0), - child: DecoratedBox( - decoration: BoxDecoration( - color: scheme.surfaceContainerLow, - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: scheme.outlineVariant), - ), - child: _hops.isEmpty - ? Padding( - padding: const EdgeInsets.all(12), - child: Text( - l10n.pathEditor_noHops, - style: theme.textTheme.bodyMedium?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ) - : SizedBox( - height: hopHeight, - child: ReorderableListView.builder( - scrollController: _hopScroll, - buildDefaultDragHandles: false, - padding: EdgeInsets.symmetric( - vertical: compact ? 0 : 4, - ), - itemCount: _hops.length, - onReorderItem: _reorderHop, - itemBuilder: (context, index) => - _hopTile(context, index, singleLine: compact), - ), - ), - ), - ), - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 6 : 16, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (!compact) ...[ - Text( - l10n.pathEditor_advancedHex, - style: theme.textTheme.titleSmall, - ), - const SizedBox(height: 8), - ], - TextField( - key: const Key('path-editor-hex-field'), - controller: _hexController, - onChanged: _onHexChanged, - textCapitalization: TextCapitalization.characters, - style: MeshTheme.mono(fontSize: 14), - scrollPadding: EdgeInsets.zero, - decoration: InputDecoration( - labelText: l10n.pathEditor_hexLabel, - helperText: compact || _hexError != null - ? null - : l10n.pathEditor_hexHelper(_hashChars), - helperMaxLines: 3, - errorText: _hexError, - errorMaxLines: 3, - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ], - ), - ), - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 6 : 14, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (!compact) ...[ - Text( - l10n.pathEditor_addHops, - style: theme.textTheme.titleSmall, - ), - const SizedBox(height: 8), - ], - TextField( - key: const Key('path-editor-search-field'), - onChanged: (value) => setState(() => _search = value), - scrollPadding: EdgeInsets.zero, - decoration: InputDecoration( - labelText: l10n.pathEditor_searchRepeaters, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ], - ), - ), Expanded( - child: repeaters.isEmpty - ? Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), - child: Align( - alignment: Alignment.topLeft, - child: Text( - l10n.path_noRepeatersFound, - style: theme.textTheme.bodyMedium?.copyWith( - color: scheme.onSurfaceVariant, + child: LayoutBuilder( + builder: (context, inner) { + final budget = _middleBudget(inner.maxHeight, compact); + return Column( + children: [ + SizedBox( + height: budget.hop, + child: budget.hop < 8 + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.fromLTRB( + 16, + 4, + 16, + 0, + ), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular( + MeshRadii.md, + ), + border: Border.all( + color: scheme.outlineVariant, + ), + ), + child: _hops.isEmpty + ? SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: Text( + l10n.pathEditor_noHops, + style: theme.textTheme.bodyMedium + ?.copyWith( + color: + scheme.onSurfaceVariant, + ), + ), + ) + : ReorderableListView.builder( + scrollController: _hopScroll, + buildDefaultDragHandles: false, + padding: EdgeInsets.symmetric( + vertical: compact ? 0 : 4, + ), + itemCount: _hops.length, + onReorderItem: _reorderHop, + itemBuilder: (context, index) => + _hopTile( + context, + index, + singleLine: compact, + ), + ), + ), + ), + ), + SizedBox( + height: budget.hex, + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 6 : 12, + 16, + 0, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!compact) ...[ + Text( + l10n.pathEditor_advancedHex, + style: theme.textTheme.titleSmall, + ), + const SizedBox(height: 8), + ], + TextField( + key: const Key('path-editor-hex-field'), + controller: _hexController, + onChanged: _onHexChanged, + textCapitalization: + TextCapitalization.characters, + style: MeshTheme.mono(fontSize: 14), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_hexLabel, + helperText: compact || _hexError != null + ? null + : l10n.pathEditor_hexHelper(_hashChars), + helperMaxLines: 3, + errorText: _hexError, + errorMaxLines: compact ? 4 : 3, + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], ), ), ), - ) - : ListView.builder( - key: const Key('path-editor-repeater-list'), - keyboardDismissBehavior: - ScrollViewKeyboardDismissBehavior.onDrag, - padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), - itemCount: repeaters.length, - itemBuilder: (context, index) => - _repeaterTile(context, repeaters[index]), - ), + SizedBox( + height: budget.search, + child: Padding( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 6 : 12, + 16, + 0, + ), + child: TextField( + key: const Key('path-editor-search-field'), + onChanged: (value) => + setState(() => _search = value), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_searchRepeaters, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ), + ), + Expanded( + child: repeaters.isEmpty + ? Padding( + padding: const EdgeInsets.fromLTRB( + 16, + 12, + 16, + 8, + ), + child: Align( + alignment: Alignment.topLeft, + child: Text( + l10n.path_noRepeatersFound, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ) + : ListView.builder( + key: const Key('path-editor-repeater-list'), + keyboardDismissBehavior: + ScrollViewKeyboardDismissBehavior.onDrag, + padding: const EdgeInsets.fromLTRB( + 16, + 8, + 16, + 8, + ), + itemCount: repeaters.length, + itemBuilder: (context, index) => + _repeaterTile(context, repeaters[index]), + ), + ), + ], + ); + }, + ), ), SafeArea( top: false, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index 79ecf6af..972b0562 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -165,6 +165,32 @@ void main() { expect(tester.takeException(), isNull); }); + testWidgets('an invalid hex path does not overflow a keyboard-height sheet', ( + tester, + ) async { + await _pumpSheet( + tester, + size: const Size(390, 640), + keyboard: 320, + initialPath: [0x60, 0x60, 0x11, 0x22], + ); + await tester.enterText( + find.byKey(const Key('path-editor-hex-field')), + 'ZZ', + ); + await tester.pumpAndSettle(); + + expect(find.textContaining('Invalid'), findsOneWidget); + expect(tester.takeException(), isNull); + expect( + find.byIcon(Icons.remove_circle_outline).hitTestable(), + findsWidgets, + ); + final button = tester.getRect(find.text('Use this path')); + final sheet = tester.getRect(find.byType(PathEditorSheet)); + expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); + }); + testWidgets('action buttons stay below the repeater list on a short sheet', ( tester, ) async { From c4675d810ed163cbebec7e3831fa5d7295d24c90 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 22:30:35 +0000 Subject: [PATCH 04/50] Seat the path sheet header with the other sheets The sheet background was taller than its content, leaving an empty band above the drag handle. Use the shared sheet header, and rank the share sheet's own contact with the same name and hash matcher. Co-authored-by: zjs81 --- documentation/design.md | 2 +- lib/utils/contact_search.dart | 41 ++++++++- lib/widgets/path_editor_sheet.dart | 68 +++++---------- lib/widgets/share_contact_sheet.dart | 102 +++++++++++++++-------- test/utils/contact_search_test.dart | 39 +++++++++ test/widgets/path_editor_sheet_test.dart | 40 +++++++++ 6 files changed, 203 insertions(+), 89 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index dee9c2ce..85ade038 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -165,7 +165,7 @@ Rules for new UI: 3. **Forms with sections, live remote values, or anything that needs Save/Discard → page.** Guard unsaved changes with `PopScope` and a discard dialog, as `repeater_settings_screen.dart` does. 4. Never stack a dialog on a sheet on a dialog. Close the sheet first, or move the flow to a page. -The manual path editor (`path_editor_sheet.dart`) is a fixed-height sheet, not a draggable one. The hop list and the hex path field stay pinned above a scrolling repeater list, including while the keyboard is open. The sheet uses the full height above the keyboard so a newly added hop is not scrolled under the title. +The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that header, including while the keyboard is open. ## 7. App bars diff --git a/lib/utils/contact_search.dart b/lib/utils/contact_search.dart index eaad99c2..9101bc9a 100644 --- a/lib/utils/contact_search.dart +++ b/lib/utils/contact_search.dart @@ -9,19 +9,54 @@ enum ContactQueryRank { namePrefix, nameContains, keyPrefix } /// /// Names that start with the query come before other substring matches. /// A public-key / hop-hash prefix matches only when the name does not. +/// Name-only half of [rankContactQuery], for a label that is not itself a +/// contact (for example the "my contact" alias on the share sheet). +ContactQueryRank? rankNameQuery(String name, String query) { + final normalized = query.trim().toLowerCase(); + if (normalized.isEmpty) return ContactQueryRank.namePrefix; + final label = name.toLowerCase(); + if (label.startsWith(normalized)) return ContactQueryRank.namePrefix; + if (label.contains(normalized)) return ContactQueryRank.nameContains; + return null; +} + ContactQueryRank? rankContactQuery(Contact contact, String query) { final normalized = query.trim().toLowerCase(); if (normalized.isEmpty) return ContactQueryRank.namePrefix; - final name = contact.name.toLowerCase(); - if (name.startsWith(normalized)) return ContactQueryRank.namePrefix; - if (name.contains(normalized)) return ContactQueryRank.nameContains; + final byName = rankNameQuery(contact.name, normalized); + if (byName != null) return byName; if (_publicKeyPrefixMatches(contact, normalized)) { return ContactQueryRank.keyPrefix; } return null; } +/// Whether [name], any [aliases], or [publicKeyHex] matches [query] with the +/// same prefix, substring, then hash order as [rankContactQuery]. +ContactQueryRank? rankLabeledKeyQuery({ + required String name, + required String publicKeyHex, + required String query, + List aliases = const [], +}) { + final normalized = query.trim().toLowerCase(); + if (normalized.isEmpty) return ContactQueryRank.namePrefix; + ContactQueryRank? best = rankNameQuery(name, normalized); + for (final alias in aliases) { + final rank = rankNameQuery(alias, normalized); + if (rank != null && (best == null || rank.index < best.index)) { + best = rank; + } + } + if (best != null) return best; + final hexPrefix = _extractHexPrefix(normalized); + if (hexPrefix != null && publicKeyHex.toLowerCase().startsWith(hexPrefix)) { + return ContactQueryRank.keyPrefix; + } + return null; +} + bool matchesContactQuery(Contact contact, String query) { return rankContactQuery(contact, query) != null; } diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 1a57678e..cbed8317 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -11,6 +11,7 @@ import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../theme/mesh_theme.dart'; import '../utils/contact_search.dart'; +import 'mesh_ui.dart'; class PathEditorSheet extends StatefulWidget { final List availableContacts; @@ -30,27 +31,26 @@ class PathEditorSheet extends StatefulWidget { List initialPath = const [], int pathHashByteWidth = pathHashSize, }) { - return showModalBottomSheet( - context: context, - isScrollControlled: true, - useSafeArea: true, + // Same container as the other sheets: safe area on the top and sides, + // keyboard inset on the bottom, and the header at the top of the sheet. + // A fraction inside an expanding align left an empty band above the handle. + return showMeshSheet( + context, builder: (context) { - final keyboard = MediaQuery.viewInsetsOf(context).bottom; - return Padding( - padding: EdgeInsets.only(bottom: keyboard), - child: Align( - alignment: Alignment.bottomCenter, - child: FractionallySizedBox( - // The keyboard already shrinks the sheet. Use the full band - // above it so the hop list is not clipped under the title. - heightFactor: keyboard > 0 ? 1 : 0.92, + return LayoutBuilder( + builder: (context, constraints) { + final height = constraints.maxHeight.isFinite + ? constraints.maxHeight + : MediaQuery.sizeOf(context).height; + return SizedBox( + height: height, child: PathEditorSheet( availableContacts: availableContacts, initialPath: initialPath, pathHashByteWidth: pathHashByteWidth, ), - ), - ), + ); + }, ); }, ); @@ -422,39 +422,11 @@ class _PathEditorSheetState extends State { return Column( children: [ - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 6 : 10, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Center( - child: Container( - width: 36, - height: 4, - decoration: BoxDecoration( - color: scheme.outline, - borderRadius: BorderRadius.circular(2), - ), - ), - ), - SizedBox(height: compact ? 4 : 12), - Text( - l10n.pathEditor_title, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w700, - letterSpacing: -0.2, - ), - ), - Semantics( - liveRegion: true, - child: Text( - l10n.pathEditor_hopCounter(_hops.length), - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ), - ], + Semantics( + liveRegion: true, + child: BottomSheetHeader( + title: l10n.pathEditor_title, + subtitle: l10n.pathEditor_hopCounter(_hops.length), ), ), Expanded( diff --git a/lib/widgets/share_contact_sheet.dart b/lib/widgets/share_contact_sheet.dart index c38c48d1..88828c11 100644 --- a/lib/widgets/share_contact_sheet.dart +++ b/lib/widgets/share_contact_sheet.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; import '../helpers/contact_share_message.dart'; import '../l10n/contact_localization.dart'; import '../l10n/l10n.dart'; @@ -56,12 +57,14 @@ class _ShareContactSheetState extends State<_ShareContactSheet> { .toList() ..sort((a, b) => compareContactQueryRank(a, b, needle)); final selfName = connector.selfName ?? ''; - final showSelf = - selfKey != null && - selfKey.length == 32 && - (needle.isEmpty || - selfName.toLowerCase().contains(needle) || - l10n.contactShare_myContact.toLowerCase().contains(needle)); + final selfRank = selfKey != null && selfKey.length == 32 + ? rankLabeledKeyQuery( + name: selfName.isEmpty ? l10n.contactShare_myContact : selfName, + publicKeyHex: pubKeyToHex(selfKey), + query: needle, + aliases: [l10n.contactShare_myContact], + ) + : null; return SafeArea( child: ConstrainedBox( @@ -83,43 +86,68 @@ class _ShareContactSheetState extends State<_ShareContactSheet> { onChanged: (value) => setState(() => _query = value), ), ), - Flexible( - child: ListView( - shrinkWrap: true, - children: [ - if (showSelf) - _tile( - context, - name: selfName.isEmpty - ? l10n.contactShare_myContact - : selfName, - subtitle: l10n.contactShare_myContact, - token: encodeContactShare( - publicKey: selfKey, - type: 1, - name: selfName, - ), - ), - for (final c in contacts) _contactTile(context, c), - if (!showSelf && contacts.isEmpty) - Padding( - padding: const EdgeInsets.all(24), - child: Center( - child: Text( - l10n.contactShare_noContacts, - style: const TextStyle(fontSize: 14), - ), - ), - ), - ], - ), - ), + Flexible(child: _shareList(context, contacts, selfRank)), ], ), ), ); } + Widget _shareList( + BuildContext context, + List contacts, + ContactQueryRank? selfRank, + ) { + final l10n = context.l10n; + final connector = widget.connector; + final selfKey = connector.selfPublicKey; + final selfName = connector.selfName ?? ''; + final rows = + <({int rank, String name, Widget tile})>[ + for (final contact in contacts) + ( + rank: rankContactQuery(contact, _query)?.index ?? 3, + name: contact.name.toLowerCase(), + tile: _contactTile(context, contact), + ), + if (selfRank != null && selfKey != null) + ( + rank: selfRank.index, + name: (selfName.isEmpty ? l10n.contactShare_myContact : selfName) + .toLowerCase(), + tile: _tile( + context, + name: selfName.isEmpty ? l10n.contactShare_myContact : selfName, + subtitle: l10n.contactShare_myContact, + token: encodeContactShare( + publicKey: selfKey, + type: 1, + name: selfName, + ), + ), + ), + ]..sort((a, b) { + final byRank = a.rank.compareTo(b.rank); + if (byRank != 0) return byRank; + return a.name.compareTo(b.name); + }); + if (rows.isEmpty) { + return Padding( + padding: const EdgeInsets.all(24), + child: Center( + child: Text( + l10n.contactShare_noContacts, + style: const TextStyle(fontSize: 14), + ), + ), + ); + } + return ListView( + shrinkWrap: true, + children: [for (final row in rows) row.tile], + ); + } + Widget _contactTile(BuildContext context, Contact c) { return _tile( context, diff --git a/test/utils/contact_search_test.dart b/test/utils/contact_search_test.dart index d2d1cff4..19937868 100644 --- a/test/utils/contact_search_test.dart +++ b/test/utils/contact_search_test.dart @@ -88,6 +88,45 @@ void main() { expect(timed.map((c) => c.name), ['A', 'B']); }); + test('a labeled key uses the same prefix, substring, then hash order', () { + expect( + rankLabeledKeyQuery( + name: 'Review Radio', + publicKeyHex: '6060abcd', + query: 'my', + aliases: ['My contact'], + ), + ContactQueryRank.namePrefix, + ); + expect( + rankLabeledKeyQuery( + name: 'Review Radio', + publicKeyHex: '6060abcd', + query: 'radio', + aliases: ['My contact'], + ), + ContactQueryRank.nameContains, + ); + expect( + rankLabeledKeyQuery( + name: 'Review Radio', + publicKeyHex: '6060abcd', + query: '6060', + aliases: ['My contact'], + ), + ContactQueryRank.keyPrefix, + ); + expect( + rankLabeledKeyQuery( + name: 'Review Radio', + publicKeyHex: '6060abcd', + query: 'zzzz', + aliases: ['My contact'], + ), + isNull, + ); + }); + test('tie-break applies inside a rank, not across ranks', () { final olderPrefix = _contact('Acre Older', [ 0x01, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index 972b0562..d98d3217 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -208,6 +208,46 @@ void main() { expect(button.top, greaterThanOrEqualTo(list.bottom - 1)); }); + testWidgets('the title sits at the top of the sheet', (tester) async { + tester.view.physicalSize = const Size(400, 800); + tester.view.devicePixelRatio = 1; + // A phone status bar. The sheet may pad for it, and must not add another + // empty band above the handle. + tester.view.padding = const FakeViewPadding(top: 47); + tester.view.viewPadding = const FakeViewPadding(top: 47); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPadding); + addTearDown(tester.view.resetViewPadding); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => PathEditorSheet.show( + context, + availableContacts: _contacts, + pathHashByteWidth: 2, + ), + child: const Text('open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + final sheetTop = tester.getTopLeft(find.byType(BottomSheet)).dy; + final titleTop = tester.getTopLeft(find.text('Build Path')).dy; + // Header only: 8px padding, a 4px handle, and a 10px gap. The status-bar + // inset stays outside the sheet, and there is no extra empty band. + expect(titleTop - sheetTop, inInclusiveRange(16, 36)); + }); + testWidgets('tapping a repeater adds a visible hop', (tester) async { await _pumpSheet(tester); await tester.enterText( From cd211da0efa739e45b860757cf066087469a0f44 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 22:53:06 +0000 Subject: [PATCH 05/50] Scroll the path sheet when the keyboard leaves no room A landscape keyboard can leave less than the search field under the header. The pinned column overflowed there, so that band now scrolls the hops, hex field, search field, and repeater list together. Co-authored-by: zjs81 --- documentation/design.md | 2 +- documentation/routing-paths.md | 2 +- lib/widgets/path_editor_sheet.dart | 455 +++++++++++++++-------- test/widgets/path_editor_sheet_test.dart | 88 +++++ 4 files changed, 388 insertions(+), 159 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index 85ade038..021a67e3 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -165,7 +165,7 @@ Rules for new UI: 3. **Forms with sections, live remote values, or anything that needs Save/Discard → page.** Guard unsaved changes with `PopScope` and a discard dialog, as `repeater_settings_screen.dart` does. 4. Never stack a dialog on a sheet on a dialog. Close the sheet first, or move the flow to a page. -The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that header, including while the keyboard is open. +The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that header, including while the keyboard is open. When the band under the header is shorter than the search field, as on a landscape phone with the keyboard open, those blocks and the repeater list scroll together instead of overflowing. ## 7. App bars diff --git a/documentation/routing-paths.md b/documentation/routing-paths.md index 90202fc4..e053e11b 100644 --- a/documentation/routing-paths.md +++ b/documentation/routing-paths.md @@ -64,6 +64,6 @@ Contacts/messages persist hop count, path bytes, and width. Legacy contact recor ## Building a path by hand -Chat → Routing → Manual opens the Build Path sheet. The hops you have added stay pinned at the top, including while the keyboard is open, and the one just added is highlighted. Under that list is the hex field, so a path can be typed without scrolling past every repeater. Search matches repeater and room names and hop hashes (the public-key prefix). Names that start with the query are listed before other substring matches, then hash-only matches. +Chat → Routing → Manual opens the Build Path sheet. The hops you have added stay pinned at the top, including while the keyboard is open, and the one just added is highlighted. Under that list is the hex field, so a path can be typed without scrolling past every repeater. On a very short sheet, such as landscape with the keyboard open, the hop list, hex field, search field, and repeater list scroll together so the search field stays reachable. Search matches repeater and room names and hop hashes (the public-key prefix). Names that start with the query are listed before other substring matches, then hash-only matches. For message-path actions, trace maps, and retry behavior, see [chat](chat-and-messaging.md), [channels](channels.md), and [map](map-and-location.md). diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index cbed8317..6cc623df 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -355,7 +355,12 @@ class _PathEditorSheetState extends State { /// An invalid hex path grows the error text. That growth comes out of the /// hop viewport first, keeping one row when it fits, and the error itself /// scrolls inside its own box instead of overflowing the sheet. - ({double hop, double hex, double search}) _middleBudget( + /// + /// [scroll] is set when that band is shorter than the search field, which + /// happens when a landscape keyboard leaves only the header and the action + /// buttons. The pinned column would overflow, so the caller lays the same + /// blocks out in one scroll view instead. + ({double hop, double hex, double search, bool scroll}) _middleBudget( double space, bool compact, ) { @@ -372,12 +377,13 @@ class _PathEditorSheetState extends State { final wantedHop = _hops.isEmpty ? math.min(scaler.scale(compact ? 64 : 80), 140.0) : math.min(_hops.length, compact ? 2 : 3) * row + 4; + final wantedHex = baseHex + errorExtra; final minHop = _hops.isEmpty ? 0.0 : math.min(row, math.max(0.0, space - gaps)); var hopH = wantedHop; - var hexH = baseHex + errorExtra; + var hexH = wantedHex; final used = hopH + hexH + searchH + gaps; if (used > space) { var overflow = used - space; @@ -397,18 +403,294 @@ class _PathEditorSheetState extends State { hopH = math.max(0.0, hopH - overflow); } } + hopH = math.max(0.0, hopH); + hexH = math.max(0.0, hexH); + // The search field stays at its full height in the pinned column. When + // the band cannot hold it, scrolling is the only way to reach it and the + // repeater list. + final scroll = hopH + hexH + searchH > space; return ( - hop: math.max(0.0, hopH), - hex: math.max(0.0, hexH), + hop: scroll ? wantedHop : hopH, + hex: scroll ? wantedHex : hexH, search: searchH, + scroll: scroll, + ); + } + + Widget _hopViewport(bool compact, double height) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return SizedBox( + height: height, + child: height < 8 + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 0), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: scheme.outlineVariant), + ), + child: _hops.isEmpty + ? SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: Text( + l10n.pathEditor_noHops, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ) + : ReorderableListView.builder( + scrollController: _hopScroll, + buildDefaultDragHandles: false, + padding: EdgeInsets.symmetric( + vertical: compact ? 0 : 4, + ), + itemCount: _hops.length, + onReorderItem: _reorderHop, + itemBuilder: (context, index) => + _hopTile(context, index, singleLine: compact), + ), + ), + ), + ); + } + + Widget _hexViewport(bool compact, double height) { + final l10n = context.l10n; + final theme = Theme.of(context); + return SizedBox( + height: height, + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!compact) ...[ + Text( + l10n.pathEditor_advancedHex, + style: theme.textTheme.titleSmall, + ), + const SizedBox(height: 8), + ], + TextField( + key: const Key('path-editor-hex-field'), + controller: _hexController, + onChanged: _onHexChanged, + textCapitalization: TextCapitalization.characters, + style: MeshTheme.mono(fontSize: 14), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_hexLabel, + helperText: compact || _hexError != null + ? null + : l10n.pathEditor_hexHelper(_hashChars), + helperMaxLines: 3, + errorText: _hexError, + errorMaxLines: compact ? 4 : 3, + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], + ), + ), + ); + } + + Widget _searchViewport(bool compact, double height) { + final l10n = context.l10n; + return SizedBox( + height: height, + child: Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0), + child: TextField( + key: const Key('path-editor-search-field'), + onChanged: (value) => setState(() => _search = value), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_searchRepeaters, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ), + ); + } + + Widget _repeaterViewport(List repeaters) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + if (repeaters.isEmpty) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Align( + alignment: Alignment.topLeft, + child: Text( + l10n.path_noRepeatersFound, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ); + } + return ListView.builder( + key: const Key('path-editor-repeater-list'), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + itemCount: repeaters.length, + itemBuilder: (context, index) => _repeaterTile(context, repeaters[index]), + ); + } + + /// One scrollable for the hop list, hex field, search field, and repeaters. + /// + /// The blocks are intrinsic height with no nested scrolling, so a drag + /// anywhere in the band moves the search field and the repeater list into + /// view. The pinned layout keeps its own viewports. + Widget _scrollingMiddle({ + required bool compact, + required List repeaters, + }) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return CustomScrollView( + key: const Key('path-editor-scroll-fallback'), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + slivers: [ + SliverToBoxAdapter(child: _scrollHopBlock(compact)), + SliverToBoxAdapter(child: _scrollHexBlock(compact)), + SliverToBoxAdapter(child: _scrollSearchBlock(compact)), + if (repeaters.isEmpty) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Text( + l10n.path_noRepeatersFound, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ) + else + SliverPadding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + sliver: SliverList.builder( + key: const Key('path-editor-repeater-list'), + itemCount: repeaters.length, + itemBuilder: (context, index) => + _repeaterTile(context, repeaters[index]), + ), + ), + ], + ); + } + + Widget _scrollHopBlock(bool compact) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 0), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: scheme.outlineVariant), + ), + child: _hops.isEmpty + ? Padding( + padding: const EdgeInsets.all(12), + child: Text( + l10n.pathEditor_noHops, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ) + : ReorderableListView.builder( + scrollController: _hopScroll, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + buildDefaultDragHandles: false, + padding: EdgeInsets.symmetric(vertical: compact ? 0 : 4), + itemCount: _hops.length, + onReorderItem: _reorderHop, + itemBuilder: (context, index) => + _hopTile(context, index, singleLine: compact), + ), + ), + ); + } + + Widget _scrollHexBlock(bool compact) { + final l10n = context.l10n; + final theme = Theme.of(context); + return Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!compact) ...[ + Text( + l10n.pathEditor_advancedHex, + style: theme.textTheme.titleSmall, + ), + const SizedBox(height: 8), + ], + TextField( + key: const Key('path-editor-hex-field'), + controller: _hexController, + onChanged: _onHexChanged, + textCapitalization: TextCapitalization.characters, + style: MeshTheme.mono(fontSize: 14), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_hexLabel, + helperText: compact || _hexError != null + ? null + : l10n.pathEditor_hexHelper(_hashChars), + helperMaxLines: 3, + errorText: _hexError, + errorMaxLines: compact ? 4 : 3, + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], + ), + ); + } + + Widget _scrollSearchBlock(bool compact) { + final l10n = context.l10n; + return Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0), + child: TextField( + key: const Key('path-editor-search-field'), + onChanged: (value) => setState(() => _search = value), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_searchRepeaters, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: compact, + ), + ), ); } @override Widget build(BuildContext context) { final l10n = context.l10n; - final theme = Theme.of(context); - final scheme = theme.colorScheme; final repeaters = _repeaters; return LayoutBuilder( @@ -433,159 +715,18 @@ class _PathEditorSheetState extends State { child: LayoutBuilder( builder: (context, inner) { final budget = _middleBudget(inner.maxHeight, compact); + if (budget.scroll) { + return _scrollingMiddle( + compact: compact, + repeaters: repeaters, + ); + } return Column( children: [ - SizedBox( - height: budget.hop, - child: budget.hop < 8 - ? const SizedBox.shrink() - : Padding( - padding: const EdgeInsets.fromLTRB( - 16, - 4, - 16, - 0, - ), - child: DecoratedBox( - decoration: BoxDecoration( - color: scheme.surfaceContainerLow, - borderRadius: BorderRadius.circular( - MeshRadii.md, - ), - border: Border.all( - color: scheme.outlineVariant, - ), - ), - child: _hops.isEmpty - ? SingleChildScrollView( - padding: const EdgeInsets.all(12), - child: Text( - l10n.pathEditor_noHops, - style: theme.textTheme.bodyMedium - ?.copyWith( - color: - scheme.onSurfaceVariant, - ), - ), - ) - : ReorderableListView.builder( - scrollController: _hopScroll, - buildDefaultDragHandles: false, - padding: EdgeInsets.symmetric( - vertical: compact ? 0 : 4, - ), - itemCount: _hops.length, - onReorderItem: _reorderHop, - itemBuilder: (context, index) => - _hopTile( - context, - index, - singleLine: compact, - ), - ), - ), - ), - ), - SizedBox( - height: budget.hex, - child: SingleChildScrollView( - padding: EdgeInsets.fromLTRB( - 16, - compact ? 6 : 12, - 16, - 0, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (!compact) ...[ - Text( - l10n.pathEditor_advancedHex, - style: theme.textTheme.titleSmall, - ), - const SizedBox(height: 8), - ], - TextField( - key: const Key('path-editor-hex-field'), - controller: _hexController, - onChanged: _onHexChanged, - textCapitalization: - TextCapitalization.characters, - style: MeshTheme.mono(fontSize: 14), - scrollPadding: EdgeInsets.zero, - decoration: InputDecoration( - labelText: l10n.pathEditor_hexLabel, - helperText: compact || _hexError != null - ? null - : l10n.pathEditor_hexHelper(_hashChars), - helperMaxLines: 3, - errorText: _hexError, - errorMaxLines: compact ? 4 : 3, - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ], - ), - ), - ), - SizedBox( - height: budget.search, - child: Padding( - padding: EdgeInsets.fromLTRB( - 16, - compact ? 6 : 12, - 16, - 0, - ), - child: TextField( - key: const Key('path-editor-search-field'), - onChanged: (value) => - setState(() => _search = value), - scrollPadding: EdgeInsets.zero, - decoration: InputDecoration( - labelText: l10n.pathEditor_searchRepeaters, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ), - ), - Expanded( - child: repeaters.isEmpty - ? Padding( - padding: const EdgeInsets.fromLTRB( - 16, - 12, - 16, - 8, - ), - child: Align( - alignment: Alignment.topLeft, - child: Text( - l10n.path_noRepeatersFound, - style: theme.textTheme.bodyMedium?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ), - ) - : ListView.builder( - key: const Key('path-editor-repeater-list'), - keyboardDismissBehavior: - ScrollViewKeyboardDismissBehavior.onDrag, - padding: const EdgeInsets.fromLTRB( - 16, - 8, - 16, - 8, - ), - itemCount: repeaters.length, - itemBuilder: (context, index) => - _repeaterTile(context, repeaters[index]), - ), - ), + _hopViewport(compact, budget.hop), + _hexViewport(compact, budget.hex), + _searchViewport(compact, budget.search), + Expanded(child: _repeaterViewport(repeaters)), ], ); }, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index d98d3217..29aa1ee8 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -67,6 +67,29 @@ Future _pumpSheet( await tester.pumpAndSettle(); } +Future _revealInFallback( + WidgetTester tester, + Finder scrollable, + Finder target, +) async { + final state = tester.state(scrollable); + final view = tester.getRect( + find.byKey(const Key('path-editor-scroll-fallback')), + ); + for (var i = 0; i < 40; i++) { + final rect = tester.getRect(target); + if (rect.center.dy >= view.top && rect.center.dy <= view.bottom) return; + final next = (state.position.pixels + 48).clamp( + 0.0, + state.position.maxScrollExtent, + ); + expect(next, greaterThan(state.position.pixels)); + state.position.jumpTo(next); + await tester.pump(); + } + fail('Could not scroll $target into the path sheet'); +} + List _repeaterNames(WidgetTester tester) { return tester .widgetList( @@ -162,6 +185,7 @@ void main() { find.byKey(const Key('path-editor-hex-field')).hitTestable(), findsOneWidget, ); + expect(find.byKey(const Key('path-editor-scroll-fallback')), findsNothing); expect(tester.takeException(), isNull); }); @@ -191,6 +215,70 @@ void main() { expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); }); + testWidgets('a landscape keyboard sheet scrolls instead of overflowing', ( + tester, + ) async { + await _pumpSheet( + tester, + size: const Size(800, 180), + initialPath: [0x60, 0x60, 0x11, 0x22], + ); + + expect(tester.takeException(), isNull); + expect( + find.byKey(const Key('path-editor-scroll-fallback')), + findsOneWidget, + ); + // The hop list has its own scrollable. The fallback is the scrollable + // that also contains the hex field. + final scrollable = find.byElementPredicate((element) { + if (element.widget is! Scrollable) return false; + var hasHex = false; + void visit(Element node) { + node.visitChildren((child) { + if (child.widget.key == const Key('path-editor-hex-field')) { + hasHex = true; + } + visit(child); + }); + } + + visit(element); + return hasHex; + }); + await tester.scrollUntilVisible( + find.byKey(const Key('path-editor-hex-field')), + 40, + scrollable: scrollable, + ); + await tester.enterText( + find.byKey(const Key('path-editor-hex-field')), + 'ZZ', + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.textContaining('Invalid'), findsOneWidget); + + await _revealInFallback( + tester, + scrollable, + find.byKey(const Key('path-editor-search-field'), skipOffstage: false), + ); + expect( + find.byKey(const Key('path-editor-search-field')).hitTestable(), + findsOneWidget, + ); + await _revealInFallback( + tester, + scrollable, + find.text('Acreage North', skipOffstage: false), + ); + expect(find.text('Acreage North').hitTestable(), findsOneWidget); + final button = tester.getRect(find.text('Use this path')); + final sheet = tester.getRect(find.byType(PathEditorSheet)); + expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); + }); + testWidgets('action buttons stay below the repeater list on a short sheet', ( tester, ) async { From 52be39e4e8dfec479abdec79bb863e94fba5005e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 22:54:58 +0000 Subject: [PATCH 06/50] Document sheet layout and shared node search The design reference now says new sheets use the shared header flush with the top of the sheet, and that contact, repeater, room and user search share one prefix, substring, then hash ranking. Co-authored-by: zjs81 --- documentation/design.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index 021a67e3..d7905230 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -165,9 +165,17 @@ Rules for new UI: 3. **Forms with sections, live remote values, or anything that needs Save/Discard → page.** Guard unsaved changes with `PopScope` and a discard dialog, as `repeater_settings_screen.dart` does. 4. Never stack a dialog on a sheet on a dialog. Close the sheet first, or move the flow to a page. -The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that header, including while the keyboard is open. When the band under the header is shorter than the search field, as on a landscape phone with the keyboard open, those blocks and the repeater list scroll together instead of overflowing. +**Sheet layout.** `showMeshSheet` is the sheet: safe area on the top and sides, and the keyboard or navigation-bar inset on the bottom. Start the content with `BottomSheetHeader`. That widget is the handle and the title row (padding 20, 8, 8, 4 and a 36×4 handle, section 4). Do not add space above it, draw a second handle, or size the sheet with a fraction inside an `Align`; that leaves an empty band over the handle. The status-bar inset stays outside the sheet. -## 7. App bars +The manual path editor (`path_editor_sheet.dart`) uses that layout. The hop list and the hex path field stay pinned under the header, including while the keyboard is open. When the band under the header is shorter than the search field, as on a landscape phone with the keyboard open, those blocks and the repeater list scroll together instead of overflowing. + +## 7. Node search + +Contact, repeater, room and user search all use `lib/utils/contact_search.dart`. Sort with `compareContactQueryRank`: names that start with the query, then other substring matches, then a public-key / hop-hash prefix. Use `rankLabeledKeyQuery` for a label that is not itself a contact, such as "my contact" on the share sheet. Do not filter with a separate name `contains`. + +That is the Contacts list and its group member picker, Discovery, Map node search, Map "send to contact", Share contact, and the Build Path repeater and room list. Channel names, chat messages, repeater CLI commands and the path-trace hex field are not this search. The map key-prefix setting is a filter, not a ranked search. + +## 8. App bars - Title: a plain localized string, ellipsized on one line. Use `AppBarTitle` on top-level and settings screens; it adds the connected node name as a subtitle and battery/SNR indicators when there is room, dropping them in that order on narrow widths. Use `AdaptiveAppBarTitle` for a plain one-line title. - Centre the title (`centerTitle: true`, `AGENTS.md`); 31 screens set it explicitly because the theme default is `false`. Chat screens (`chat_screen.dart`, `channel_chat_screen.dart`) deliberately use `centerTitle: false` for their two-line name + route title. @@ -176,7 +184,7 @@ The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `Bott - Search: tapping search swaps the title for the field and hides all actions (`actions: _searching ? null : [...]`). The leading back arrow and the system back gesture close the search (`PopScope(canPop: !_searching)`) instead of leaving the screen. - Long operations: show progress as the app bar `bottom` (`SyncProgressAppBarBottom`, or a 4px `LinearProgressIndicator` for Refresh all in `repeater_settings_screen.dart`). -## 8. States +## 9. States | State | How to show it | |---|---| @@ -199,7 +207,7 @@ The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `Bott Follow the same pattern for any new remote-value screen. -## 9. Text and localization +## 10. Text and localization - All user-facing strings go through `context.l10n` (`lib/l10n/l10n.dart`). Add keys to `lib/l10n/app_en.arb` first. No string literals in widgets, including fallbacks. - Keep strings short: labels are a few words, subtitles one sentence. @@ -213,7 +221,7 @@ Follow the same pattern for any new remote-value screen. - Upper-casing is done in code (`SectionHeader`, `StatTile`, `RouteChip`); keep the ARB strings in normal case. - Test with a long locale (German, Portuguese) and a large system font (at least 1.3×, ideally 2.0×) on a narrow phone (320dp). `test/screens/small_screen_layout_test.dart` checks many screens at 320×568 at 1.0, 1.3 and 2.0× in English; add new screens to it. -## 10. Checklist for a UI change +## 11. Checklist for a UI change - [ ] Colours from `colorScheme` or theme extensions; no raw `Colors.*` or `MeshPalette.ink/bg/line` in chrome. - [ ] Text styles from `textTheme` or `MeshTheme.mono`; nothing below 12. @@ -221,13 +229,14 @@ Follow the same pattern for any new remote-value screen. - [ ] Popup menu rows use `MeshMenuItemRow`; segmented buttons use `MeshSegmentLabel`; destructive menu items last, in `scheme.error`. - [ ] Every `IconButton` and FAB has a localized `tooltip`. - [ ] Tap targets at least 48×48. -- [ ] Right container: dialog for confirm/short input, `showMeshSheet` + `BottomSheetHeader` for choices and item actions, page for forms. +- [ ] Right container: dialog for confirm/short input, `showMeshSheet` + `BottomSheetHeader` for choices and item actions, page for forms. No gap above the sheet handle. +- [ ] Contact, repeater, room and user search uses `compareContactQueryRank`: prefix, then substring, then hop hash. - [ ] Loading, empty, error, offline and unknown-value states handled. - [ ] All strings in `app_en.arb`; checked in German or Portuguese at 1.3× and 2.0× on a narrow screen. - [ ] Light, dark and one custom theme checked. - [ ] This page updated if you introduced or changed a pattern. -## 11. Known inconsistencies +## 12. Known inconsistencies The current code does not yet follow this page everywhere: From 92dadb0d3a6b2f2d2161f983c9268358e64a068b Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 07/50] Fix stale map labels, avatar initials and offline bubble widths - Map node labels follow light/dark theme changes. - Avatar initials use only letters and digits; hop avatars fall back to the hash prefix. - Incoming channel bubbles are the same width connected and offline. - Day separators wrap instead of overflowing with large text. --- documentation/design.md | 2 +- lib/screens/channel_chat_screen.dart | 4 +- lib/screens/channel_message_path_screen.dart | 28 +- lib/screens/map_screen.dart | 9 +- lib/utils/platform_info.dart | 7 +- lib/widgets/chat_day_separator.dart | 41 ++- lib/widgets/contact_visuals.dart | 35 ++ lib/widgets/mesh_ui.dart | 25 +- .../channel_message_path_avatar_test.dart | 84 +++++ test/screens/chat_bubble_width_test.dart | 321 ++++++++++++++++++ test/screens/map_rebuild_scope_test.dart | 61 +++- test/widgets/avatar_initials_test.dart | 73 ++++ 12 files changed, 642 insertions(+), 48 deletions(-) create mode 100644 test/screens/channel_message_path_avatar_test.dart create mode 100644 test/screens/chat_bubble_width_test.dart create mode 100644 test/widgets/avatar_initials_test.dart diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..8262ed87 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -102,7 +102,7 @@ Minimum sizes: no hard-coded `fontSize` below 12 exists in `lib/screens` or `lib | Sheet header | padding 20, 8, 8, 4 (LTRB), 36×4 drag handle | `BottomSheetHeader` | | Radii | `MeshRadii.xs` 6, `sm` 10, `md` 14 (cards, inputs, menus, snackbars, list tiles), `lg` 18 (sheets, dialogs), `xl` 24, `pill` 999 (buttons, chips, FAB) | `MeshRadii` | | Default icon size | 22 | `iconTheme` | -| Avatar | 40 | `AvatarCircle` | +| Avatar | 40; initials from letters and digits only (`avatarInitials`), else a person icon. Pass a hop's hex prefix, not a "(AB) Name" label | `AvatarCircle` | | List bottom padding under a FAB | 88 | `channels_screen.dart` | Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small action buttons, 18 for inline refresh icons and spinners. Keep tappable icons at 20 or more. diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 67a397ab..618602a4 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -3958,8 +3958,10 @@ class _SwipeReplyBubbleState extends State<_SwipeReplyBubble> { onPointerMove: _handleSwipePointerMove, onPointerUp: (event) => _handleSwipePointerUp(event.position), onPointerCancel: (_) => _resetSwipe(), + // Same insets as the plain row in _buildMessageBubble, so a bubble is + // as wide whether or not it can be swiped (offline, desktop, outgoing). child: Padding( - padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8), + padding: const EdgeInsets.symmetric(vertical: 3), child: Stack( alignment: Alignment.center, children: [ diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index e99917a1..bdd415ba 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -21,6 +21,7 @@ import '../models/display_path.dart'; import '../models/path_playback.dart'; import '../theme/mesh_theme.dart'; import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/contact_visuals.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/path_map_scaffold.dart'; import '../widgets/path_map_ui.dart'; @@ -356,7 +357,7 @@ class ChannelMessagePathScreen extends StatelessWidget { Stack( clipBehavior: Clip.none, children: [ - AvatarCircle(name: hop.displayLabel, size: 36), + AvatarCircle(name: hop.avatarName, size: 36), Positioned( right: -4, top: -4, @@ -1616,14 +1617,23 @@ class _PathHop { bool get hasLocation => position != null; - String get displayLabel { - final prefixLabel = hopBytes != null && hopBytes!.isNotEmpty - ? hopBytes! - .map((b) => b.toRadixString(16).padLeft(2, '0')) - .join('') - .toUpperCase() - : _formatPrefix(prefix); - return '($prefixLabel) ${_resolveName(contact, l10n)}'; + String get prefixLabel => hopBytes != null && hopBytes!.isNotEmpty + ? hopBytes! + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join('') + .toUpperCase() + : _formatPrefix(prefix); + + String get displayLabel => '($prefixLabel) ${_resolveName(contact, l10n)}'; + + /// Avatar source: the repeater's own name, or the hop's hex prefix when + /// the hop is unresolved or its name has nothing to make initials from. + String get avatarName { + final name = contact?.name.trim() ?? ''; + if (name.toLowerCase() == 'unknown' || avatarInitials(name) == null) { + return prefixLabel; + } + return name; } } diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 018b7ec8..b3270202 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -1198,6 +1198,9 @@ class _MapScreenState extends State with WidgetsBindingObserver { showOtherNodes: settings.mapShowOtherNodes, isBuildingPathTrace: _isBuildingPathTrace, clusterNodes: settings.mapClusterNodes, + // Node labels bake in the overlay colors, so a light/dark or theme + // switch must rebuild them. + colorScheme: Theme.of(context).colorScheme, ); if (key != _nodeMarkersCacheKey) { _nodeMarkersCacheKey = key; @@ -4385,6 +4388,7 @@ class _NodeMarkersCacheKey { final bool showOtherNodes; final bool isBuildingPathTrace; final bool clusterNodes; + final ColorScheme colorScheme; const _NodeMarkersCacheKey({ required this.contactsSignature, @@ -4405,6 +4409,7 @@ class _NodeMarkersCacheKey { required this.showOtherNodes, required this.isBuildingPathTrace, required this.clusterNodes, + required this.colorScheme, }); @override @@ -4427,7 +4432,8 @@ class _NodeMarkersCacheKey { showChatNodes == other.showChatNodes && showOtherNodes == other.showOtherNodes && isBuildingPathTrace == other.isBuildingPathTrace && - clusterNodes == other.clusterNodes; + clusterNodes == other.clusterNodes && + colorScheme == other.colorScheme; } @override @@ -4450,6 +4456,7 @@ class _NodeMarkersCacheKey { showOtherNodes, isBuildingPathTrace, clusterNodes, + colorScheme, ); } diff --git a/lib/utils/platform_info.dart b/lib/utils/platform_info.dart index a388932a..6132474d 100644 --- a/lib/utils/platform_info.dart +++ b/lib/utils/platform_info.dart @@ -32,7 +32,12 @@ class PlatformInfo { static bool get isMobile => isAndroid || isIOS; /// Whether the app is running on a desktop platform (macOS, Windows, or Linux). - static bool get isDesktop => isMacOS || isWindows || isLinux; + static bool get isDesktop => + debugIsDesktopOverride ?? (isMacOS || isWindows || isLinux); + + /// Lets widget tests exercise the mobile layout on a desktop test host. + @visibleForTesting + static bool? debugIsDesktopOverride; /// Whether the current platform supports a native USB serial backend. static bool get supportsNativeUsbSerial => diff --git a/lib/widgets/chat_day_separator.dart b/lib/widgets/chat_day_separator.dart index a6d9bcad..0ca0b26c 100644 --- a/lib/widgets/chat_day_separator.dart +++ b/lib/widgets/chat_day_separator.dart @@ -44,21 +44,34 @@ class ChatDaySeparator extends StatelessWidget { ); return Padding( padding: const EdgeInsets.symmetric(vertical: 10), - child: Row( - children: [ - line, - const SizedBox(width: 10), - Text( - formatChatDayLabel(context, day), - style: MeshTheme.mono( - fontSize: 12, - fontWeight: FontWeight.w600, - color: color, + child: LayoutBuilder( + // Large text on a narrow phone wraps the label instead of overflowing; + // each rule keeps at least 16dp. + builder: (context, constraints) => Row( + children: [ + line, + const SizedBox(width: 10), + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: (constraints.maxWidth - 2 * (10 + 16)).clamp( + 0.0, + double.infinity, + ), + ), + child: Text( + formatChatDayLabel(context, day), + textAlign: TextAlign.center, + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w600, + color: color, + ), + ), ), - ), - const SizedBox(width: 10), - line, - ], + const SizedBox(width: 10), + line, + ], + ), ), ); } diff --git a/lib/widgets/contact_visuals.dart b/lib/widgets/contact_visuals.dart index cc9c4319..2caf6bb1 100644 --- a/lib/widgets/contact_visuals.dart +++ b/lib/widgets/contact_visuals.dart @@ -5,6 +5,7 @@ import '../l10n/app_localizations.dart'; import '../models/contact.dart'; import '../theme/mesh_theme.dart'; import '../theme/theme_icons.dart'; +import '../utils/emoji_utils.dart'; /// Shared node-type visuals and last-seen formatting for contact lists /// (contacts, discovery, nearby-node scan). @@ -41,6 +42,40 @@ ThemeIconSlot? contactTypeIconSlot(int type) { } } +final RegExp _letterOrDigit = RegExp(r'^[\p{L}\p{N}]', unicode: true); + +/// Avatar initials for a display name, or null when the name has nothing +/// usable so the caller can show an icon or key prefix instead. +/// +/// Only letters and digits count: punctuation such as `-`, `(` or `[` splits +/// words but never becomes an initial, so "(Base) Node" gives "BN" and +/// "- Relay" gives "RE". Characters are whole grapheme clusters, so accented +/// letters and emoji are never cut in half. A name with no letters or digits +/// but an emoji shows that emoji. +String? avatarInitials(String name) { + final words = []; + final current = StringBuffer(); + String? emoji; + for (final cluster in name.characters) { + if (_letterOrDigit.hasMatch(cluster)) { + current.write(cluster); + continue; + } + if (current.isNotEmpty) { + words.add(current.toString()); + current.clear(); + } + emoji ??= firstEmoji(cluster); + } + if (current.isNotEmpty) words.add(current.toString()); + + if (words.isEmpty) return emoji; + if (words.length == 1) { + return words.first.characters.take(2).toString().toUpperCase(); + } + return (words[0].characters.first + words[1].characters.first).toUpperCase(); +} + /// The most recent activity for [contact]: for chat nodes this includes the /// last message, for other node types only the last advert or telemetry fix. DateTime resolveContactLastSeen(Contact contact) { diff --git a/lib/widgets/mesh_ui.dart b/lib/widgets/mesh_ui.dart index 8bef6c59..e15905eb 100644 --- a/lib/widgets/mesh_ui.dart +++ b/lib/widgets/mesh_ui.dart @@ -7,6 +7,7 @@ import 'package:flutter/services.dart'; import '../l10n/l10n.dart'; import '../theme/mesh_theme.dart'; import '../theme/theme_icons.dart'; +import 'contact_visuals.dart'; /// MeshCore shared design kit. /// @@ -283,7 +284,8 @@ class StatTile extends StatelessWidget { /// Initials avatar with a deterministic per-name hue, or a fixed [color] /// for node-type coloring. Optional [icon] or themeable [iconSlot] replaces -/// initials. +/// initials. Initials come from [avatarInitials]; a name with no letters, +/// digits or emoji shows a generic person icon instead. class AvatarCircle extends StatelessWidget { final String name; final double size; @@ -320,7 +322,7 @@ class AvatarCircle extends StatelessWidget { @override Widget build(BuildContext context) { final accent = color ?? _colorFor(name); - final initials = _initials(name); + final initials = avatarInitials(name); final background = _tintedCardBackground(context, accent, 0.14); // A theme picture (e.g. a holiday marker) fills the whole circle, the // same as on the map, rather than sitting small inside the tint. @@ -360,9 +362,9 @@ class AvatarCircle extends StatelessWidget { size: size * 0.55, color: readableAccent(accent, background, minContrast: 3), ) - : icon != null + : icon != null || initials == null ? Icon( - icon, + icon ?? Icons.person_outline, size: size * 0.5, color: readableAccent(accent, background, minContrast: 3), ) @@ -376,21 +378,6 @@ class AvatarCircle extends StatelessWidget { ), ); } - - static String _initials(String name) { - final words = name - .trim() - .split(RegExp(r'\s+')) - .where((w) => w.isNotEmpty) - .toList(); - if (words.isEmpty) return '?'; - if (words.length == 1) { - return words.first.characters.take(2).toString().toUpperCase(); - } - return (words.first.characters.take(1).toString() + - words[1].characters.take(1).toString()) - .toUpperCase(); - } } /// Four-bar signal strength indicator driven by an SNR value (dB), colored diff --git a/test/screens/channel_message_path_avatar_test.dart b/test/screens/channel_message_path_avatar_test.dart new file mode 100644 index 00000000..cf34f0ba --- /dev/null +++ b/test/screens/channel_message_path_avatar_test.dart @@ -0,0 +1,84 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/channel_message_path_screen.dart'; +import 'package:meshcore_open/widgets/mesh_ui.dart'; +import 'package:provider/provider.dart'; + +class _FakeConnector extends MeshCoreConnector { + _FakeConnector(this.hopContacts); + + final List hopContacts; + + @override + List get allContacts => hopContacts; + + @override + double? get selfLatitude => null; + + @override + double? get selfLongitude => null; +} + +void main() { + testWidgets('hop avatars use the repeater name or the hex prefix', ( + tester, + ) async { + final connector = _FakeConnector([ + Contact( + publicKey: Uint8List(32)..first = 0xAA, + name: '(Base) Hilltop', + type: advTypeRepeater, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.utc(2026), + ), + ]); + final message = ChannelMessage( + senderName: 'Alice', + text: 'hello', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([0xAA, 0xBC]), + channelIndex: 0, + ); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: connector, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: ChannelMessagePathScreen( + message: message, + channelMessage: true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final avatarNames = tester + .widgetList(find.byType(AvatarCircle)) + .map((avatar) => avatar.name) + .toList(); + expect(avatarNames, containsAll(['(Base) Hilltop', 'BC'])); + expect( + find.descendant(of: find.byType(AvatarCircle), matching: find.text('BH')), + findsOneWidget, + ); + expect( + find.descendant( + of: find.byType(AvatarCircle), + matching: find.textContaining('('), + ), + findsNothing, + ); + }); +} diff --git a/test/screens/chat_bubble_width_test.dart b/test/screens/chat_bubble_width_test.dart new file mode 100644 index 00000000..e8e6cfc3 --- /dev/null +++ b/test/screens/chat_bubble_width_test.dart @@ -0,0 +1,321 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/last_radio_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/utils/platform_info.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; + +final _radioKey = Uint8List.fromList(List.generate(32, (i) => 0xA0 + i)); +final _radioHex = pubKeyToHex(_radioKey); +final _aliceKey = Uint8List.fromList(List.generate(32, (i) => 0x10 + i)); +final _psk = Uint8List.fromList(List.generate(16, (i) => 0x40 + i)); + +const _long = + 'The ridge trail is washed out past the second bridge, so take the ' + 'lower path along the river and meet us at the old ranger station.'; + +/// Shows the saved radio as connected or offline without a transport, so +/// both states render exactly the same stored transcript. +class _ToggleConnector extends MeshCoreConnector { + bool connected = false; + + @override + bool get isConnected => connected; +} + +DateTime _at(int seconds) => + DateTime.fromMillisecondsSinceEpoch(1700000000000 + seconds * 1000); + +Future _seedRadio() async { + final alice = Contact( + publicKey: _aliceKey, + name: 'Alice', + type: advTypeChat, + pathLength: 1, + path: Uint8List.fromList([0x22]), + lastSeen: _at(0), + ); + await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([alice]); + final channel = Channel(index: 0, name: 'Base Camp', psk: _psk); + final channelStore = ChannelStore()..setPublicKeyHex = _radioHex; + await channelStore.saveChannels([channel]); + await channelStore.saveSlotChannelIds({0: channel.storageId!}); + + ChannelMessage channelMessage( + int second, + String text, { + required bool outgoing, + String? translated, + }) => ChannelMessage( + senderName: outgoing ? 'Base' : 'Bob', + text: text, + translatedText: translated, + timestamp: _at(second), + isOutgoing: outgoing, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ); + await (ChannelMessageStore()..setPublicKeyHex = _radioHex) + .saveChannelMessages(channel.storageId!, [ + channelMessage(1, 'ok', outgoing: false), + channelMessage(2, _long, outgoing: false), + channelMessage(3, 'on my way', outgoing: true), + channelMessage(4, _long, outgoing: true), + channelMessage( + 5, + 'Der Weg ist frei', + outgoing: false, + translated: 'The path is clear', + ), + ]); + + Message directMessage( + int second, + String text, { + required bool outgoing, + String? translated, + }) => Message( + senderKey: _aliceKey, + text: text, + translatedText: translated, + timestamp: _at(second), + isOutgoing: outgoing, + status: MessageStatus.delivered, + ); + await (MessageStore()..setPublicKeyHex = _radioHex) + .saveMessages(alice.publicKeyHex, [ + directMessage(1, 'hi', outgoing: false), + directMessage(2, _long, outgoing: false), + directMessage(3, 'see you', outgoing: true), + directMessage(4, _long, outgoing: true), + directMessage( + 5, + 'Der Weg ist frei', + outgoing: false, + translated: 'The path is clear', + ), + ]); + await LastRadioStore().save( + LastRadio( + publicKeyHex: _radioHex, + name: 'Base', + transport: LastRadio.transportBle, + bleRemoteId: 'AA:BB:CC:DD:EE:FF', + savedAt: _at(0), + ), + ); +} + +Future _app( + WidgetTester tester, + MeshCoreConnector connector, + Widget home, +) async { + final storage = StorageService(); + final settings = AppSettingsService(); + await tester.runAsync(settings.loadSettings); + final translation = TranslationService(settings); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: MessageRetryService()), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ChangeNotifierProvider.value( + value: NetworkMapUploadService( + connector: connector, + settings: settings, + ), + ), + ], + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +/// Horizontal extent of every rendered bubble, in transcript order. +List _bubbleExtents(WidgetTester tester) { + final frames = find.byType(MessageBubbleFrame); + expect(frames, findsWidgets); + return [ + for (final element in frames.evaluate()) + () { + final rect = tester.getRect(find.byWidget(element.widget)); + return '${rect.left.toStringAsFixed(1)}..' + '${rect.right.toStringAsFixed(1)}'; + }(), + ]; +} + +Future> _render( + WidgetTester tester, + _ToggleConnector connector, + Widget Function() screen, { + required bool connected, +}) async { + connector.connected = connected; + await tester.pumpWidget(await _app(tester, connector, screen())); + await _settle(tester); + final extents = _bubbleExtents(tester); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(seconds: 1)); + return extents; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('bubble_width_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + ChannelMessageStore().forgetArchive(); + MessageStore().forgetArchive(); + await _seedRadio(); + ChannelMessageStore().forgetArchive(); + MessageStore().forgetArchive(); + }); + + // On phones, incoming channel bubbles are swipeable (reply) only while + // connected; that must not change their size or position. Day separators + // and bubbles must also fit 320dp at large text sizes. + for (final desktop in [false, true]) { + for (final scale in [1.0, 1.3, 2.0]) { + final label = '${desktop ? 'desktop' : 'phone'}, 320dp, ${scale}x text'; + + testWidgets('channel bubbles match connected vs offline ($label)', ( + tester, + ) async { + PlatformInfo.debugIsDesktopOverride = desktop; + addTearDown(() => PlatformInfo.debugIsDesktopOverride = null); + tester.view.physicalSize = const Size(320, 4000); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = scale; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + final connector = _ToggleConnector(); + addTearDown(connector.dispose); + await tester.runAsync(connector.restoreLastRadio); + final channel = connector.channels.single; + + final offline = await _render( + tester, + connector, + () => ChannelChatScreen(channel: channel), + connected: false, + ); + final connected = await _render( + tester, + connector, + () => ChannelChatScreen(channel: channel), + connected: true, + ); + expect(offline, hasLength(5)); + expect(connected, offline); + }); + + testWidgets('DM bubbles match connected vs offline ($label)', ( + tester, + ) async { + PlatformInfo.debugIsDesktopOverride = desktop; + addTearDown(() => PlatformInfo.debugIsDesktopOverride = null); + tester.view.physicalSize = const Size(320, 4000); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = scale; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + final connector = _ToggleConnector(); + addTearDown(connector.dispose); + await tester.runAsync(connector.restoreLastRadio); + final alice = connector.contacts.single; + + final offline = await _render( + tester, + connector, + () => ChatScreen(contact: alice), + connected: false, + ); + final connected = await _render( + tester, + connector, + () => ChatScreen(contact: alice), + connected: true, + ); + expect(offline, hasLength(5)); + expect(connected, offline); + }); + } + } +} diff --git a/test/screens/map_rebuild_scope_test.dart b/test/screens/map_rebuild_scope_test.dart index 03c94d08..200db19e 100644 --- a/test/screens/map_rebuild_scope_test.dart +++ b/test/screens/map_rebuild_scope_test.dart @@ -95,7 +95,11 @@ void main() { viewState.dispose(); }); - Future openMap(WidgetTester tester) async { + Future openMap( + WidgetTester tester, { + ThemeMode themeMode = ThemeMode.light, + LatLng? highlight, + }) async { await tester.pumpWidget( MultiProvider( providers: [ @@ -107,9 +111,11 @@ void main() { ], child: MaterialApp( theme: MeshTheme.light(), + darkTheme: MeshTheme.dark(), + themeMode: themeMode, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - home: const MapScreen(), + home: MapScreen(highlightPosition: highlight), ), ), ); @@ -185,4 +191,55 @@ void main() { expect(markerPoints(tester), contains(const LatLng(35, -112))); await tester.pumpWidget(const SizedBox.shrink()); }); + + testWidgets('node labels follow a system light/dark switch', (tester) async { + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + tester.platformDispatcher.platformBrightnessTestValue = Brightness.light; + connector.nodes = [_node()]; + // Zoomed in past the label threshold so node names are drawn. + await openMap( + tester, + themeMode: ThemeMode.system, + highlight: const LatLng(35, -112), + ); + + Color? labelColor() => tester + .widget( + find.descendant( + of: find.byType(MarkerLayer), + matching: find.text('Repeater'), + ), + ) + .style + ?.color; + + expect(labelColor(), MeshTheme.light().colorScheme.onSurface); + + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + await tester.pumpAndSettle(); + expect(labelColor(), MapPalette.textPrimary); + + tester.platformDispatcher.platformBrightnessTestValue = Brightness.light; + await tester.pumpAndSettle(); + expect(labelColor(), MeshTheme.light().colorScheme.onSurface); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a fixed light theme ignores the system switch', (tester) async { + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + tester.platformDispatcher.platformBrightnessTestValue = Brightness.light; + connector.nodes = [_node()]; + await openMap(tester, highlight: const LatLng(35, -112)); + + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + await tester.pumpAndSettle(); + final label = tester.widget( + find.descendant( + of: find.byType(MarkerLayer), + matching: find.text('Repeater'), + ), + ); + expect(label.style?.color, MeshTheme.light().colorScheme.onSurface); + await tester.pumpWidget(const SizedBox.shrink()); + }); } diff --git a/test/widgets/avatar_initials_test.dart b/test/widgets/avatar_initials_test.dart new file mode 100644 index 00000000..9d09d163 --- /dev/null +++ b/test/widgets/avatar_initials_test.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/widgets/contact_visuals.dart'; +import 'package:meshcore_open/widgets/mesh_ui.dart'; + +void main() { + group('avatarInitials', () { + test('empty and whitespace-only names have no initials', () { + expect(avatarInitials(''), isNull); + expect(avatarInitials(' '), isNull); + }); + + test('punctuation-only names have no initials', () { + expect(avatarInitials('-'), isNull); + expect(avatarInitials('(--) [ ]'), isNull); + }); + + test('punctuation never becomes an initial', () { + expect(avatarInitials('(Base) Node'), 'BN'); + expect(avatarInitials('- Relay'), 'RE'); + expect(avatarInitials('[AB12] Hilltop'), 'AH'); + expect(avatarInitials('Node-1'), 'N1'); + }); + + test('plain names keep the existing two-letter shape', () { + expect(avatarInitials('Alice Smith'), 'AS'); + expect(avatarInitials('tower'), 'TO'); + expect(avatarInitials('A1B2C3D4'), 'A1'); + }); + + test('Cyrillic names use their letters', () { + expect(avatarInitials('Иван Петров'), 'ИП'); + expect(avatarInitials('(ретранслятор)'), 'РЕ'); + }); + + test('CJK names use their characters', () { + expect(avatarInitials('東京 中継'), '東中'); + expect(avatarInitials('「大阪」'), '大阪'); + }); + + test('emoji is kept whole and skipped when letters exist', () { + expect(avatarInitials('🔥 Fire Node'), 'FN'); + expect(avatarInitials('Fire🔥Node'), 'FN'); + expect(avatarInitials('🔥'), '🔥'); + expect(avatarInitials('👨‍👩‍👧 -'), '👨‍👩‍👧'); + }); + + test('combining accents stay with their letter', () { + expect(avatarInitials('école'), 'ÉC'); + }); + }); + + testWidgets('AvatarCircle shows an icon when the name has no initials', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: Column( + children: [ + AvatarCircle(name: '(--)'), + AvatarCircle(name: '(Base) Node'), + ], + ), + ), + ), + ); + + expect(find.byIcon(Icons.person_outline), findsOneWidget); + expect(find.text('BN'), findsOneWidget); + expect(find.textContaining('('), findsNothing); + }); +} From 316088dfd67e32623247c84ccd8ab9a0f39598a6 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 08/50] Fix list ordering and long-list scrolling - Sort channels by latest message and contacts by recent message using local arrival time instead of the sender's clock. - Contacts added from a card sort by when they were added until the radio hears an advert (app-side only; lastAdvert stays 0). - Stop entrance animations on rows scrolled into view and reuse unchanged contact rows across connector updates. --- documentation/design.md | 2 +- documentation/performance-profiling.md | 36 ++ lib/connector/meshcore_connector.dart | 25 ++ lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 + lib/l10n/app_localizations_bg.dart | 3 + lib/l10n/app_localizations_cs.dart | 3 + lib/l10n/app_localizations_de.dart | 3 + lib/l10n/app_localizations_en.dart | 3 + lib/l10n/app_localizations_es.dart | 3 + lib/l10n/app_localizations_fr.dart | 3 + lib/l10n/app_localizations_hu.dart | 3 + lib/l10n/app_localizations_it.dart | 3 + lib/l10n/app_localizations_ja.dart | 3 + lib/l10n/app_localizations_ko.dart | 3 + lib/l10n/app_localizations_nl.dart | 3 + lib/l10n/app_localizations_pl.dart | 3 + lib/l10n/app_localizations_pt.dart | 3 + lib/l10n/app_localizations_ru.dart | 3 + lib/l10n/app_localizations_sk.dart | 3 + lib/l10n/app_localizations_sl.dart | 3 + lib/l10n/app_localizations_sv.dart | 3 + lib/l10n/app_localizations_uk.dart | 3 + lib/l10n/app_localizations_zh.dart | 3 + lib/screens/channels_screen.dart | 3 +- lib/screens/contacts_screen.dart | 104 +++-- lib/services/backup_service.dart | 4 +- lib/storage/contact_added_at_store.dart | 45 +++ lib/widgets/contact_visuals.dart | 12 +- lib/widgets/mesh_ui.dart | 42 +- test/connector/contact_added_at_test.dart | 152 ++++++++ test/screens/list_scroll_perf_test.dart | 356 +++++++++++++++++ test/screens/recency_sort_test.dart | 456 ++++++++++++++++++++++ test/services/backup_service_test.dart | 26 ++ test/widgets/contact_last_seen_test.dart | 73 ++++ 35 files changed, 1357 insertions(+), 43 deletions(-) create mode 100644 lib/storage/contact_added_at_store.dart create mode 100644 test/connector/contact_added_at_test.dart create mode 100644 test/screens/list_scroll_perf_test.dart create mode 100644 test/screens/recency_sort_test.dart create mode 100644 test/widgets/contact_last_seen_test.dart diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..f6ba0cd1 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -131,7 +131,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Radio offline on a remote-node screen | `RadioDisconnectedBanner` | Renders nothing while connected | | Sync progress | `SyncProgressAppBarBottom` as the app bar `bottom` | 3px bar | | Toast message | `showDismissibleSnackBar(context, content: Text(...))` | Tap to dismiss, replaces the current snackbar, safe after an async gap | -| List item entrance | `ListEntrance(index:)` | Optional | +| List item entrance | `ListEntrance(index:)` | Optional. Plays only for rows built while the list is at rest at the top; rows scrolled into view appear at once | **Buttons.** Theme shapes are all pill-shaped. In use: diff --git a/documentation/performance-profiling.md b/documentation/performance-profiling.md index 48657397..ca0c85d9 100644 --- a/documentation/performance-profiling.md +++ b/documentation/performance-profiling.md @@ -57,3 +57,39 @@ them into the selected radio's scope. Review-mode cleanup also covers the databa For a manual full application-data copy, keep the history database alongside the application's other support files; copying the preferences file alone no longer includes native message or route histories. + +## Long contact and channel lists + +`test/screens/list_scroll_perf_test.dart` builds the contacts list with 500 +contacts and the channels list with 40 channels, flings each one with a +connector notify partway through, and prints build counts and how many visible +rows were blank or still fading in during the fling: + +```sh +flutter test test/screens/list_scroll_perf_test.dart +``` + +It fails if rows scrolled into view play the entrance fade, or if a connector +notify that changes nothing rebuilds contact rows. The counts are a widget-test +proxy; frame times still need a phone. + +To check scrolling on a phone: + +1. Connect a radio with several hundred contacts and a few dozen channels (or + use the same radio before and after a change), then run + `flutter run --profile` on the phone. +2. Open DevTools from the printed link and select the Performance page. Turn + on "Track widget builds" only for a separate run: it adds overhead to the + frame times. +3. Open Contacts, wait for sync to finish, and clear the timeline. +4. Fling the list hard to the bottom and back to the top five times, then drag + it up and down quickly for a few seconds. Repeat while messages and adverts + are arriving. +5. In the frame chart, note the share of frames over budget (16 ms at 60 Hz, + 8 ms at 120 Hz) on the UI and raster threads, and the worst frames. Select a + slow frame to see whether build, layout, paint or raster dominates. +6. Watch the screen: rows must be fully drawn as they enter, with no blank + rows trailing the finger. +7. Repeat steps 3 to 6 on Channels. +8. Record the device, build mode, contact and channel counts and the numbers + from step 5 for the before and after builds. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index ad9fa57e..78709b39 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -61,6 +61,7 @@ import '../storage/channel_settings_store.dart'; import '../storage/channel_region_store.dart'; import '../storage/channel_storage_migration.dart'; import '../storage/channel_store.dart'; +import '../storage/contact_added_at_store.dart'; import '../storage/contact_discovery_store.dart'; import '../storage/contact_settings_store.dart'; import '../storage/contact_store.dart'; @@ -525,6 +526,8 @@ class MeshCoreConnector extends ChangeNotifier { final ChannelRegionStore _channelRegionStore = ChannelRegionStore(); final ContactSettingsStore _contactSettingsStore = ContactSettingsStore(); final ContactStore _contactStore = ContactStore(); + final ContactAddedAtStore _contactAddedAtStore = ContactAddedAtStore(); + final Map _contactAddedAt = {}; final ContactDiscoveryStore _discoveryContactStore = ContactDiscoveryStore(); final ChannelStore _channelStore = ChannelStore(); final UnreadStore _unreadStore = UnreadStore(); @@ -648,6 +651,11 @@ class MeshCoreConnector extends ChangeNotifier { return radio.bleDisplayName; } + /// Phone time a contact was first added from a card; the list orders by it + /// while the radio has no advert time for the contact. + DateTime? contactAddedAt(String contactPubKeyHex) => + _contactAddedAt[contactPubKeyHex]; + Contact? getContactByPubKeyHex(String contactPubKeyHex) { return _contacts.cast().firstWhere( (c) => c?.publicKeyHex == contactPubKeyHex, @@ -2435,6 +2443,9 @@ class MeshCoreConnector extends ChangeNotifier { _contacts ..clear() ..addAll(cached); + _contactAddedAt + ..clear() + ..addAll(_contactAddedAtStore.load()); for (final contact in cached) { _ensureContactSmazSettingLoaded(contact.publicKeyHex); _ensureContactCyr2LatSettingLoaded(contact.publicKeyHex); @@ -5097,6 +5108,13 @@ class MeshCoreConnector extends ChangeNotifier { pathHashByteWidth: pathHashByteWidth, ); await sendFrame(frame, waitForGenericAck: true); + if (publicKey != null) { + final keyHex = pubKeyToHex(publicKey); + if (!_contactAddedAt.containsKey(keyHex)) { + _contactAddedAt[keyHex] = DateTime.now(); + await _contactAddedAtStore.save(_contactAddedAt); + } + } await refreshContacts(); } @@ -6092,6 +6110,9 @@ class MeshCoreConnector extends ChangeNotifier { _contactsStorageFull = false; _contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex); _knownContactKeys.remove(contact.publicKeyHex); + if (_contactAddedAt.remove(contact.publicKeyHex) != null) { + unawaited(_contactAddedAtStore.save(_contactAddedAt)); + } unawaited(updateKnownDiscovered()); unawaited(_persistContacts()); _conversations.remove(contact.publicKeyHex); @@ -7780,6 +7801,9 @@ class MeshCoreConnector extends ChangeNotifier { ); _contacts.removeWhere((c) => c.publicKeyHex == keyHex); _knownContactKeys.remove(keyHex); + if (_contactAddedAt.remove(keyHex) != null) { + unawaited(_contactAddedAtStore.save(_contactAddedAt)); + } _contactsStorageFull = false; unawaited(updateKnownDiscovered()); unawaited(_persistContacts()); @@ -9864,6 +9888,7 @@ class MeshCoreConnector extends ChangeNotifier { _channelRegionStore.setPublicKeyHex = keyHex; _contactSettingsStore.setPublicKeyHex = keyHex; _contactStore.setPublicKeyHex = keyHex; + _contactAddedAtStore.setPublicKeyHex = keyHex; _channelStore.setPublicKeyHex = keyHex; _unreadStore.setPublicKeyHex = keyHex; _discoveryContactStore.setPublicKeyHex = keyHex; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..69b5814d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -844,6 +844,7 @@ "contacts_noContactsMatchFilter": "No contacts match your filter", "contacts_noMembers": "No members", "contacts_lastSeenNow": "recently", + "contacts_lastSeenNever": "not heard yet", "contacts_lastSeenMinsAgo": "~ {minutes} min.", "@contacts_lastSeenMinsAgo": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..596d9c18 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3295,6 +3295,12 @@ abstract class AppLocalizations { /// **'recently'** String get contacts_lastSeenNow; + /// No description provided for @contacts_lastSeenNever. + /// + /// In en, this message translates to: + /// **'not heard yet'** + String get contacts_lastSeenNever; + /// No description provided for @contacts_lastSeenMinsAgo. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..97a32866 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1838,6 +1838,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_lastSeenNow => 'наскоро'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes мин.'; diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..a2a40921 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -1825,6 +1825,9 @@ class AppLocalizationsCs extends AppLocalizations { @override String get contacts_lastSeenNow => 'nedávno'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min.'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..f785a1d5 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1838,6 +1838,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get contacts_lastSeenNow => 'gerade eben'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes Min.'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..6c829f45 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1805,6 +1805,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_lastSeenNow => 'recently'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min.'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..1dd7013d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1830,6 +1830,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get contacts_lastSeenNow => 'Reciente'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..bf596443 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1835,6 +1835,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get contacts_lastSeenNow => 'À l\'instant'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..4369484e 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1828,6 +1828,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get contacts_lastSeenNow => 'nemrég'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min.'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..065997df 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1832,6 +1832,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get contacts_lastSeenNow => 'Poco fa'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..891cb25e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1741,6 +1741,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get contacts_lastSeenNow => '最近'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '約 $minutes 分前'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..50910136 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1745,6 +1745,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get contacts_lastSeenNow => '최근'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes분'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..0657cf9c 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1824,6 +1824,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get contacts_lastSeenNow => 'recent'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min.'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..c50c56f7 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1846,6 +1846,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contacts_lastSeenNow => 'niedawno'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..f52985b2 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1831,6 +1831,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get contacts_lastSeenNow => 'Recente'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..1a312bf1 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1830,6 +1830,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contacts_lastSeenNow => 'недавно'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes мин.'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..44cbe823 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1824,6 +1824,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contacts_lastSeenNow => 'nedávno'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min.'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..8963eefb 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1822,6 +1822,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_lastSeenNow => 'pravkar'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..7e44b2e0 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1812,6 +1812,9 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contacts_lastSeenNow => 'nyss'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes min'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..8a4a9311 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1826,6 +1826,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_lastSeenNow => 'нещодавно'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '~ $minutes хв.'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..28cd0955 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1715,6 +1715,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_lastSeenNow => '刚刚'; + @override + String get contacts_lastSeenNever => 'not heard yet'; + @override String contacts_lastSeenMinsAgo(int minutes) { return '约 $minutes 分钟'; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 6f247343..ad3bd2ba 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -783,13 +783,14 @@ class _ChannelsScreenState extends State { break; case ChannelSortOption.latestMessages: // Filtered messages don't bump a channel, matching the preview. + // Ordered by local arrival time: sender clocks can be far off. // Looked up once per channel: the lookup can scan back through // filtered messages, and the comparator runs O(n log n) times. final epoch = DateTime(1970); final latest = { for (final channel in filtered) channel: - connector.latestVisibleChannelMessage(channel)?.timestamp ?? + connector.latestVisibleChannelMessage(channel)?.receivedAt ?? epoch, }; filtered.sort((a, b) { diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 2d60dd3a..cf9ad1b8 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -80,6 +80,8 @@ class _ContactsScreenState extends State { final List<_PendingContactOperation> _pendingOperations = []; final DerivedListCache _filteredCache = DerivedListCache(); + final Map _rowCache = {}; + MeshCoreConnector? _rowCacheConnector; StreamSubscription? _frameSubscription; @@ -1098,21 +1100,12 @@ class _ContactsScreenState extends State { itemBuilder: (context, row) { if (row == 0) return discoveredTile; final index = row - 1; - final contact = filteredAndSorted[index]; - final unreadCount = connector.getUnreadCountForContact( - contact, - ); - return _ContactTileEntrance( - index: index, - contact: contact, - pathHashByteWidth: connector.pathHashByteWidth, - lastSeen: resolveContactLastSeen(contact), - unreadCount: unreadCount, - isFavorite: contact.isFavorite, - onTap: () => _openChat(context, contact), - onLongPress: () => - _showContactOptions(context, connector, contact), - onManage: _manageAction(context, contact), + return _contactRow( + context, + connector, + filteredAndSorted[index], + index, + filteredAndSorted.length, ); }, ), @@ -1122,6 +1115,54 @@ class _ContactsScreenState extends State { ); } + /// Returns the row built last time for [contact] when nothing it shows has + /// changed. The connector notifies up to 20 times a second on a busy mesh + /// and each notify rebuilds this screen; handing the list the same widget + /// instance lets Flutter skip rebuilding those rows. + _ContactTileEntrance _contactRow( + BuildContext context, + MeshCoreConnector connector, + Contact contact, + int index, + int rowCount, + ) { + if (!identical(_rowCacheConnector, connector)) { + _rowCache.clear(); + _rowCacheConnector = connector; + } + final unreadCount = connector.getUnreadCountForContact(contact); + final pathHashByteWidth = connector.pathHashByteWidth; + // Relative ("5 mins ago"), so it can change while the contact does not. + final lastSeenLabel = formatContactLastSeen( + context.l10n, + resolveContactLastSeen(contact), + ); + final cached = _rowCache[contact.publicKeyHex]; + if (cached != null && + identical(cached.contact, contact) && + cached.index == index && + cached.unreadCount == unreadCount && + cached.pathHashByteWidth == pathHashByteWidth && + cached.lastSeenLabel == lastSeenLabel) { + return cached; + } + // Drop rows of contacts that left the list now and then. + if (_rowCache.length > rowCount + 100) _rowCache.clear(); + return _rowCache[contact.publicKeyHex] = _ContactTileEntrance( + index: index, + contact: contact, + pathHashByteWidth: pathHashByteWidth, + lastSeenLabel: lastSeenLabel, + unreadCount: unreadCount, + isFavorite: contact.isFavorite, + // The State's context: rows outlive the list's item context while the + // list is swapped for an empty state. + onTap: () => _openChat(this.context, contact), + onLongPress: () => _showContactOptions(this.context, connector, contact), + onManage: _manageAction(this.context, contact), + ); + } + List _filterAndSortContacts( List contacts, MeshCoreConnector connector, @@ -1155,7 +1196,8 @@ class _ContactsScreenState extends State { DateTime _lastMessageTime(MeshCoreConnector connector, Contact contact) { final messages = connector.getMessages(contact); - return messages.isEmpty ? DateTime(1970) : messages.last.timestamp; + // Local arrival time: sender clocks can be far off. + return messages.isEmpty ? DateTime(1970) : messages.last.receivedAt; } List _computeFilteredContacts( @@ -1203,16 +1245,24 @@ class _ContactsScreenState extends State { switch (viewState.contactsSortOption) { case ContactSortOption.lastSeen: - filtered.sort( - (a, b) => - resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)), - ); + final lastSeenAt = { + for (final c in filtered) + c: resolveContactLastSeen( + c, + addedAt: connector.contactAddedAt(c.publicKeyHex), + ), + }; + filtered.sort((a, b) => lastSeenAt[b]!.compareTo(lastSeenAt[a]!)); break; case ContactSortOption.recentMessages: final lastMessageAt = { for (final c in filtered) c: _lastMessageTime(connector, c), }; - filtered.sort((a, b) => lastMessageAt[b]!.compareTo(lastMessageAt[a]!)); + filtered.sort((a, b) { + final timeCompare = lastMessageAt[b]!.compareTo(lastMessageAt[a]!); + if (timeCompare != 0) return timeCompare; + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + }); break; case ContactSortOption.name: filtered.sort( @@ -1874,7 +1924,7 @@ void confirmRemoveContact( class _ContactTile extends StatelessWidget { final Contact contact; final int pathHashByteWidth; - final DateTime lastSeen; + final String lastSeenLabel; final int unreadCount; final bool isFavorite; final VoidCallback onTap; @@ -1884,7 +1934,7 @@ class _ContactTile extends StatelessWidget { const _ContactTile({ required this.contact, required this.pathHashByteWidth, - required this.lastSeen, + required this.lastSeenLabel, required this.unreadCount, required this.isFavorite, required this.onTap, @@ -2016,7 +2066,7 @@ class _ContactTile extends StatelessWidget { ], ), Text( - formatContactLastSeen(context.l10n, lastSeen), + lastSeenLabel, maxLines: 2, overflow: TextOverflow.ellipsis, style: MeshTheme.mono( @@ -2121,7 +2171,7 @@ class _ContactTileEntrance extends StatelessWidget { final int index; final Contact contact; final int pathHashByteWidth; - final DateTime lastSeen; + final String lastSeenLabel; final int unreadCount; final bool isFavorite; final VoidCallback onTap; @@ -2132,7 +2182,7 @@ class _ContactTileEntrance extends StatelessWidget { required this.index, required this.contact, required this.pathHashByteWidth, - required this.lastSeen, + required this.lastSeenLabel, required this.unreadCount, required this.isFavorite, required this.onTap, @@ -2147,7 +2197,7 @@ class _ContactTileEntrance extends StatelessWidget { child: _ContactTile( contact: contact, pathHashByteWidth: pathHashByteWidth, - lastSeen: lastSeen, + lastSeenLabel: lastSeenLabel, unreadCount: unreadCount, isFavorite: isFavorite, onTap: onTap, diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart index 4fd46e41..1a7d48f0 100644 --- a/lib/services/backup_service.dart +++ b/lib/services/backup_service.dart @@ -23,6 +23,7 @@ const String _encryptedBackupFormat = 'meshcore-open-encrypted-backup'; const List _contactPreferencePrefixes = [ 'contacts', 'contact_groups', + 'contact_added_at_', 'contact_smaz_', 'contact_cyr2lat_', 'contact_url_images_', @@ -1094,7 +1095,8 @@ class BackupService { return true; } if (items.contains(BackupItem.contacts) && - key.startsWith('contacts$devicePrefix')) { + (key.startsWith('contacts$devicePrefix') || + key.startsWith('contact_added_at_$devicePrefix'))) { return true; } if (items.contains(BackupItem.perContactSettings) && diff --git a/lib/storage/contact_added_at_store.dart b/lib/storage/contact_added_at_store.dart new file mode 100644 index 00000000..9ff61ca8 --- /dev/null +++ b/lib/storage/contact_added_at_store.dart @@ -0,0 +1,45 @@ +import 'dart:convert'; + +import '../utils/app_logger.dart'; +import 'prefs_manager.dart'; + +/// Phone time at which each contact was first added from a card, keyed by +/// contact public key hex. App-side only: the radio keeps advert time 0 for +/// these contacts, so this orders them until a real advert arrives. +class ContactAddedAtStore { + static const String _keyPrefix = 'contact_added_at_'; + + String publicKeyHex = ''; + set setPublicKeyHex(String value) => + publicKeyHex = value.length > 10 ? value.substring(0, 10) : ''; + + String get keyFor => '$_keyPrefix$publicKeyHex'; + + Map load() { + if (publicKeyHex.isEmpty) return {}; + final jsonString = PrefsManager.instance.getString(keyFor); + if (jsonString == null || jsonString.isEmpty) return {}; + try { + final decoded = jsonDecode(jsonString) as Map; + return { + for (final entry in decoded.entries) + if (entry.value is int) + entry.key: DateTime.fromMillisecondsSinceEpoch(entry.value as int), + }; + } catch (e) { + appLogger.warn('Stored contact added times are unreadable: $e'); + return {}; + } + } + + Future save(Map addedAt) async { + if (publicKeyHex.isEmpty) return; + await PrefsManager.instance.setString( + keyFor, + jsonEncode({ + for (final entry in addedAt.entries) + entry.key: entry.value.millisecondsSinceEpoch, + }), + ); + } +} diff --git a/lib/widgets/contact_visuals.dart b/lib/widgets/contact_visuals.dart index cc9c4319..d8f2f972 100644 --- a/lib/widgets/contact_visuals.dart +++ b/lib/widgets/contact_visuals.dart @@ -43,14 +43,22 @@ ThemeIconSlot? contactTypeIconSlot(int type) { /// The most recent activity for [contact]: for chat nodes this includes the /// last message, for other node types only the last advert or telemetry fix. -DateTime resolveContactLastSeen(Contact contact) { - final heard = contact.lastHeard; +/// [addedAt] (the phone time the contact was added from a card) stands in +/// while the radio has no advert time for it. +DateTime resolveContactLastSeen(Contact contact, {DateTime? addedAt}) { + final heard = + addedAt != null && + contact.lastSeen.millisecondsSinceEpoch == 0 && + addedAt.isAfter(contact.lastHeard) + ? addedAt + : contact.lastHeard; if (contact.type != advTypeChat) return heard; return contact.lastMessageAt.isAfter(heard) ? contact.lastMessageAt : heard; } /// Short relative "last seen" label ("now", "5 mins ago", "2 days ago"). String formatContactLastSeen(AppLocalizations l10n, DateTime lastSeen) { + if (lastSeen.millisecondsSinceEpoch == 0) return l10n.contacts_lastSeenNever; final diff = DateTime.now().difference(lastSeen); if (diff.isNegative || diff.inMinutes < 5) { diff --git a/lib/widgets/mesh_ui.dart b/lib/widgets/mesh_ui.dart index 8bef6c59..f65b39be 100644 --- a/lib/widgets/mesh_ui.dart +++ b/lib/widgets/mesh_ui.dart @@ -699,6 +699,11 @@ class ErrorRetryCard extends StatelessWidget { /// Staggered fade + slide entrance for list items. Wrap each item and pass /// its [index]; animation only plays once per widget lifecycle. +/// +/// Only rows built while their list is at rest at the top play it. Rows that +/// a scroll brings into view appear at once: a delayed fade there leaves +/// blank rows trailing the finger and adds a ticker and an opacity layer per +/// row during a fling. class ListEntrance extends StatefulWidget { final int index; final Widget child; @@ -711,41 +716,56 @@ class ListEntrance extends StatefulWidget { class _ListEntranceState extends State with SingleTickerProviderStateMixin { - // Created eagerly: a lazy `late final` initializer would run on first - // access — which can be dispose(), where ticker creation throws. - late final AnimationController _controller; - late final CurvedAnimation _curve; + // Created in initState, not lazily: a lazy initializer would run on first + // access — which can be dispose(), where ticker creation throws. Null when + // the row skips the entrance. + AnimationController? _controller; + CurvedAnimation? _curve; + + /// Whether the enclosing list has scrolled away from the top or is moving, + /// i.e. this row is entering because of a scroll. + bool _enteredByScroll() { + final scrollable = context.findAncestorStateOfType(); + if (scrollable == null) return false; + final position = scrollable.position; + return position.isScrollingNotifier.value || + (position.hasPixels && position.pixels != 0); + } @override void initState() { super.initState(); - _controller = AnimationController( + // Decided once: changing the tree shape later would rebuild the row. + if (_enteredByScroll()) return; + final controller = _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 280), ); - _curve = CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic); + _curve = CurvedAnimation(parent: controller, curve: Curves.easeOutCubic); final delay = Duration(milliseconds: 24 * widget.index.clamp(0, 12)); Future.delayed(delay, () { - if (mounted) _controller.forward(); + if (mounted) controller.forward(); }); } @override void dispose() { - _curve.dispose(); - _controller.dispose(); + _curve?.dispose(); + _controller?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { + final curve = _curve; + if (curve == null) return widget.child; return FadeTransition( - opacity: _curve, + opacity: curve, child: SlideTransition( position: Tween( begin: const Offset(0, 0.04), end: Offset.zero, - ).animate(_curve), + ).animate(curve), child: widget.child, ), ); diff --git a/test/connector/contact_added_at_test.dart b/test/connector/contact_added_at_test.dart new file mode 100644 index 00000000..a2d2a3f7 --- /dev/null +++ b/test/connector/contact_added_at_test.dart @@ -0,0 +1,152 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/contact_added_at_store.dart'; +import 'package:meshcore_open/storage/last_radio_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/utils/contact_qr.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Future _waitFor(bool Function() condition, {int seconds = 8}) async { + final end = DateTime.now().add(Duration(seconds: seconds)); + while (!condition()) { + if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); + await Future.delayed(const Duration(milliseconds: 25)); + } +} + +class _RecordingReviewRadio extends ReviewRadio { + final List sent = []; + + _RecordingReviewRadio() + : super(scheduledMessageInterval: const Duration(hours: 1)); + + @override + void handle(Uint8List frame) { + sent.add(frame); + super.handle(frame); + } +} + +// [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert x4] +const _lastAdvertOffset = 1 + 32 + 1 + 1 + 1 + 64 + 32; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test( + 'a card add records a local added time once, never on the radio', + () async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + final retryService = MessageRetryService(); + addTearDown(retryService.dispose); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + final radio = _RecordingReviewRadio(); + connector.reviewRadioFactoryForTest = () => radio; + await connector.connectReview(); + await _waitFor(() => connector.hasLoadedContacts); + + final key = Uint8List.fromList(List.generate(32, (i) => 0xA0 + (i % 16))); + final keyHex = pubKeyToHex(key); + final card = ScannedContact(publicKey: key, name: 'Card', type: 1); + + final before = DateTime.now(); + await connector.addContactFromCard(card); + final addedAt = connector.contactAddedAt(keyHex); + expect(addedAt, isNotNull); + expect(addedAt!.isBefore(before), isFalse); + + // The radio still gets advert time 0 (its replay guard). + final addFrame = radio.sent.lastWhere( + (f) => f.first == cmdAddUpdateContact, + ); + expect( + ByteData.sublistView( + addFrame, + ).getUint32(_lastAdvertOffset, Endian.little), + 0, + ); + + // Re-adding keeps the first time. + await Future.delayed(const Duration(milliseconds: 5)); + await connector.addContactFromCard(card); + expect(connector.contactAddedAt(keyHex), addedAt); + + // Persisted per radio. + final store = ContactAddedAtStore() + ..setPublicKeyHex = connector.selfPublicKeyHex; + expect( + store.load()[keyHex]?.millisecondsSinceEpoch, + addedAt.millisecondsSinceEpoch, + ); + final otherRadio = ContactAddedAtStore() + ..setPublicKeyHex = 'ffffffffff00'; + expect(otherRadio.load(), isEmpty); + + // Removing the contact forgets it, so a later add starts fresh. + await connector.removeContact( + Contact( + publicKey: key, + name: 'Card', + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ), + ); + expect(connector.contactAddedAt(keyHex), isNull); + + // So does the firmware deleting it to make room. + await connector.addContactFromCard(card); + expect(connector.contactAddedAt(keyHex), isNotNull); + connector.handleFrameForTest([pushCodeContactDeleted, ...key]); + expect(connector.contactAddedAt(keyHex), isNull); + await Future.delayed(Duration.zero); + expect(store.load(), isNot(contains(keyHex))); + + await connector.disconnect(manual: true); + }, + ); + + test('a saved radio restores its added times after a restart', () async { + const radioHex = + 'a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf'; + final contactHex = 'c1' * 32; + final addedAt = DateTime.fromMillisecondsSinceEpoch(1790000000000); + await (ContactAddedAtStore()..setPublicKeyHex = radioHex).save({ + contactHex: addedAt, + }); + await LastRadioStore().save( + LastRadio( + publicKeyHex: radioHex, + name: 'Base', + transport: LastRadio.transportBle, + bleRemoteId: 'AA:BB:CC:DD:EE:FF', + savedAt: addedAt, + ), + ); + + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + await connector.restoreLastRadio(); + + expect(connector.contactAddedAt(contactHex), addedAt); + }); +} diff --git a/test/screens/list_scroll_perf_test.dart b/test/screens/list_scroll_perf_test.dart new file mode 100644 index 00000000..4bb53484 --- /dev/null +++ b/test/screens/list_scroll_perf_test.dart @@ -0,0 +1,356 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/channels_screen.dart'; +import 'package:meshcore_open/screens/contacts_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/mesh_ui.dart'; + +/// Repeatable stand-in for profiling rapid scrolling on a phone: builds the +/// contacts list with 500 contacts and the channels list with 40 channels, +/// flings each list, and counts widget builds and rows that are not fully +/// drawn while scrolling. Run with `flutter test +/// test/screens/list_scroll_perf_test.dart` and read the printed lines. +/// See documentation/performance-profiling.md for the on-device check. + +const _contactCount = 500; +const _channelCount = 40; + +class _Connector extends MeshCoreConnector { + List nodes = []; + List slots = []; + final Map unread = {}; + final Map latest = {}; + + @override + List get contacts => List.unmodifiable(nodes); + + @override + List get channels => List.unmodifiable(slots); + + @override + int getUnreadCountForContact(Contact contact) => + unread[contact.publicKeyHex] ?? 0; + + @override + int getUnreadCountForChannel(Channel channel) => channel.unreadCount; + + @override + ChannelMessage? latestVisibleChannelMessage(Channel channel) => + latest[channel.index]; + + @override + Future getChannels({int? maxChannels, bool force = false}) async {} +} + +Contact _contact(int i, DateTime now) { + final key = Uint8List(32) + ..[0] = i >> 8 + ..[1] = i & 0xff + ..[2] = 0x5a; + final type = i % 10 == 0 + ? advTypeRepeater + : i % 25 == 0 + ? advTypeRoom + : advTypeChat; + return Contact( + publicKey: key, + name: 'Node ${i.toString().padLeft(3, '0')}', + type: type, + pathLength: i % 4, + path: Uint8List.fromList(List.filled(i % 4, i & 0xff)), + latitude: i.isEven ? 35.0 : null, + longitude: i.isEven ? -112.0 : null, + lastSeen: now.subtract(Duration(minutes: i * 7)), + ); +} + +/// Counts element builds per widget type, via the framework's debug hook. +class _BuildCounter { + final Map counts = {}; + + void start() { + counts.clear(); + debugOnRebuildDirtyWidget = (element, _) { + final name = element.widget.runtimeType.toString(); + counts[name] = (counts[name] ?? 0) + 1; + }; + } + + void stop() => debugOnRebuildDirtyWidget = null; + + int operator [](String type) => counts[type] ?? 0; + int get total => counts.values.fold(0, (a, b) => a + b); +} + +/// Rows inside the visible list area whose entrance fade has not finished: +/// they are blank or partly transparent while the user scrolls. +int _rowsNotFullyDrawn(WidgetTester tester, Rect viewport) { + final fades = find.descendant( + of: find.byType(ListEntrance), + matching: find.byType(FadeTransition), + ); + var count = 0; + for (final element in fades.evaluate()) { + final fade = element.widget as FadeTransition; + final box = element.renderObject as RenderBox?; + if (box == null || !box.attached || !box.hasSize) continue; + final rect = box.localToGlobal(Offset.zero) & box.size; + if (!rect.overlaps(viewport)) continue; + if (fade.opacity.value < 1) count++; + } + return count; +} + +class _ScrollResult { + int frames = 0; + int notFullyDrawnRowFrames = 0; + int maxNotFullyDrawn = 0; + int notFullyDrawnAfterStop = 0; +} + +/// Flings [list] like a rapid swipe and pumps 60 Hz frames until the list +/// stops, firing a connector notify partway through. +Future<_ScrollResult> _fling( + WidgetTester tester, + Finder list, + _Connector connector, { + required Offset offset, +}) async { + final viewport = tester.getRect(list); + final position = tester.state( + find.descendant(of: list, matching: find.byType(Scrollable)).first, + ); + final result = _ScrollResult(); + await tester.fling(list, offset, 6000); + for (var i = 0; i < 400; i++) { + if (i == 10) connector.notifyListeners(); + await tester.pump(const Duration(milliseconds: 16)); + result.frames++; + final hidden = _rowsNotFullyDrawn(tester, viewport); + result.notFullyDrawnRowFrames += hidden; + if (hidden > result.maxNotFullyDrawn) result.maxNotFullyDrawn = hidden; + if (i > 12 && !position.position.isScrollingNotifier.value) break; + } + result.notFullyDrawnAfterStop = _rowsNotFullyDrawn(tester, viewport); + return result; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _Connector connector; + late AppSettingsService settings; + late UiViewStateService viewState; + final counter = _BuildCounter(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = _Connector(); + settings = AppSettingsService(); + viewState = UiViewStateService(); + }); + + tearDown(() { + counter.stop(); + connector.dispose(); + settings.dispose(); + viewState.dispose(); + }); + + /// Opens [home] and returns how many rows played the entrance animation. + Future open(WidgetTester tester, Widget home) async { + tester.view.physicalSize = const Size(1080, 2340); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: viewState), + ], + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ), + ); + await tester.pump(); + final animatedRows = find + .descendant( + of: find.byType(ListEntrance), + matching: find.byType(FadeTransition), + ) + .evaluate() + .length; + // Let the first screen's entrance animations finish. + for (var i = 0; i < 40; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + return animatedRows; + } + + Future notifyAndSettle(WidgetTester tester) async { + connector.notifyListeners(); + await tester.pump(const Duration(milliseconds: 60)); + await tester.pump(); + } + + Future close(WidgetTester tester) async { + counter.stop(); + await tester.pumpWidget(const SizedBox.shrink()); + // Drain entrance-delay timers. + await tester.pump(const Duration(seconds: 1)); + } + + testWidgets('contacts list: rapid fling with 500 contacts', (tester) async { + final now = DateTime.now(); + connector.nodes = [ + for (var i = 0; i < _contactCount; i++) _contact(i, now), + ]; + for (var i = 1; i < _contactCount; i += 9) { + connector.unread[connector.nodes[i].publicKeyHex] = i % 5 + 1; + } + final animatedRows = await open(tester, const ContactsScreen()); + final list = find.byType(ListView); + expect(list, findsOneWidget); + + counter.start(); + final down = await _fling( + tester, + list, + connector, + offset: const Offset(0, -2500), + ); + final flingBuilds = Map.of(counter.counts); + final flingTotal = counter.total; + + counter.start(); + await notifyAndSettle(tester); + final notifyTiles = counter['_ContactTile']; + final notifyTotal = counter.total; + + // A live change still reaches the visible tile. + final visible = tester + .widgetList( + find.byWidgetPredicate( + (w) => w.runtimeType.toString() == '_ContactTile', + ), + ) + .map((w) => (w as dynamic).contact as Contact) + .toList(); + final target = visible[visible.length ~/ 2]; + connector.unread[target.publicKeyHex] = 42; + counter.start(); + await notifyAndSettle(tester); + final changeTiles = counter['_ContactTile']; + expect(find.text('42'), findsOneWidget); + + // So does a replaced contact. + final renamedAt = connector.nodes.indexOf(visible.first); + connector.nodes = List.of(connector.nodes) + ..[renamedAt] = visible.first.copyWith(name: 'Renamed node'); + await notifyAndSettle(tester); + expect(find.text('Renamed node'), findsOneWidget); + + // ignore: avoid_print + print( + '[list-perf] contacts fling: frames=${down.frames} ' + 'itemBuilds=${flingBuilds['_ContactTileEntrance'] ?? 0} ' + 'tileBuilds=${flingBuilds['_ContactTile'] ?? 0} ' + 'entranceBuilds=${flingBuilds['ListEntrance'] ?? 0} ' + 'allBuilds=$flingTotal ' + 'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} ' + 'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} ' + 'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n' + '[list-perf] contacts notify (no change): tileBuilds=$notifyTiles ' + 'allBuilds=$notifyTotal; one unread change: tileBuilds=$changeTiles', + ); + + // The first screen still animates in; rows a fling brings in do not. + expect(animatedRows, greaterThan(0)); + expect(down.notFullyDrawnRowFrames, 0); + // A notify that changes nothing rebuilds no rows; a change rebuilds one. + expect(notifyTiles, 0); + expect(changeTiles, 1); + + await close(tester); + }); + + testWidgets('channels list: rapid fling with 40 channels', (tester) async { + final now = DateTime.now(); + connector.slots = [ + for (var i = 0; i < _channelCount; i++) + Channel( + index: i, + name: i == 0 ? 'Public' : '#topic-$i', + psk: Uint8List.fromList(List.filled(16, i + 1)), + unreadCount: i % 3 == 0 ? i : 0, + ), + ]; + for (var i = 0; i < _channelCount; i++) { + connector.latest[i] = ChannelMessage( + senderName: 'Sender $i', + text: 'Message preview number $i on the mesh', + timestamp: now.subtract(Duration(minutes: i * 13)), + isOutgoing: false, + status: ChannelMessageStatus.sent, + channelIndex: i, + ); + } + viewState.setChannelsSortOption(ChannelSortOption.name); + final animatedRows = await open(tester, const ChannelsScreen()); + final list = find.byType(ListView); + expect(list, findsOneWidget); + + counter.start(); + final down = await _fling( + tester, + list, + connector, + offset: const Offset(0, -2500), + ); + final flingBuilds = Map.of(counter.counts); + final flingTotal = counter.total; + + counter.start(); + await notifyAndSettle(tester); + final notifyTiles = counter['MeshCard']; + + // ignore: avoid_print + print( + '[list-perf] channels fling: frames=${down.frames} ' + 'itemBuilds=${flingBuilds['ListEntrance'] ?? 0} ' + 'cardBuilds=${flingBuilds['MeshCard'] ?? 0} ' + 'allBuilds=$flingTotal ' + 'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} ' + 'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} ' + 'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n' + '[list-perf] channels notify (no change): cardBuilds=$notifyTiles', + ); + + expect(animatedRows, greaterThan(0)); + expect(down.notFullyDrawnRowFrames, 0); + + await close(tester); + }); +} diff --git a/test/screens/recency_sort_test.dart b/test/screens/recency_sort_test.dart new file mode 100644 index 00000000..66f6659c --- /dev/null +++ b/test/screens/recency_sort_test.dart @@ -0,0 +1,456 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/screens/channels_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/screens/contacts_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_filter/message_filter_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/last_radio_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/utils/contact_filter_types.dart'; + +final _radioKey = Uint8List.fromList(List.generate(32, (i) => 0xA0 + i)); +final _radioHex = pubKeyToHex(_radioKey); + +Uint8List _key(int seed) => + Uint8List.fromList(List.generate(32, (i) => seed + i)); +Uint8List _psk(int seed) => + Uint8List.fromList(List.generate(16, (i) => seed + i)); + +/// Local arrival times, an hour apart. Sender clocks are set far off them. +final _base = DateTime(2026, 11, 20, 12); +DateTime _arrived(int hours) => _base.add(Duration(hours: hours)); +final _farFuture = DateTime(2099); +final _farPast = DateTime(2001); + +ChannelMessage _channelMessage( + int slot, + String text, { + required DateTime sentAt, + required DateTime receivedAt, + String? filterReason, +}) => ChannelMessage( + senderName: 'Bob', + text: text, + timestamp: sentAt, + receivedAt: receivedAt, + isOutgoing: false, + status: ChannelMessageStatus.sent, + channelIndex: slot, + filterReason: filterReason, +); + +Message _directMessage( + Uint8List senderKey, + String text, { + required DateTime sentAt, + required DateTime receivedAt, +}) => Message( + senderKey: senderKey, + text: text, + timestamp: sentAt, + receivedAt: receivedAt, + isOutgoing: false, + status: MessageStatus.delivered, +); + +/// Seeds the remembered radio with channels (slots in map order) and +/// contacts, each with its saved messages. +Future _seed({ + Map Function(int slot)> channelMessages = + const {}, + Map Function(Uint8List key)> contactMessages = const {}, +}) async { + final channelStore = ChannelStore()..setPublicKeyHex = _radioHex; + final messageStore = ChannelMessageStore()..setPublicKeyHex = _radioHex; + final channels = []; + var slot = 0; + for (final entry in channelMessages.entries) { + final channel = Channel(index: slot, name: entry.key, psk: _psk(slot * 16)); + channels.add(channel); + await messageStore.saveChannelMessages( + channel.storageId!, + entry.value(slot), + ); + slot++; + } + await channelStore.saveChannels(channels); + await channelStore.saveSlotChannelIds({ + for (final c in channels) c.index: c.storageId!, + }); + + final contacts = []; + final directStore = MessageStore()..setPublicKeyHex = _radioHex; + var seed = 0x10; + for (final entry in contactMessages.entries) { + final key = _key(seed); + seed += 0x20; + final contact = Contact( + publicKey: key, + name: entry.key, + type: advTypeChat, + pathLength: 1, + path: Uint8List.fromList([0x22]), + lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ); + contacts.add(contact); + await directStore.saveMessages(contact.publicKeyHex, entry.value(key)); + } + await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts(contacts); + + await LastRadioStore().save( + LastRadio( + publicKeyHex: _radioHex, + name: 'Base', + transport: LastRadio.transportBle, + bleRemoteId: 'AA:BB:CC:DD:EE:FF', + savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ), + ); + ChannelMessageStore().forgetArchive(); + MessageStore().forgetArchive(); +} + +/// Restores the seeded radio into a connector that never connects. +Future _connector( + WidgetTester tester, { + MessageFilterService? filter, +}) async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + if (filter != null) { + final retry = MessageRetryService(); + addTearDown(retry.dispose); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(StorageService()), + messageFilterService: filter, + ); + } + await tester.runAsync(connector.restoreLastRadio); + return connector; +} + +Future _pumpScreen( + WidgetTester tester, + MeshCoreConnector connector, + UiViewStateService viewState, + Widget home, +) async { + final storage = StorageService(); + final settings = AppSettingsService(); + await tester.runAsync(settings.loadSettings); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: MessageRetryService()), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: TranslationService(settings)), + ChangeNotifierProvider.value(value: viewState), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ChangeNotifierProvider.value( + value: NetworkMapUploadService( + connector: connector, + settings: settings, + ), + ), + ], + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ), + ); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +/// [names] in the order they appear on screen, top to bottom. +List _screenOrder(WidgetTester tester, List names) { + final top = { + for (final name in names) name: tester.getTopLeft(find.text(name).first).dy, + }; + return [...names]..sort((a, b) => top[a]!.compareTo(top[b]!)); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('recency_sort_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + ChannelMessageStore().forgetArchive(); + MessageStore().forgetArchive(); + }); + + Future pumpChannels( + WidgetTester tester, { + MessageFilterService? filter, + }) async { + final connector = await _connector(tester, filter: filter); + final viewState = UiViewStateService() + ..setChannelsSortOption(ChannelSortOption.latestMessages); + await _pumpScreen(tester, connector, viewState, const ChannelsScreen()); + } + + Future pumpContacts(WidgetTester tester) async { + final connector = await _connector(tester); + final viewState = UiViewStateService() + ..setContactsSortOption(ContactSortOption.recentMessages); + await _pumpScreen(tester, connector, viewState, const ContactsScreen()); + } + + testWidgets('Latest messages sorts channels by local arrival, not sender ' + 'clocks far in the future or past', (tester) async { + await _seed( + channelMessages: { + // Oldest arrival, but the sender's clock is decades ahead. + 'Future Clock': (slot) => [ + _channelMessage( + slot, + 'from the future', + sentAt: _farFuture, + receivedAt: _arrived(0), + ), + ], + // Newest arrival, but the sender's clock is decades behind. + 'Past Clock': (slot) => [ + _channelMessage( + slot, + 'from the past', + sentAt: _farPast, + receivedAt: _arrived(2), + ), + ], + 'Correct Clock': (slot) => [ + _channelMessage( + slot, + 'on time', + sentAt: _arrived(1), + receivedAt: _arrived(1), + ), + ], + 'Quiet': (_) => [], + }, + ); + await pumpChannels(tester); + + expect( + _screenOrder(tester, [ + 'Future Clock', + 'Past Clock', + 'Correct Clock', + 'Quiet', + ]), + ['Past Clock', 'Correct Clock', 'Future Clock', 'Quiet'], + ); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('A newer message hidden by the message filter does not bump ' + 'its channel', (tester) async { + await _seed( + channelMessages: { + 'Spammed': (slot) => [ + _channelMessage( + slot, + 'real message', + sentAt: _arrived(0), + receivedAt: _arrived(0), + ), + _channelMessage( + slot, + 'buy now', + sentAt: _farFuture, + receivedAt: _arrived(5), + filterReason: 'rule', + ), + ], + 'Normal': (slot) => [ + _channelMessage( + slot, + 'hello', + sentAt: _arrived(1), + receivedAt: _arrived(1), + ), + ], + }, + ); + final filter = MessageFilterService(); + addTearDown(filter.dispose); + await tester.runAsync(filter.load); + await pumpChannels(tester, filter: filter); + + expect(_screenOrder(tester, ['Spammed', 'Normal']), ['Normal', 'Spammed']); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('Channels with equal arrival times fall back to name order', ( + tester, + ) async { + List same(int slot) => [ + _channelMessage(slot, 'tie $slot', sentAt: _farFuture, receivedAt: _base), + ]; + await _seed( + channelMessages: {'Charlie': same, 'Alpha': same, 'Bravo': same}, + ); + await pumpChannels(tester); + + expect(_screenOrder(tester, ['Charlie', 'Alpha', 'Bravo']), [ + 'Alpha', + 'Bravo', + 'Charlie', + ]); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('Recent messages sorts contacts by local arrival, not sender ' + 'clocks far in the future or past', (tester) async { + await _seed( + contactMessages: { + 'Fiona': (key) => [ + _directMessage( + key, + 'from the future', + sentAt: _farFuture, + receivedAt: _arrived(0), + ), + ], + 'Paul': (key) => [ + _directMessage( + key, + 'from the past', + sentAt: _farPast, + receivedAt: _arrived(2), + ), + ], + 'Carl': (key) => [ + _directMessage( + key, + 'on time', + sentAt: _arrived(1), + receivedAt: _arrived(1), + ), + ], + }, + ); + await pumpContacts(tester); + + expect(_screenOrder(tester, ['Fiona', 'Paul', 'Carl']), [ + 'Paul', + 'Carl', + 'Fiona', + ]); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('Contacts with equal arrival times fall back to name order', ( + tester, + ) async { + List same(Uint8List key) => [ + _directMessage(key, 'tie', sentAt: _farPast, receivedAt: _base), + ]; + await _seed(contactMessages: {'Zed': same, 'Amy': same, 'Mo': same}); + await pumpContacts(tester); + + expect(_screenOrder(tester, ['Zed', 'Amy', 'Mo']), ['Amy', 'Mo', 'Zed']); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('Contact rows still open after the list was replaced by an ' + 'empty search result', (tester) async { + List none(Uint8List key) => []; + await _seed( + contactMessages: { + 'Amy': none, + 'Ben': none, + 'Cal': none, + 'Dee': none, + 'Eve': none, + }, + ); + final connector = await _connector(tester); + final viewState = UiViewStateService(); + await _pumpScreen(tester, connector, viewState, const ContactsScreen()); + expect(find.text('Amy'), findsOneWidget); + + viewState.setContactsSearchText('no such contact'); + await tester.pumpAndSettle(); + expect(find.text('Amy'), findsNothing); + viewState.setContactsSearchText(''); + await tester.pumpAndSettle(); + + await tester.longPress(find.text('Amy')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.byType(BottomSheet), findsOneWidget); + Navigator.of(tester.element(find.byType(BottomSheet))).pop(); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Amy')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.byType(ChatScreen), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); +} diff --git a/test/services/backup_service_test.dart b/test/services/backup_service_test.dart index e500d290..2584d576 100644 --- a/test/services/backup_service_test.dart +++ b/test/services/backup_service_test.dart @@ -132,6 +132,32 @@ void main() { }, ); + test('keeps contact added times out of app settings', () async { + SharedPreferences.setMockInitialValues({ + 'app_settings': jsonEncode({'theme_mode': 'dark'}), + 'contact_added_at_0011223344': jsonEncode({'aa': 1}), + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + addTearDown(PrefsManager.reset); + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + + final json = await const BackupService().createBackup( + items: {BackupItem.appSettings}, + connector: connector, + settings: AppSettings(), + password: '', + ); + final payload = jsonDecode(json) as Map; + final section = + (payload['sections'] as Map)['appSettings'] + as Map; + final preferences = section['preferences'] as Map; + expect(preferences, contains('app_settings')); + expect(preferences, isNot(contains('contact_added_at_0011223344'))); + }); + test('backs up a sensitive key without unrelated app settings', () async { SharedPreferences.setMockInitialValues({ 'app_settings': jsonEncode({ diff --git a/test/widgets/contact_last_seen_test.dart b/test/widgets/contact_last_seen_test.dart new file mode 100644 index 00000000..9dd73500 --- /dev/null +++ b/test/widgets/contact_last_seen_test.dart @@ -0,0 +1,73 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations_en.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/widgets/contact_visuals.dart'; + +Contact _contact(int seed, {required DateTime lastSeen, DateTime? message}) => + Contact( + publicKey: Uint8List.fromList(List.filled(32, seed)), + name: 'c$seed', + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: lastSeen, + lastMessageAt: message, + ); + +void main() { + final epoch = DateTime.fromMillisecondsSinceEpoch(0); + final now = DateTime.now(); + + test('added time orders a contact the radio has no advert time for', () { + final added = now.subtract(const Duration(minutes: 1)); + final fromCard = _contact(1, lastSeen: epoch); + final heardHourAgo = _contact( + 2, + lastSeen: now.subtract(const Duration(hours: 1)), + ); + final addedAt = {fromCard: added}; + final sorted = [heardHourAgo, fromCard] + ..sort( + (a, b) => resolveContactLastSeen( + b, + addedAt: addedAt[b], + ).compareTo(resolveContactLastSeen(a, addedAt: addedAt[a])), + ); + + expect(resolveContactLastSeen(fromCard, addedAt: added), added); + expect(sorted.first, fromCard); + }); + + test('a real advert time is never replaced by the added time', () { + final advert = now.subtract(const Duration(days: 30)); + final contact = _contact(3, lastSeen: advert); + + expect(resolveContactLastSeen(contact, addedAt: now), advert); + }); + + test('a newer message still wins over the added time', () { + final message = now; + final contact = _contact(4, lastSeen: epoch, message: message); + + expect( + resolveContactLastSeen( + contact, + addedAt: now.subtract(const Duration(hours: 1)), + ), + message, + ); + }); + + test('a contact never heard shows "not heard yet", not decades ago', () { + final l10n = AppLocalizationsEn(); + + expect(formatContactLastSeen(l10n, epoch), l10n.contacts_lastSeenNever); + expect( + resolveContactLastSeen(_contact(5, lastSeen: epoch)), + epoch, + reason: 'display label is driven by the advert/message time only', + ); + }); +} From ffbb61bc3d443cccb33c594840249a3d3cccdc23 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 09/50] Keep chat reading position during sync, selection and app switches - Room chats: keep the visible message in place when synced messages arrive, don't pull a scrolling reader back to the bottom, and keep loaded older pages while the chat is open. - Selecting messages no longer jumps to the newest message. - Focus returning after a sheet, dialog or app switch no longer counts as opening the keyboard. --- documentation/chat-and-messaging.md | 3 +- lib/connector/meshcore_connector.dart | 9 +- lib/helpers/chat_scroll_anchor.dart | 192 ++++++++++ lib/helpers/composer_focus_intent.dart | 52 +++ lib/screens/channel_chat_screen.dart | 32 +- lib/screens/chat_screen.dart | 43 ++- test/helpers/chat_scroll_anchor_test.dart | 92 +++++ test/helpers/composer_focus_intent_test.dart | 78 ++++ .../channel_chat_selection_scroll_test.dart | 323 +++++++++++++++++ .../chat_app_switch_keyboard_test.dart | 281 +++++++++++++++ test/screens/room_chat_scroll_test.dart | 336 ++++++++++++++++++ 11 files changed, 1431 insertions(+), 10 deletions(-) create mode 100644 lib/helpers/chat_scroll_anchor.dart create mode 100644 lib/helpers/composer_focus_intent.dart create mode 100644 test/helpers/chat_scroll_anchor_test.dart create mode 100644 test/helpers/composer_focus_intent_test.dart create mode 100644 test/screens/channel_chat_selection_scroll_test.dart create mode 100644 test/screens/chat_app_switch_keyboard_test.dart create mode 100644 test/screens/room_chat_scroll_test.dart diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 53a47331..d1467d4a 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -35,7 +35,8 @@ From the Contacts screen, tap any Chat-type contact to open the ChatScreen. - Message text follows the system font size (Android/iOS accessibility text size); pinch-to-zoom scales on top of it - **Pinch-to-zoom**: Two-finger zoom (0.8x–1.8x) and double-tap to reset - **Jump to bottom**: Floating button appears when scrolled away from the bottom -- **Lazy loading**: Scrolling to top loads older messages from storage. The newest 200 messages are kept in memory; up to 1000 per conversation are kept in storage +- **Lazy loading**: Scrolling to top loads older messages from storage. The newest 200 messages are kept in memory, plus any older pages loaded while the chat is open; up to 1000 per conversation are kept in storage +- **Reading position**: Near the bottom, the chat follows new messages. Scrolled up, it stays on the messages you are reading while new ones arrive below, such as a room's backlog right after login, and never pulls a scroll in progress back to the bottom - **Arrival order**: Messages are ordered by when they arrived on this device, not by the sender's clock. If a message's time is more than 5 minutes in the future, a small clock-warning icon appears next to its time (the sender's clock is probably wrong); tap it for an explanation ### Input Bar diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index ad9fa57e..89535e4e 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -9191,8 +9191,13 @@ class MeshCoreConnector extends ChangeNotifier { } messages.add(message); - if (messages.length > _messageWindowSize) { - final trimCount = messages.length - _messageWindowSize; + // The open chat keeps the older pages its reader scrolled back to; + // trimming them would pull the history out from under the reader. + final windowSize = pubKeyHex == _activeContactKey + ? MessageStore.maxStoredMessages + : _messageWindowSize; + if (messages.length > windowSize) { + final trimCount = messages.length - windowSize; _messageStore.archive(pubKeyHex, messages.sublist(0, trimCount)); messages.removeRange(0, trimCount); } diff --git a/lib/helpers/chat_scroll_anchor.dart b/lib/helpers/chat_scroll_anchor.dart new file mode 100644 index 00000000..20f489e7 --- /dev/null +++ b/lib/helpers/chat_scroll_anchor.dart @@ -0,0 +1,192 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Keeps the rows a reader is looking at in place when messages are added +/// below them in a reversed chat list. +/// +/// In a `reverse: true` list the newest message is index 0, so every new +/// message moves the older ones up an index. The list keeps layout offsets by +/// index, which leaves the scroll offset unchanged and shifts what is on +/// screen up by the new rows' height. Call [rowsInsertedBelow] while building +/// the list, before it lays out the new rows; [AnchoredChatListView] then +/// scrolls by however far the lowest row on screen moved, in the same layout +/// pass, so nothing visibly jumps. +class ChatScrollAnchor { + _RenderAnchorSliver? _sliver; + _Anchor? _pending; + + /// Notes that [count] rows are being added at index 0, below every row + /// currently laid out, and remembers the lowest row on screen. + void rowsInsertedBelow(int count) { + _pending = null; + final list = _sliver?.child; + if (count <= 0 || list is! RenderSliverMultiBoxAdaptor) return; + if (list.geometry == null) return; + final start = list.constraints.scrollOffset; + final end = start + list.constraints.remainingPaintExtent; + for (var row = list.firstChild; row != null; row = list.childAfter(row)) { + final offset = list.childScrollOffset(row); + if (offset == null || !row.hasSize) continue; + if (offset >= end) break; + if (offset + _extentOf(row, list) > start) { + _pending = _Anchor(list.indexOf(row) + count, offset); + // Rows of equal height would not relayout the list on their own. + _sliver!.markNeedsLayout(); + return; + } + } + } + + /// The scroll correction that puts the remembered row back where it was, + /// or null when none is needed (yet). + double? _correctionAfterLayout( + RenderSliverMultiBoxAdaptor list, + double? listCorrection, + ) { + final pending = _pending; + if (pending == null) return null; + if (listCorrection != null) { + // The list shifts every row by this itself; measure on the next pass. + pending.offset += listCorrection; + return null; + } + double? target; + final first = list.firstChild; + final last = list.lastChild; + if (first == null || last == null) { + _pending = null; + return null; + } + for (RenderBox? row = first; row != null; row = list.childAfter(row)) { + if (list.indexOf(row) == pending.index) { + target = list.childScrollOffset(row); + break; + } + } + if (target != null) { + _pending = null; + final delta = target - pending.offset; + return delta.abs() < 0.5 ? null : delta; + } + // The row is not laid out at this offset: scroll to an estimate of where + // it is, which lays out the rows there, and correct exactly next pass. + if (++pending.passes > 3) { + _pending = null; + return null; + } + final firstIndex = list.indexOf(first); + final lastIndex = list.indexOf(last); + final firstOffset = list.childScrollOffset(first); + final lastOffset = list.childScrollOffset(last); + if (firstOffset == null || lastOffset == null) { + _pending = null; + return null; + } + // Child sizes are off limits here, so space rows by their mean pitch. + final average = lastIndex > firstIndex + ? (lastOffset - firstOffset) / (lastIndex - firstIndex) + : 50.0; + final estimate = pending.index > lastIndex + ? lastOffset + (pending.index - lastIndex) * average + : firstOffset - (firstIndex - pending.index) * average; + final delta = estimate - pending.offset; + pending.offset = estimate; + return delta.abs() < 0.5 ? null : delta; + } + + static double _extentOf(RenderBox row, RenderSliver list) => + list.constraints.axis == Axis.vertical ? row.size.height : row.size.width; +} + +class _Anchor { + _Anchor(this.index, this.offset); + + /// The remembered row's index once the new rows are in. + final int index; + + /// Where the row has to be laid out for the reader to see no movement. + double offset; + int passes = 0; +} + +/// A [ListView.builder] whose on-screen rows stay put when a +/// [ChatScrollAnchor] is told rows were added below them. +class AnchoredChatListView extends ListView { + AnchoredChatListView.builder({ + super.key, + required this.scrollAnchor, + super.reverse, + super.controller, + super.padding, + required super.itemBuilder, + super.itemCount, + }) : super.builder(); + + final ChatScrollAnchor scrollAnchor; + + @override + Widget buildChildLayout(BuildContext context) => _AnchorSliver( + anchor: scrollAnchor, + child: super.buildChildLayout(context), + ); +} + +class _AnchorSliver extends SingleChildRenderObjectWidget { + const _AnchorSliver({required this.anchor, required Widget super.child}); + + final ChatScrollAnchor anchor; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderAnchorSliver(anchor); + + @override + void updateRenderObject( + BuildContext context, + _RenderAnchorSliver renderObject, + ) { + renderObject.anchor = anchor; + } +} + +class _RenderAnchorSliver extends RenderProxySliver { + _RenderAnchorSliver(this._anchor); + + ChatScrollAnchor _anchor; + set anchor(ChatScrollAnchor value) { + if (identical(value, _anchor)) return; + if (attached) { + if (identical(_anchor._sliver, this)) _anchor._sliver = null; + value._sliver = this; + } + _anchor = value; + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _anchor._sliver = this; + } + + @override + void detach() { + if (identical(_anchor._sliver, this)) _anchor._sliver = null; + super.detach(); + } + + @override + void performLayout() { + final list = child!; + list.layout(constraints, parentUsesSize: true); + final listGeometry = list.geometry!; + final correction = list is RenderSliverMultiBoxAdaptor + ? _anchor._correctionAfterLayout( + list, + listGeometry.scrollOffsetCorrection, + ) + : null; + geometry = correction == null + ? listGeometry + : SliverGeometry(scrollOffsetCorrection: correction); + } +} diff --git a/lib/helpers/composer_focus_intent.dart b/lib/helpers/composer_focus_intent.dart new file mode 100644 index 00000000..baa698db --- /dev/null +++ b/lib/helpers/composer_focus_intent.dart @@ -0,0 +1,52 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +/// Tells the user focusing the chat composer apart from Flutter handing focus +/// back after an app switch or after a sheet, dialog or menu closes. +/// +/// On desktop and web the focus manager takes focus off the composer when the +/// window goes inactive and puts it back on resume. That is not the user +/// starting to type, so the chat must not jump to the newest message and lose +/// the reading position. Mobile keeps focus across an app switch. On every +/// platform a sheet, dialog or menu opened over the chat takes focus and the +/// composer gets it back when that closes, which is not a tap either. +class ComposerFocusIntent with WidgetsBindingObserver { + ComposerFocusIntent() { + WidgetsBinding.instance.addObserver(this); + } + + bool _lostWhileAway = false; + bool _lostToRoute = false; + + /// Call from the composer focus node's listener. Returns true when focus + /// was just gained by a tap or by app code, false for a loss of focus or a + /// focus restored on resume or when a route on top closes. + /// + /// [coveredByRoute] is whether the chat's route is no longer the current + /// one (a sheet, dialog or menu is open on top). + bool isUserFocusGain(bool hasFocus, {bool coveredByRoute = false}) { + if (!hasFocus) { + final state = WidgetsBinding.instance.lifecycleState; + _lostWhileAway = state != null && state != AppLifecycleState.resumed; + _lostToRoute = coveredByRoute; + return false; + } + final restored = _lostWhileAway || _lostToRoute; + _lostWhileAway = false; + _lostToRoute = false; + return !restored; + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) return; + // The focus manager observes the lifecycle from app start, so its restore + // is already queued and runs first. Clearing afterwards keeps a focus + // that was not restored (the user clicked elsewhere) from swallowing the + // next real tap on the composer. + scheduleMicrotask(() => _lostWhileAway = false); + } + + void dispose() => WidgetsBinding.instance.removeObserver(this); +} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 67a397ab..43389b60 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -16,6 +16,7 @@ import '../storage/community_store.dart'; import '../utils/platform_info.dart'; import '../helpers/chat_jump.dart'; import '../helpers/chat_scroll_controller.dart'; +import '../helpers/composer_focus_intent.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/gif_helper.dart'; @@ -104,6 +105,7 @@ class _ChannelChatScreenState extends State { final TextEditingController _textController = TextEditingController(); final ChatScrollController _scrollController = ChatScrollController(); final FocusNode _textFieldFocusNode = FocusNode(); + final _composerFocusIntent = ComposerFocusIntent(); ChannelMessage? _replyingToMessage; bool _useReplyRegion = false; final CommunityStore _communityStore = CommunityStore(); @@ -134,6 +136,13 @@ class _ChannelChatScreenState extends State { MeshCoreConnector? _connector; final ChatSendGuard _sendGuard = ChatSendGuard(); bool _channelSkipNextBottomSnap = false; + + /// Newest entry and selection size seen by the last bottom-snap check, so + /// a rebuild that only changed the selection is not mistaken for a new + /// message. + String? _snapNewestEntryId; + int _snapSelectionCount = 0; + String? _unreadDividerMessageId; _TranscriptLayout? _transcriptLayout; ReceivedImageStore? _watchedImageStore; @@ -263,9 +272,12 @@ class _ChannelChatScreenState extends State { } void _onTextFieldFocusChange() { - if (_textFieldFocusNode.hasFocus && mounted) { - _scrollController.handleKeyboardOpen(); - } + if (!mounted) return; + final userFocus = _composerFocusIntent.isUserFocusGain( + _textFieldFocusNode.hasFocus, + coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true), + ); + if (userFocus) _scrollController.handleKeyboardOpen(); } Future _loadOlderMessages() async { @@ -351,6 +363,7 @@ class _ChannelChatScreenState extends State { _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); + _composerFocusIntent.dispose(); _textFieldFocusNode.dispose(); _textController.dispose(); _searchController.dispose(); @@ -923,12 +936,25 @@ class _ChannelChatScreenState extends State { rowCount + (_isLoadingOlder ? 1 : 0); // Auto-scroll to bottom if user is already at bottom + final newestEntryId = layout.ids.first; + final selectionCount = _selectedIds.length; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; + final newEntry = + newestEntryId != _snapNewestEntryId; + final selectionChanged = + selectionCount != _snapSelectionCount; + _snapNewestEntryId = newestEntryId; + _snapSelectionCount = selectionCount; if (_channelSkipNextBottomSnap) { _channelSkipNextBottomSnap = false; return; } + // Picking or clearing messages is not a new + // message: keep the reading position. + if (!newEntry && (_selecting || selectionChanged)) { + return; + } _scrollController.scrollToBottomIfAtBottom(); }); diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index ad509b82..5ce053c8 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -20,7 +20,9 @@ import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; +import '../helpers/chat_scroll_anchor.dart'; import '../helpers/chat_scroll_controller.dart'; +import '../helpers/composer_focus_intent.dart'; import '../helpers/gif_helper.dart'; import '../helpers/ipfs_link_attach_flow.dart'; import '../helpers/contact_share_message.dart'; @@ -94,7 +96,10 @@ class _ChatScreenState extends State { final _messageAreaKey = GlobalKey(); final _textController = TextEditingController(); final _scrollController = ChatScrollController(); + final _scrollAnchor = ChatScrollAnchor(); + ({String id, bool bookmarksOnly})? _newestRow; final _textFieldFocusNode = FocusNode(); + final _composerFocusIntent = ComposerFocusIntent(); final GlobalKey _unreadScrollKey = GlobalKey(); bool _isLoadingOlder = false; bool _showBookmarkedOnly = false; @@ -218,9 +223,12 @@ class _ChatScreenState extends State { } void _onTextFieldFocusChange() { - if (_textFieldFocusNode.hasFocus && mounted) { - _scrollController.handleKeyboardOpen(); - } + if (!mounted) return; + final userFocus = _composerFocusIntent.isUserFocusGain( + _textFieldFocusNode.hasFocus, + coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true), + ); + if (userFocus) _scrollController.handleKeyboardOpen(); } Future _loadOlderMessages() async { @@ -241,6 +249,7 @@ class _ChatScreenState extends State { _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); + _composerFocusIntent.dispose(); _textFieldFocusNode.dispose(); _textController.dispose(); _searchController.dispose(); @@ -678,15 +687,41 @@ class _ChatScreenState extends State { final reversedMessages = visibleMessages.reversed.toList(); final itemCount = reversedMessages.length + (_isLoadingOlder ? 1 : 0); + // A reader scrolled up keeps their place when messages arrive below, as + // a room's backlog does in a burst right after login. + final previous = _newestRow; + final newest = ( + id: reversedMessages.first.messageId, + bookmarksOnly: _showBookmarkedOnly, + ); + _newestRow = newest; + if (previous != null && + previous.bookmarksOnly == newest.bookmarksOnly && + previous.id != newest.id && + _pendingUnreadScrollTarget == null && + _scrollController.showJumpToBottom.value) { + final inserted = reversedMessages.indexWhere( + (m) => m.messageId == previous.id, + ); + if (inserted > 0) _scrollAnchor.rowsInsertedBelow(inserted); + } + // Auto-scroll to bottom if user is already at bottom WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; if (_pendingUnreadScrollTarget != null) return; + // Never take over a drag or fling: during a sync every update would + // pull a reader who starts scrolling up back to the newest message. + if (_scrollController.hasClients && + _scrollController.position.isScrollingNotifier.value) { + return; + } _scrollController.scrollToBottomIfAtBottom(); }); return ChatZoomWrapper( - child: ListView.builder( + child: AnchoredChatListView.builder( + scrollAnchor: _scrollAnchor, reverse: true, // List grows from bottom up controller: _scrollController, padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), diff --git a/test/helpers/chat_scroll_anchor_test.dart b/test/helpers/chat_scroll_anchor_test.dart new file mode 100644 index 00000000..3514cf9e --- /dev/null +++ b/test/helpers/chat_scroll_anchor_test.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/chat_scroll_anchor.dart'; + +/// A reversed chat list of rows with uneven heights. [add] appends newer +/// rows, which land at index 0 below everything else. +class _Harness { + final controller = ScrollController(); + final anchor = ChatScrollAnchor(); + var items = List.generate(100, (i) => 'm$i'); + late StateSetter _setState; + + Widget build() => MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + _setState = setState; + final rows = items.reversed.toList(); + return AnchoredChatListView.builder( + scrollAnchor: anchor, + reverse: true, + controller: controller, + padding: const EdgeInsets.all(16), + itemCount: rows.length, + itemBuilder: (context, i) => SizedBox( + height: 40.0 + (int.parse(rows[i].substring(1)) % 5) * 20, + child: Text(rows[i]), + ), + ); + }, + ), + ), + ); + + void add(int count, {bool anchored = true}) { + _setState(() { + final start = items.length; + items = [...items, for (var i = 0; i < count; i++) 'n${start + i}']; + if (anchored) anchor.rowsInsertedBelow(count); + }); + } +} + +void main() { + for (final count in [1, 3, 30, 300]) { + testWidgets('$count rows added below keep the visible rows in place', ( + tester, + ) async { + final harness = _Harness(); + addTearDown(harness.controller.dispose); + await tester.pumpWidget(harness.build()); + harness.controller.jumpTo(2000); + await tester.pump(); + final row = find.text('m72'); + expect(row, findsOneWidget); + final before = tester.getTopLeft(row).dy; + + harness.add(count); + await tester.pump(); + + expect(row, findsOneWidget); + expect(tester.getTopLeft(row).dy, moreOrLessEquals(before)); + expect(harness.controller.position.pixels, greaterThan(2000)); + }); + } + + testWidgets('without the anchor the rows on screen move', (tester) async { + final harness = _Harness(); + addTearDown(harness.controller.dispose); + await tester.pumpWidget(harness.build()); + harness.controller.jumpTo(2000); + await tester.pump(); + final before = tester.getTopLeft(find.text('m72')).dy; + + harness.add(3, anchored: false); + await tester.pump(); + + expect(tester.getTopLeft(find.text('m72')).dy, isNot(before)); + }); + + testWidgets('a list at the bottom is left at the bottom', (tester) async { + final harness = _Harness(); + addTearDown(harness.controller.dispose); + await tester.pumpWidget(harness.build()); + + harness.add(3, anchored: false); + await tester.pump(); + + expect(harness.controller.position.pixels, 0); + expect(find.text('n102'), findsOneWidget); + }); +} diff --git a/test/helpers/composer_focus_intent_test.dart b/test/helpers/composer_focus_intent_test.dart new file mode 100644 index 00000000..e1705d42 --- /dev/null +++ b/test/helpers/composer_focus_intent_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/composer_focus_intent.dart'; + +void _setLifecycle(WidgetTester tester, List states) { + for (final state in states) { + tester.binding.handleAppLifecycleStateChanged(state); + } +} + +const _away = [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, +]; +const _back = [ + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, +]; + +void main() { + testWidgets('focus gained while in the foreground is user focus', ( + tester, + ) async { + final intent = ComposerFocusIntent(); + addTearDown(intent.dispose); + + expect(intent.isUserFocusGain(true), isTrue); + expect(intent.isUserFocusGain(false), isFalse); + expect(intent.isUserFocusGain(true), isTrue); + }); + + testWidgets('focus lost while away and given back on resume is not', ( + tester, + ) async { + final intent = ComposerFocusIntent(); + addTearDown(intent.dispose); + + expect(intent.isUserFocusGain(true), isTrue); + _setLifecycle(tester, _away.sublist(0, 1)); + expect(intent.isUserFocusGain(false), isFalse); + _setLifecycle(tester, [..._away.sublist(1), ..._back]); + // The restore lands before the resume microtask clears the flag. + expect(intent.isUserFocusGain(true), isFalse); + // The next tap counts again. + expect(intent.isUserFocusGain(false), isFalse); + expect(intent.isUserFocusGain(true), isTrue); + }); + + testWidgets('focus not restored on resume does not swallow the next tap', ( + tester, + ) async { + final intent = ComposerFocusIntent(); + addTearDown(intent.dispose); + + _setLifecycle(tester, _away.sublist(0, 1)); + expect(intent.isUserFocusGain(false), isFalse); + _setLifecycle(tester, [..._away.sublist(1), ..._back]); + await tester.pump(); // Resume microtasks run; nothing restored focus. + + expect(intent.isUserFocusGain(true), isTrue); + }); + + testWidgets('focus given back when a sheet or dialog closes is not', ( + tester, + ) async { + final intent = ComposerFocusIntent(); + addTearDown(intent.dispose); + + expect(intent.isUserFocusGain(true), isTrue); + expect(intent.isUserFocusGain(false, coveredByRoute: true), isFalse); + expect(intent.isUserFocusGain(true), isFalse); + // Losing focus with nothing on top, then tapping, counts again. + expect(intent.isUserFocusGain(false), isFalse); + expect(intent.isUserFocusGain(true), isTrue); + }); +} diff --git a/test/screens/channel_chat_selection_scroll_test.dart b/test/screens/channel_chat_selection_scroll_test.dart new file mode 100644 index 00000000..39c12447 --- /dev/null +++ b/test/screens/channel_chat_selection_scroll_test.dart @@ -0,0 +1,323 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/helpers/chat_scroll_controller.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; + +/// Selecting messages must not move the transcript: picking, selecting all +/// and clearing are not new messages, and the composer getting its focus back +/// when the action sheet closes is not the user opening the keyboard. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('selection_scroll_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + testWidgets('selecting from far up the history keeps the scroll offset', ( + tester, + ) async { + _useSmallView(tester); + await _pumpChannelChat(tester); + + // The composer has focus (keyboard open) while the user reads back. + await tester.tap(find.byType(TextField).last); + await _settle(tester); + await _scrollTo(tester, 600); + + await _startSelection(tester); + expect(find.text('1 selected'), findsOneWidget); + expect(_position(tester).pixels, 600); + + // Select a few more. + for (var i = 0; i < 2; i++) { + await _tapVisibleUnselected(tester); + expect(_position(tester).pixels, 600); + } + expect(find.text('3 selected'), findsOneWidget); + + // Select all from the selection app bar's menu. + await tester.tap(find.byIcon(Icons.more_vert)); + await _settle(tester); + await tester.tap(find.text('Select all')); + await _settle(tester); + expect(find.byIcon(Icons.radio_button_unchecked), findsNothing); + expect(_position(tester).pixels, 600); + + // End selection. + await tester.tap(find.byTooltip('Clear selection')); + await _settle(tester); + expect(find.byTooltip('Clear selection'), findsNothing); + expect(_position(tester).pixels, 600); + + await _tearDown(tester); + }); + + testWidgets('selection near the bottom does not snap to the newest message', ( + tester, + ) async { + _useSmallView(tester); + await _pumpChannelChat(tester); + await _scrollTo(tester, 600); + await _startSelection(tester); + + // Inside the "at bottom" threshold, where a new message would snap. + await _scrollTo(tester, 60); + + await _tapVisibleUnselected(tester); + expect(find.text('2 selected'), findsOneWidget); + expect(_position(tester).pixels, 60); + + await tester.tap(find.byTooltip('Clear selection')); + await _settle(tester); + expect(_position(tester).pixels, 60); + + await _tearDown(tester); + }); + + testWidgets('incoming messages during selection behave as before', ( + tester, + ) async { + _useSmallView(tester); + final connector = await _pumpChannelChat(tester); + final channelIndex = connector.channels[0].index; + + await _scrollTo(tester, 600); + await _startSelection(tester); + + // Reading back: a new message must not pull the view down. + _receive(connector, channelIndex, 'Arrives while reading back'); + await _settle(tester); + expect(find.text('1 selected'), findsOneWidget); + expect(_position(tester).pixels, greaterThanOrEqualTo(600)); + + // Near the bottom: a new message still scrolls into view. + await _scrollTo(tester, 60); + _receive(connector, channelIndex, 'Arrives while at the bottom'); + await _settle(tester); + expect(find.text('1 selected'), findsOneWidget); + expect(_position(tester).pixels, 0); + + await _tearDown(tester); + }); +} + +void _useSmallView(WidgetTester tester) { + tester.view.physicalSize = const Size(400, 700); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); +} + +ScrollPosition _position(WidgetTester tester) => tester + .widget( + find.byWidgetPredicate( + (w) => w is ListView && w.controller is ChatScrollController, + ), + ) + .controller! + .position; + +/// Jumps to [pixels] from the bottom. Jumps twice: the first lays out +/// messages whose heights were only estimated, which can correct the offset. +Future _scrollTo(WidgetTester tester, double pixels) async { + for (var i = 0; i < 2; i++) { + _position(tester).jumpTo(pixels); + await _settle(tester); + } + expect(_position(tester).pixels, pixels); +} + +/// Long-presses a message in the middle of the screen and picks "Select +/// messages" from its action sheet. The long-press callback is invoked +/// directly: in tests a real long press on the bubble text starts text +/// selection instead. +Future _startSelection(WidgetTester tester) async { + final detector = find + .byWidgetPredicate((w) => w is GestureDetector && w.onLongPress != null) + .evaluate() + .firstWhere((e) { + final box = e.renderObject! as RenderBox; + final y = box.localToGlobal(box.size.center(Offset.zero)).dy; + return y > 150 && y < 450; + }); + (detector.widget as GestureDetector).onLongPress!(); + await _settle(tester); + await tester.ensureVisible(find.text('Select messages')); + await tester.pump(); + await tester.tap(find.text('Select messages')); + await _settle(tester); +} + +/// Taps the selection circle of an unselected message on screen. +Future _tapVisibleUnselected(WidgetTester tester) async { + final list = tester.getRect( + find.byWidgetPredicate( + (w) => w is ListView && w.controller is ChatScrollController, + ), + ); + final circle = find + .byIcon(Icons.radio_button_unchecked) + .evaluate() + .firstWhere((e) { + final box = e.renderObject! as RenderBox; + return list.contains(box.localToGlobal(box.size.center(Offset.zero))); + }); + await tester.tap(find.byWidget(circle.widget)); + await _settle(tester); +} + +var _received = 0; + +void _receive(MeshCoreConnector connector, int channelIndex, String text) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channelIndex, + sender: 'Alice', + message: text, + timestampSecs: + DateTime.now().millisecondsSinceEpoch ~/ 1000 + 60 * ++_received, + ), + ); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +/// One review-radio connection shared by the tests: reconnecting it in the +/// same run does not resend the channel list. +(MeshCoreConnector, List)? _shared; + +/// Connects the review radio (once), seeds a long history and shows the +/// first channel's chat. +Future _pumpChannelChat(WidgetTester tester) async { + final firstRun = _shared == null; + final (connector, providers) = _shared ??= await _connect(tester); + if (firstRun) { + final base = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 10000; + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: connector.channels[0].index, + sender: 'Alice', + message: 'History message $i with enough words to wrap a line', + timestampSecs: base + i * 60, + ), + ); + } + } + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: ChannelChatScreen(channel: connector.channels[0]), + ), + ), + ); + await _settle(tester); + return connector; +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || connector.channels.length < 2) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels.length, greaterThanOrEqualTo(2)); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/screens/chat_app_switch_keyboard_test.dart b/test/screens/chat_app_switch_keyboard_test.dart new file mode 100644 index 00000000..f586ad68 --- /dev/null +++ b/test/screens/chat_app_switch_keyboard_test.dart @@ -0,0 +1,281 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/chat_composer.dart'; + +const _screen = Size(400, 800); +const _keyboard = 300.0; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('app_switch_kb_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + // Android/iOS keep focus on the composer across an app switch; the OS may + // or may not bring the keyboard back. Layout must follow the reported + // inset, and the draft, focus and reading position must survive. + for (final keyboardBack in [true, false]) { + for (final atBottom in [false, true]) { + final keyboard = keyboardBack ? 'keyboard back' : 'OS closed keyboard'; + final reading = atBottom ? 'at the bottom' : 'reading history'; + testWidgets('mobile app switch: $keyboard, $reading', (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpChannelChat(tester); + await tester.tap(_composerField); + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard); + await _settle(tester); + await tester.enterText(_composerField, 'half written'); + await _settle(tester); + + if (!atBottom) { + await tester.drag(find.byType(ListView).first, const Offset(0, 300)); + await _settle(tester); + } + final offsetBefore = _list(tester).position.pixels; + expect(offsetBefore, atBottom ? 0 : greaterThan(100)); + expect(_composerBottom(tester), closeTo(_screen.height - _keyboard, 1)); + + // Switch away; the OS hides the keyboard while the app is hidden. + _goBackground(tester); + tester.view.viewInsets = FakeViewPadding.zero; + await tester.pump(); + + _goForeground(tester); + if (keyboardBack) { + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard); + } + await _settle(tester); + + final inset = keyboardBack ? _keyboard : 0.0; + expect(_composerBottom(tester), closeTo(_screen.height - inset, 1)); + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_composer(tester).controller.text, 'half written'); + expect(_list(tester).position.pixels, closeTo(offsetBefore, 1)); + + // Tapping the field opens the keyboard again above the composer. + await tester.tap(_composerField); + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard); + await _settle(tester); + expect(_composerBottom(tester), closeTo(_screen.height - _keyboard, 1)); + expect(_composer(tester).controller.text, 'half written'); + + await _tearDown(tester); + }); + } + } + + // Desktop and web take focus away when the window goes inactive and restore + // it on resume. That restore used to count as "keyboard opened" and jumped + // the transcript to the newest message. + testWidgets('desktop app switch keeps the reading position', (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpChannelChat(tester); + await tester.tap(_composerField); + await _settle(tester); + await tester.enterText(_composerField, 'half written'); + // Mouse-wheel up through the history; the composer keeps focus. + _list(tester).jumpTo(300); + await _settle(tester); + + _goBackground(tester); + await tester.pump(); + expect(_composer(tester).focusNode.hasFocus, isFalse); + _goForeground(tester); + await _settle(tester); + + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_composer(tester).controller.text, 'half written'); + expect(_list(tester).position.pixels, closeTo(300, 1)); + + // A real click on the composer still jumps to the newest message. + _composer(tester).focusNode.unfocus(); + await _settle(tester); + await tester.tap(_composerField); + await _settle(tester); + expect(_list(tester).position.pixels, 0); + + await _tearDown(tester); + }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); +} + +final _composerField = find.descendant( + of: find.byType(ChatComposer), + matching: find.byType(EditableText), +); + +EditableText _composer(WidgetTester tester) => + tester.widget(_composerField); + +void _goBackground(WidgetTester tester) { + for (final state in const [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + ]) { + tester.binding.handleAppLifecycleStateChanged(state); + } +} + +void _goForeground(WidgetTester tester) { + for (final state in const [ + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ]) { + tester.binding.handleAppLifecycleStateChanged(state); + } +} + +ScrollController _list(WidgetTester tester) => + tester.widget(find.byType(ListView).first).controller!; + +double _composerBottom(WidgetTester tester) => + tester.getBottomLeft(find.byType(ChatComposer)).dy; + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +(MeshCoreConnector, List)? _shared; + +Future _pumpChannelChat(WidgetTester tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: ChannelChatScreen(channel: connector.channels[0]), + ), + ), + ); + await _settle(tester); + return connector; +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while (connector.channels.isEmpty && DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + // Enough history that the transcript scrolls with or without a keyboard. + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: 0, + sender: 'Tester', + message: 'History line number $i about the weather on the hill', + timestampSecs: now - 4000 + i, + ), + ); + } + while (connector.getChannelMessages(connector.channels[0]).length < 40 && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels, isNotEmpty); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/screens/room_chat_scroll_test.dart b/test/screens/room_chat_scroll_test.dart new file mode 100644 index 00000000..ffc9bce9 --- /dev/null +++ b/test/screens/room_chat_scroll_test.dart @@ -0,0 +1,336 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/unread_divider.dart'; + +/// Room chats receive their backlog as a burst of messages right after login. +/// These tests feed such a burst into an open room chat and check that the +/// reader's place holds, and that opening the chat still lands where the +/// unread preference says. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('room_scroll_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + setUp(() { + final view = + TestWidgetsFlutterBinding.instance.platformDispatcher.views.first; + view.physicalSize = const Size(400, 800); + view.devicePixelRatio = 1.0; + }); + tearDown( + () => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first + .reset(), + ); + + testWidgets('a sync burst keeps the reader on the message they were ' + 'reading', (tester) async { + final (connector, room) = await _openRoom(tester, history: 60); + final controller = _listController(tester); + + controller.jumpTo(1500); + await _settle(tester); + final reading = _lowestVisibleMessage(tester); + final before = tester.getTopLeft(reading).dy; + + // One at a time, as the radio hands queued posts over, then a batch + // that lands within a single frame. + for (var i = 0; i < 5; i++) { + _receive(connector, room, 'synced single $i'); + await tester.pump(); + } + for (var i = 0; i < 25; i++) { + _receive(connector, room, 'synced batch $i'); + } + await _settle(tester); + + expect(connector.getMessages(room), hasLength(90)); + expect(reading, findsOneWidget); + expect(tester.getTopLeft(reading).dy, moreOrLessEquals(before)); + await _tearDown(tester); + }); + + testWidgets('a reader starting to scroll up during sync is not pulled ' + 'back to the newest message', (tester) async { + final (connector, room) = await _openRoom(tester, history: 60); + final controller = _listController(tester); + expect(controller.position.pixels, 0); + + final gesture = await tester.startGesture(const Offset(200, 400)); + for (var i = 0; i < 12; i++) { + await gesture.moveBy(const Offset(0, 25)); + _receive(connector, room, 'during drag $i'); + await tester.pump(const Duration(milliseconds: 16)); + } + await gesture.up(); + await _settle(tester); + + expect(connector.getMessages(room), hasLength(72)); + expect(controller.position.pixels, greaterThan(200)); + await _tearDown(tester); + }); + + testWidgets('first open at the bottom still follows new messages', ( + tester, + ) async { + final (connector, room) = await _openRoom(tester, history: 60); + final controller = _listController(tester); + expect(controller.position.pixels, 0); + + for (var i = 0; i < 5; i++) { + _receive(connector, room, 'newest $i'); + await tester.pump(); + } + await _settle(tester); + + expect(connector.getMessages(room), hasLength(65)); + expect(controller.position.pixels, 0); + expect(find.text('newest 4', findRichText: true), findsOneWidget); + await _tearDown(tester); + }); + + testWidgets('jump to oldest unread lands on the divider and holds through ' + 'a sync burst', (tester) async { + final (connector, room) = await _openRoom( + tester, + history: 60, + unread: 30, + jumpToOldestUnread: true, + ); + final controller = _listController(tester); + // history 30 is the oldest of the 30 unread messages. + final anchor = find.text('history 30', findRichText: true); + expect(anchor, findsOneWidget); + expect(find.byType(UnreadDivider), findsOneWidget); + expect(controller.position.pixels, greaterThan(100)); + final before = tester.getTopLeft(anchor).dy; + expect(before, inInclusiveRange(0, 800)); + + for (var i = 0; i < 10; i++) { + _receive(connector, room, 'after open $i'); + await tester.pump(); + } + await _settle(tester); + expect(connector.getMessages(room), hasLength(70)); + expect(tester.getTopLeft(anchor).dy, moreOrLessEquals(before)); + await _tearDown(tester); + }); + + testWidgets('older pages loaded in an open chat survive new messages', ( + tester, + ) async { + final (connector, room) = await _openRoom(tester, history: 230); + final window = connector.getMessages(room); + expect(window, hasLength(200)); + final older = await tester.runAsync( + () => connector.loadOlderMessages(room.publicKeyHex), + ); + expect(older, isNotEmpty); + final paged = connector.getMessages(room).length; + expect(paged, greaterThan(200)); + + _receive(connector, room, 'arrives while reading history'); + await _settle(tester); + expect(connector.getMessages(room), hasLength(paged + 1)); + expect(connector.getMessages(room).first.text, older!.first.text); + await _tearDown(tester); + }); + + testWidgets('an open chat still caps its window at the stored limit', ( + tester, + ) async { + final (connector, room) = await _openRoom(tester, history: 0); + for (var i = 0; i < MessageStore.maxStoredMessages + 10; i++) { + _receive(connector, room, 'flood $i'); + } + final window = connector.getMessages(room); + expect(window, hasLength(MessageStore.maxStoredMessages)); + expect(window.last.text, 'flood ${MessageStore.maxStoredMessages + 9}'); + await _tearDown(tester); + }); +} + +var _timestamp = 1700000000; + +void _receive(MeshCoreConnector connector, Contact room, String text) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: room.publicKey, + text: text, + timestampSecs: _timestamp++, + ), + ); +} + +ScrollController _listController(WidgetTester tester) => tester + .widget(find.byWidgetPredicate((w) => w is ListView)) + .controller!; + +/// The on-screen history message nearest the bottom of the list. +Finder _lowestVisibleMessage(WidgetTester tester) { + Finder? best; + var bestY = double.negativeInfinity; + for (var i = 0; i < 60; i++) { + final finder = find.text('history $i', findRichText: true); + if (finder.evaluate().isEmpty) continue; + final y = tester.getTopLeft(finder).dy; + if (y > 80 && y < 600 && y > bestY) { + bestY = y; + best = finder; + } + } + expect(best, isNotNull, reason: 'a history message should be on screen'); + return best!; +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +/// Connects the review radio, gives its room [history] messages and opens +/// the room chat as a login does, with [unread] of them unread. +Future<(MeshCoreConnector, Contact)> _openRoom( + WidgetTester tester, { + required int history, + int unread = 0, + bool jumpToOldestUnread = false, +}) async { + final (connector, providers, settings) = _shared ??= await _connect(tester); + await tester.runAsync( + () => settings.setJumpToOldestUnread(jumpToOldestUnread), + ); + final room = connector.contacts.firstWhere((c) => c.type == advTypeRoom); + connector.clearMessagesForContact(room); + await tester.runAsync(() => connector.flushPendingWrites()); + for (var i = 0; i < history; i++) { + _receive(connector, room, 'history $i'); + } + expect(connector.getMessages(room), hasLength(history.clamp(0, 200))); + connector.markContactRead(room.publicKeyHex); + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: ChatScreen(contact: room, initialUnreadCount: unread), + ), + ), + ); + await _settle(tester); + return (connector, room); +} + +/// One review-radio connection shared by the tests: reconnecting it in the +/// same run does not resend the contact list. +(MeshCoreConnector, List, AppSettingsService)? _shared; + +Future<(MeshCoreConnector, List, AppSettingsService)> +_connect(WidgetTester tester) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while (!connector.contacts.any((c) => c.type == advTypeRoom) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + // Let the connect-time message sync finish so test frames are not held. + await Future.delayed(const Duration(milliseconds: 500)); + }); + expect(connector.contacts.any((c) => c.type == advTypeRoom), isTrue); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + settings, + ); +} From fc5f7eb5164b29fe1b841fb31b43c00aa301c61e Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 10/50] Add in-chat compression selector A Compression: Off / SMAZ / Cyr2Lat strip at the top of DM and channel chats opens one sheet that explains each mode and holds the Cyr2Lat profile picker. New connector setters keep the modes mutually exclusive. The old switches are removed from contact settings and the channel edit sheet, so editing a channel no longer overwrites its compression setting. --- documentation/README.md | 2 +- documentation/additional-features.md | 31 +- documentation/channels.md | 6 +- documentation/chat-and-messaging.md | 6 +- documentation/design.md | 3 +- documentation/settings.md | 2 +- lib/connector/meshcore_connector.dart | 165 ++++---- lib/l10n/app_en.arb | 27 +- lib/l10n/app_localizations.dart | 102 +++-- lib/l10n/app_localizations_bg.dart | 61 ++- lib/l10n/app_localizations_cs.dart | 60 ++- lib/l10n/app_localizations_de.dart | 61 ++- lib/l10n/app_localizations_en.dart | 60 ++- lib/l10n/app_localizations_es.dart | 60 ++- lib/l10n/app_localizations_fr.dart | 61 ++- lib/l10n/app_localizations_hu.dart | 60 ++- lib/l10n/app_localizations_it.dart | 60 ++- lib/l10n/app_localizations_ja.dart | 59 ++- lib/l10n/app_localizations_ko.dart | 59 ++- lib/l10n/app_localizations_nl.dart | 60 ++- lib/l10n/app_localizations_pl.dart | 60 ++- lib/l10n/app_localizations_pt.dart | 73 ++-- lib/l10n/app_localizations_ru.dart | 60 ++- lib/l10n/app_localizations_sk.dart | 60 ++- lib/l10n/app_localizations_sl.dart | 60 ++- lib/l10n/app_localizations_sv.dart | 60 ++- lib/l10n/app_localizations_uk.dart | 60 ++- lib/l10n/app_localizations_zh.dart | 59 ++- lib/models/chat_compression_mode.dart | 3 + lib/screens/channel_chat_screen.dart | 28 ++ lib/screens/channels_screen.dart | 93 +---- lib/screens/chat_screen.dart | 120 ++---- lib/widgets/chat_compression_selector.dart | 356 ++++++++++++++++++ lib/widgets/mesh_nav_tile.dart | 29 +- test/connector/channel_slot_map_test.dart | 5 +- .../connector/chat_compression_mode_test.dart | 163 ++++++++ test/screens/offline_mode_test.dart | 246 ++++++++++++ .../chat_compression_selector_test.dart | 313 +++++++++++++++ 38 files changed, 2302 insertions(+), 551 deletions(-) create mode 100644 lib/models/chat_compression_mode.dart create mode 100644 lib/widgets/chat_compression_selector.dart create mode 100644 test/connector/chat_compression_mode_test.dart create mode 100644 test/widgets/chat_compression_selector_test.dart diff --git a/documentation/README.md b/documentation/README.md index 64533529..8e392098 100644 --- a/documentation/README.md +++ b/documentation/README.md @@ -20,7 +20,7 @@ MeshCore Open is an open-source Flutter client for MeshCore LoRa mesh networking 7. [Settings](settings.md) - Device settings, app settings, radio configuration, backup/restore, and exports 8. [Notifications](notifications.md) - System notifications, replies from watches and Android Auto, unread badges, and notification preferences 9. [Repeater Management](repeater-management.md) - Repeater hub, status, CLI, telemetry, and neighbors -10. [Additional Features](additional-features.md) - GIF picker, localization, debug logs, SMAZ compression, and more +10. [Additional Features](additional-features.md) - GIF picker, localization, debug logs, SMAZ and Cyr2Lat compression, and more 11. [Routing Paths](routing-paths.md) - Path encoding, validation, device capability detection, and storage 12. [BLE Protocol & Data Layer](ble-protocol.md) - Technical reference for the communication protocol and data architecture 13. [Regions](regions.md) - App and radio default regions, unscoped sends, message labels, and reply regions diff --git a/documentation/additional-features.md b/documentation/additional-features.md index b160577d..3b984c8c 100644 --- a/documentation/additional-features.md +++ b/documentation/additional-features.md @@ -58,21 +58,28 @@ A list of nodes heard passively over the air but not yet added as contacts. Each --- -## SMAZ Compression +## Compression (SMAZ and Cyr2Lat) -### What It Is -An optional per-contact and per-channel text compression feature using the SMAZ algorithm (optimized for short English text). +### Where to Find It +Every open direct-message and channel chat shows **Compression: Off**, **Compression: SMAZ** or **Compression: Cyr2Lat** in a strip just below the app bar, above the messages. Tap it to open one sheet with the three choices and what each does. The choice applies to that contact or channel only and is saved on the phone, so it can be changed while the radio is offline. A channel that has not synced from the radio yet has no saved identity, so the strip is disabled and says why. -### How to Enable -- **Per contact**: Chat screen → overflow menu → Contact Settings → toggle "SMAZ compression" -- **Per channel**: Long-press channel → Edit → toggle "SMAZ compression" +Only one mode is active per chat. Choosing SMAZ turns Cyr2Lat off and the other way round. Off and SMAZ close the sheet once saved; Cyr2Lat keeps it open to show its profile picker. If saving fails, the sheet says so and keeps showing the saved choice. -### How It Works -- When enabled, compression is applied using a "compress only if smaller" strategy — the message is only transmitted compressed if the encoded result is actually shorter than the original. Otherwise, the original text is sent uncompressed -- Compressed messages are transmitted with a `s:` prefix followed by base64-encoded data -- Recipients using MeshCore Open will decompress automatically. **Recipients using other software** that is not SMAZ-aware will see garbled `s:...` text -- The codec operates on ASCII. Non-ASCII / non-English text generally does not benefit from compression and may even expand. Best suited for short English messages -- Disabled by default +### Off +Sends your text exactly as typed. Every app can read it. + +### SMAZ (lossless) +- Compresses with the SMAZ short-text dictionary (optimized for short English text) +- "Compress only if smaller": a message is sent compressed only when the encoded result is shorter. Otherwise the original text is sent, so turning SMAZ on does not compress every message +- Compressed messages are sent as `s:` followed by base64 data. MeshCore Open decodes them back to exactly the original text. **Apps that do not understand SMAZ** show the `s:...` text instead +- The codec works on ASCII. Non-English text rarely benefits and may grow + +### Cyr2Lat (character substitution) +- Replaces some Cyrillic letters with lookalike Latin ones (for example `А→A`, `З→3`, `Ь→b`). Many Cyrillic letters take two bytes in UTF-8 and Latin ones take one, so some Cyrillic messages get shorter +- Not lossless: the exact characters change. Recipients need nothing special to read the result, but copying, searching, names and technical text may behave differently. Your own sent messages appear in the converted form +- The replacements come from a Cyr2Lat profile. Pick the chat's profile in the same sheet; without one, the app-wide profile from App Settings → Cyr2Lat is used. Not useful for English text + +Both are off by default. Settings saved before this selector existed are kept. --- diff --git a/documentation/channels.md b/documentation/channels.md index a8ce6641..3f682c25 100644 --- a/documentation/channels.md +++ b/documentation/channels.md @@ -61,7 +61,7 @@ Name limits count the `#` and any community prefix, so the name stored on the ra | Action | Description | |---|---| -| Edit | Change name, PSK (with a dice icon to generate a random PSK), SMAZ compression toggle (compresses outgoing messages to allow longer text within the byte limit), Cyr2Lat encoding toggle (transliterates Cyrillic to Latin for compatibility), or "Enable URL images" toggle (previews image links; requires internet) | +| Edit | Change name, PSK (with a dice icon to generate a random PSK), or "Enable URL images" toggle (previews image links; requires internet). Compression is chosen inside the channel chat (see below) | | Mute / Unmute | Toggle push notification suppression for this channel | | Delete | Remove the channel from the device and delete its messages, settings, region and images (confirmation required) | @@ -82,6 +82,10 @@ Tap a channel card to open the channel chat screen. - Overflow menu (⋮) → **Show bookmarks** toggles the channel's bookmarked-message filter; the bookmark icon is filled while active and outlined while inactive. - Overflow menu (⋮) → **Chat background**: a color or picture, with a fade slider, behind this channel only. See [Chat backgrounds](themes.md#chat-backgrounds). Holiday greetings in new messages play a short animation, as in [direct chat](chat-and-messaging.md#message-list) +### Compression Strip + +Below the app bar, above the messages, the same strip as in [direct chats](chat-and-messaging.md#compression-strip) shows and changes this channel's compression: Off, SMAZ or Cyr2Lat. It is stored with the channel's key, so every slot holding that channel shares it, and it can be changed offline. Until the channel has synced from the radio the strip is disabled and says why. See [Compression](additional-features.md#compression-smaz-and-cyr2lat). + ### Message Display - Reverse-scrolling list (newest at bottom) diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 53a47331..fbca33dc 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -20,7 +20,11 @@ From the Contacts screen, tap any Chat-type contact to open the ChatScreen. - **Subtitle**: Current routing path label (e.g., "2 hops", "flood (auto)", "direct (forced)") and unread count. Tapping the subtitle shows the full path details. - **Action buttons**: - **Search** (magnifier icon): Replaces the title with a search field and lists every message in this conversation's full history whose text (or translation) contains the typed word, newest first, with matches highlighted. Channel search also matches sender names and skips messages caught by the [message filter](message-filter.md). Back, Esc or the arrow closes search. Channel chats have the same button. - - **Overflow menu** (⋮ icon): Contains Routing, Info, Telemetry, Settings, Chat background, Clear Chat, and Remove from contacts (rooms also have Room Server Management). Routing opens the routing sheet where you can switch between Auto, Direct, and Flood routing and manage recent paths (hop count, round-trip time, age, success count, color-coded by repeater). Info shows a dialog with contact type, path, GPS coordinates, and public key. Chat background sets a color or picture (with a fade slider) behind this chat only; see [Chat backgrounds](themes.md#chat-backgrounds). + - **Overflow menu** (⋮ icon): Contains Routing, Info, Telemetry, Settings (link images and telemetry permissions), Chat background, Clear Chat, and Remove from contacts (rooms also have Room Server Management). Routing opens the routing sheet where you can switch between Auto, Direct, and Flood routing and manage recent paths (hop count, round-trip time, age, success count, color-coded by repeater). Info shows a dialog with contact type, path, GPS coordinates, and public key. Chat background sets a color or picture (with a fade slider) behind this chat only; see [Chat backgrounds](themes.md#chat-backgrounds). + +### Compression Strip + +Below the app bar, above the messages, a strip shows **Compression: Off**, **SMAZ** or **Cyr2Lat** for this contact. Tap it to choose a mode in one sheet that explains each: SMAZ is lossless but needs a SMAZ-aware app on the other end and is only used when it makes a message smaller; Cyr2Lat swaps some Cyrillic letters for lookalike Latin ones, stays readable everywhere, but changes the exact characters, using the chosen Cyr2Lat profile. The setting is saved on the phone and can be changed offline. Channel chats show the same strip. See [Compression](additional-features.md#compression-smaz-and-cyr2lat). ### Message List diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..8483c73d 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -117,7 +117,8 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Label above a group | `SectionHeader(label, trailing:)` | Upper-cases for you; pass the normal-case l10n string | | Settings navigation row | `MeshNavTile` | `onTap: null` dims it to 50 % and reports it as disabled; use `subtitle` to say why | | Settings switch | `SwitchListTile` inside `MeshSettingsTileTheme` | Wrap the settings screen body once in `MeshSettingsTileTheme` | -| Radio-style choice in a sheet | `MeshSheetOption` | Used by the language picker and map time filter | +| Radio-style choice in a sheet | `MeshSheetOption` | Used by the language picker, map time filter and compression sheet. Optional `subtitle` explains the option; `onTap: null` disables it. Selected rows show a filled radio icon **and** a bold title, with `selected` semantics | +| Per-chat setting at the top of a chat | Full-width strip under the app bar, above the transcript (`ChatCompressionSelector` in `widgets/chat_compression_selector.dart`) | `surfaceContainerLow` fill, `outlineVariant` bottom border, 48dp minimum height, `bodyLarge` w600 "Label: value ▾"; tap opens one `showMeshSheet` with `MeshSheetOption`s. Shows the saved value only; a spinner replaces ▾ while saving; a disabled strip shows why below the label. One shared widget for DM and channel chats; parents pass state and async callbacks | | Choosing between images | Selectable thumbnail tiles in a centred `Wrap` | Image send versions (`_versionTile` in `image_send_preview_sheet.dart`). `InkWell` with `MeshRadii.sm`; selected tile gets a 3px `primary` border **and** a `primary` check badge (never colour alone); caption under the tile in `bodySmall`, w600 when selected; figures such as packet counts in `MeshTheme.mono` 12; wrap the tile in `Semantics(button: true, selected:, label:)` | | Popup menu row | **always** `PopupMenuItem(child: MeshMenuItemRow(icon:, label:))` | Label wraps to 2 lines then ellipsizes; `leading:` for `ThemedIcon`; no icon keeps the 20px slot | | Segmented button label | **always** `ButtonSegment(label: MeshSegmentLabel(text))` | Shrinks to 12 (before system scale), then wraps at word boundaries onto 2 centred lines; never breaks a word | diff --git a/documentation/settings.md b/documentation/settings.md index 3f101f07..91b2af5e 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -178,7 +178,7 @@ Save the settings before sharing. The upload action is shown in the chat compose Image message controls live in App Settings → Messaging. Turn on **Enable image messages** first; **Process images automatically** and the image model download/cancel/removal controls then appear. Automatic processing reconstructs every image as it arrives and uses about 2 GB of memory for a second each time; leave it off to reconstruct with a tap. See [Image Messages](image-messages.md) for firmware, native-runtime, storage, and memory requirements. ### Cyrillic-to-Latin (Cyr2Lat) -Controls character substitution profiles used to render Cyrillic text in Latin characters. A dropdown selects the active profile; Add, Edit, and Delete buttons manage the profile list (the last remaining profile cannot be deleted). Each profile stores a JSON character map. +Controls character substitution profiles used to render Cyrillic text in Latin characters. A dropdown selects the active profile; Add, Edit, and Delete buttons manage the profile list (the last remaining profile cannot be deleted). Each profile stores a JSON character map. The active profile is the default; each chat can pick its own in its **Compression** strip (see [Compression](additional-features.md#compression-smaz-and-cyr2lat)). ### Debug - **App Debug Logging**: Enable the in-app debug log diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index ad9fa57e..2f311f43 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -12,6 +12,7 @@ import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_ import '../utils/advert_signature.dart'; import '../models/channel.dart'; import '../models/channel_message.dart'; +import '../models/chat_compression_mode.dart'; import '../models/bookmarked_message.dart'; import '../models/companion_radio_stats.dart'; import '../models/contact.dart'; @@ -1816,10 +1817,6 @@ class MeshCoreConnector extends ChangeNotifier { await _channelRegionStore.saveDefaultRegion(region); } - void ensureContactSmazSettingLoaded(String contactKeyHex) { - _ensureContactSmazSettingLoaded(contactKeyHex); - } - bool isChannelCyr2LatEnabled(int channelIndex) { _ensureChannelCyr2LatSettingLoaded(channelIndex); return _channelCyr2LatEnabled[channelIndex] ?? false; @@ -1830,10 +1827,6 @@ class MeshCoreConnector extends ChangeNotifier { return _contactCyr2LatEnabled[contactKeyHex] ?? false; } - void ensureContactCyr2LatSettingLoaded(String contactKeyHex) { - _ensureContactCyr2LatSettingLoaded(contactKeyHex); - } - Future loadUnreadState() async { _contactUnreadCount ..clear() @@ -2102,30 +2095,97 @@ class MeshCoreConnector extends ChangeNotifier { ]; } - Future setChannelSmazEnabled(int channelIndex, bool enabled) async { - final slots = _slotsSharingChannel(channelIndex); - for (final slot in slots) { - _channelSmazEnabled[slot] = enabled; + ChatCompressionMode channelCompressionMode(int channelIndex) { + if (isChannelSmazEnabled(channelIndex)) return ChatCompressionMode.smaz; + if (isChannelCyr2LatEnabled(channelIndex)) { + return ChatCompressionMode.cyr2lat; } - final channelId = _channelIdForSlot(channelIndex); - if (enabled) { - for (final slot in slots) { - _channelCyr2LatEnabled[slot] = false; - } - if (channelId != null) { - await _channelSettingsStore.saveCyr2LatEnabled(channelId, false); - } - } - if (channelId != null) { - await _channelSettingsStore.saveSmazEnabled(channelId, enabled); - } - notifyListeners(); + return ChatCompressionMode.off; } - Future setContactSmazEnabled(String contactKeyHex, bool enabled) async { - _contactSmazEnabled[contactKeyHex] = enabled; - await _contactSettingsStore.saveSmazEnabled(contactKeyHex, enabled); - notifyListeners(); + ChatCompressionMode contactCompressionMode(String contactKeyHex) { + _ensureContactSmazSettingLoaded(contactKeyHex); + if (isContactSmazEnabled(contactKeyHex)) return ChatCompressionMode.smaz; + if (isContactCyr2LatEnabled(contactKeyHex)) { + return ChatCompressionMode.cyr2lat; + } + return ChatCompressionMode.off; + } + + /// Serializes compression writes so overlapping choices can't interleave + /// their flag writes and leave SMAZ and Cyr2Lat both on. + Future _compressionWrites = Future.value(); + + Future _queueCompressionWrite(Future Function() write) { + final next = _compressionWrites.then((_) => write()); + _compressionWrites = next.catchError((_) {}); + return next; + } + + /// Saves [mode] for the channel in [channelIndex] and every slot holding + /// the same channel. Flags are switched off before the new one is switched + /// on, and memory follows each completed write, so a failure never leaves + /// both on. Throws [StateError] when the slot has no storage ID. + Future setChannelCompressionMode( + int channelIndex, + ChatCompressionMode mode, + ) { + return _queueCompressionWrite(() async { + final channelId = _channelIdForSlot(channelIndex); + if (channelId == null) { + throw StateError('Channel slot $channelIndex has no storage ID'); + } + final slots = _slotsSharingChannel(channelIndex); + Future writeSmaz(bool on) async { + await _channelSettingsStore.saveSmazEnabled(channelId, on); + for (final slot in slots) { + _channelSmazEnabled[slot] = on; + } + } + + Future writeCyr2Lat(bool on) async { + await _channelSettingsStore.saveCyr2LatEnabled(channelId, on); + for (final slot in slots) { + _channelCyr2LatEnabled[slot] = on; + } + } + + try { + if (mode != ChatCompressionMode.smaz) await writeSmaz(false); + if (mode != ChatCompressionMode.cyr2lat) await writeCyr2Lat(false); + if (mode == ChatCompressionMode.smaz) await writeSmaz(true); + if (mode == ChatCompressionMode.cyr2lat) await writeCyr2Lat(true); + } finally { + notifyListeners(); + } + }); + } + + /// Contact counterpart of [setChannelCompressionMode]. + Future setContactCompressionMode( + String contactKeyHex, + ChatCompressionMode mode, + ) { + return _queueCompressionWrite(() async { + Future writeSmaz(bool on) async { + await _contactSettingsStore.saveSmazEnabled(contactKeyHex, on); + _contactSmazEnabled[contactKeyHex] = on; + } + + Future writeCyr2Lat(bool on) async { + await _contactSettingsStore.saveCyr2LatEnabled(contactKeyHex, on); + _contactCyr2LatEnabled[contactKeyHex] = on; + } + + try { + if (mode != ChatCompressionMode.smaz) await writeSmaz(false); + if (mode != ChatCompressionMode.cyr2lat) await writeCyr2Lat(false); + if (mode == ChatCompressionMode.smaz) await writeSmaz(true); + if (mode == ChatCompressionMode.cyr2lat) await writeCyr2Lat(true); + } finally { + notifyListeners(); + } + }); } Future setChannelUrlImagesEnabled( @@ -2151,35 +2211,6 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } - Future setChannelCyr2LatEnabled(int channelIndex, bool enabled) async { - final slots = _slotsSharingChannel(channelIndex); - for (final slot in slots) { - _channelCyr2LatEnabled[slot] = enabled; - } - final channelId = _channelIdForSlot(channelIndex); - if (enabled) { - for (final slot in slots) { - _channelSmazEnabled[slot] = false; - } - if (channelId != null) { - await _channelSettingsStore.saveSmazEnabled(channelId, false); - } - } - if (channelId != null) { - await _channelSettingsStore.saveCyr2LatEnabled(channelId, enabled); - } - notifyListeners(); - } - - Future setContactCyr2LatEnabled( - String contactKeyHex, - bool enabled, - ) async { - _contactCyr2LatEnabled[contactKeyHex] = enabled; - await _contactSettingsStore.saveCyr2LatEnabled(contactKeyHex, enabled); - notifyListeners(); - } - Future setChannelRegion(int channelIndex, String region) async { // Update in-memory state and notify synchronously so the UI reflects the // change immediately; persistence happens in the background. @@ -8337,7 +8368,7 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureContactSmazSettingLoaded(String contactKeyHex) { if (_contactSmazEnabled.containsKey(contactKeyHex)) return; _contactSettingsStore.loadSmazEnabled(contactKeyHex).then((enabled) { - if (_contactSmazEnabled[contactKeyHex] == enabled) return; + if (_contactSmazEnabled.containsKey(contactKeyHex)) return; _contactSmazEnabled[contactKeyHex] = enabled; notifyListeners(); }); @@ -8346,7 +8377,7 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureContactCyr2LatSettingLoaded(String contactKeyHex) { if (_contactCyr2LatEnabled.containsKey(contactKeyHex)) return; _contactSettingsStore.loadCyr2LatEnabled(contactKeyHex).then((enabled) { - if (_contactCyr2LatEnabled[contactKeyHex] == enabled) return; + if (_contactCyr2LatEnabled.containsKey(contactKeyHex)) return; _contactCyr2LatEnabled[contactKeyHex] = enabled; notifyListeners(); }); @@ -8364,7 +8395,7 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureContactCyr2LatProfileLoaded(String contactKeyHex) { if (_contactCyr2LatProfileId.containsKey(contactKeyHex)) return; _contactSettingsStore.loadCyr2LatProfileId(contactKeyHex).then((profileId) { - if (_contactCyr2LatProfileId[contactKeyHex] == profileId) return; + if (_contactCyr2LatProfileId.containsKey(contactKeyHex)) return; _contactCyr2LatProfileId[contactKeyHex] = profileId; notifyListeners(); }); @@ -8375,7 +8406,7 @@ class MeshCoreConnector extends ChangeNotifier { final channelId = _slotChannelIds[channelIndex]; if (channelId == null) return; _channelSettingsStore.loadCyr2LatEnabled(channelId).then((enabled) { - if (_channelCyr2LatEnabled[channelIndex] == enabled) return; + if (_channelCyr2LatEnabled.containsKey(channelIndex)) return; _channelCyr2LatEnabled[channelIndex] = enabled; notifyListeners(); }); @@ -8386,7 +8417,7 @@ class MeshCoreConnector extends ChangeNotifier { final channelId = _slotChannelIds[channelIndex]; if (channelId == null) return; _channelSettingsStore.loadCyr2LatProfileId(channelId).then((profileId) { - if (_channelCyr2LatProfileId[channelIndex] == profileId) return; + if (_channelCyr2LatProfileId.containsKey(channelIndex)) return; _channelCyr2LatProfileId[channelIndex] = profileId; notifyListeners(); }); @@ -8402,13 +8433,13 @@ class MeshCoreConnector extends ChangeNotifier { String? profileId, ) async { if (_channelCyr2LatProfileId[channelIndex] == profileId) return; - for (final slot in _slotsSharingChannel(channelIndex)) { - _channelCyr2LatProfileId[slot] = profileId; - } final channelId = _channelIdForSlot(channelIndex); if (channelId != null) { await _channelSettingsStore.saveCyr2LatProfileId(channelId, profileId); } + for (final slot in _slotsSharingChannel(channelIndex)) { + _channelCyr2LatProfileId[slot] = profileId; + } notifyListeners(); } @@ -8422,8 +8453,8 @@ class MeshCoreConnector extends ChangeNotifier { String? profileId, ) async { if (_contactCyr2LatProfileId[contactKeyHex] == profileId) return; - _contactCyr2LatProfileId[contactKeyHex] = profileId; await _contactSettingsStore.saveCyr2LatProfileId(contactKeyHex, profileId); + _contactCyr2LatProfileId[contactKeyHex] = profileId; notifyListeners(); } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..0e612bb8 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -973,9 +973,6 @@ } } }, - "channels_smazCompression": "SMAZ compression", - "channels_cyr2latCompression": "Cyr2Lat compression", - "channels_cyr2latCompressionDscr": "Replaces some Cyrillic characters with Latin characters when sending.", "channels_cyr2latSettingsHeading": "Cyr2Lat Setup", "channels_cyr2latSettingsSubheading": "List of replacements", "channels_cyr2latSettingsDscr": "Edit the JSON configuration of character replacement", @@ -1414,7 +1411,6 @@ "chat_path": "Path", "chat_viewPathOnMap": "View path on map", "chat_publicKey": "Public Key", - "chat_compressOutgoingMessages": "Compress outgoing messages", "chat_floodForced": "Flood (forced)", "chat_directForced": "Direct (forced)", "chat_hopsForced": "{count} hops (forced)", @@ -4341,5 +4337,26 @@ "chat_composerOffline": "Connect to a radio to send messages", "@chat_composerOffline": { "description": "Shown in place of the message box while no radio is connected" - } + }, + "chatCompression_title": "Compression", + "chatCompression_label": "Compression: {mode}", + "@chatCompression_label": { + "description": "Always-visible control at the top of a chat; mode is Off, SMAZ or Cyr2Lat", + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "chatCompression_off": "Off", + "chatCompression_smaz": "SMAZ", + "chatCompression_cyr2lat": "Cyr2Lat", + "chatCompression_changeHint": "Change compression for this chat", + "chatCompression_sheetSubtitle": "Applies to messages you send in this chat. Saved on this phone.", + "chatCompression_offDescription": "No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.", + "chatCompression_smazDescription": "Lossless compression for short text. The recipient's app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.", + "chatCompression_cyr2latDescription": "Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.", + "chatCompression_profile": "Cyr2Lat profile", + "chatCompression_noStorageId": "Can't change compression until this channel has synced from the radio.", + "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting." } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..d3b05d2f 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3607,24 +3607,6 @@ abstract class AppLocalizations { /// **'Edit Channel {index}'** String channels_editChannelTitle(int index); - /// No description provided for @channels_smazCompression. - /// - /// In en, this message translates to: - /// **'SMAZ compression'** - String get channels_smazCompression; - - /// No description provided for @channels_cyr2latCompression. - /// - /// In en, this message translates to: - /// **'Cyr2Lat compression'** - String get channels_cyr2latCompression; - - /// No description provided for @channels_cyr2latCompressionDscr. - /// - /// In en, this message translates to: - /// **'Replaces some Cyrillic characters with Latin characters when sending.'** - String get channels_cyr2latCompressionDscr; - /// No description provided for @channels_cyr2latSettingsHeading. /// /// In en, this message translates to: @@ -4813,12 +4795,6 @@ abstract class AppLocalizations { /// **'Public Key'** String get chat_publicKey; - /// No description provided for @chat_compressOutgoingMessages. - /// - /// In en, this message translates to: - /// **'Compress outgoing messages'** - String get chat_compressOutgoingMessages; - /// No description provided for @chat_floodForced. /// /// In en, this message translates to: @@ -12633,6 +12609,84 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Connect to a radio to send messages'** String get chat_composerOffline; + + /// No description provided for @chatCompression_title. + /// + /// In en, this message translates to: + /// **'Compression'** + String get chatCompression_title; + + /// Always-visible control at the top of a chat; mode is Off, SMAZ or Cyr2Lat + /// + /// In en, this message translates to: + /// **'Compression: {mode}'** + String chatCompression_label(String mode); + + /// No description provided for @chatCompression_off. + /// + /// In en, this message translates to: + /// **'Off'** + String get chatCompression_off; + + /// No description provided for @chatCompression_smaz. + /// + /// In en, this message translates to: + /// **'SMAZ'** + String get chatCompression_smaz; + + /// No description provided for @chatCompression_cyr2lat. + /// + /// In en, this message translates to: + /// **'Cyr2Lat'** + String get chatCompression_cyr2lat; + + /// No description provided for @chatCompression_changeHint. + /// + /// In en, this message translates to: + /// **'Change compression for this chat'** + String get chatCompression_changeHint; + + /// No description provided for @chatCompression_sheetSubtitle. + /// + /// In en, this message translates to: + /// **'Applies to messages you send in this chat. Saved on this phone.'** + String get chatCompression_sheetSubtitle; + + /// No description provided for @chatCompression_offDescription. + /// + /// In en, this message translates to: + /// **'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'** + String get chatCompression_offDescription; + + /// No description provided for @chatCompression_smazDescription. + /// + /// In en, this message translates to: + /// **'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'** + String get chatCompression_smazDescription; + + /// No description provided for @chatCompression_cyr2latDescription. + /// + /// In en, this message translates to: + /// **'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'** + String get chatCompression_cyr2latDescription; + + /// No description provided for @chatCompression_profile. + /// + /// In en, this message translates to: + /// **'Cyr2Lat profile'** + String get chatCompression_profile; + + /// No description provided for @chatCompression_noStorageId. + /// + /// In en, this message translates to: + /// **'Can\'t change compression until this channel has synced from the radio.'** + String get chatCompression_noStorageId; + + /// No description provided for @chatCompression_saveFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t save the compression setting. Showing the saved setting.'** + String get chatCompression_saveFailed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..fe6e6735 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -2020,16 +2020,6 @@ class AppLocalizationsBg extends AppLocalizations { return 'Редактирай Канал $index'; } - @override - String get channels_smazCompression => 'Компресия SMAZ'; - - @override - String get channels_cyr2latCompression => 'Компресия Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Заменя някои кирилични символи с латиница при изпращане.'; - @override String get channels_cyr2latSettingsHeading => 'Настройки на Cyr2Lat'; @@ -2757,10 +2747,6 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_publicKey => 'Публичен ключ'; - @override - String get chat_compressOutgoingMessages => - 'Компресиране на изходящи съобщения'; - @override String get chat_floodForced => 'Flood (принудително)'; @@ -7582,4 +7568,51 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_composerOffline => 'Свържете се с радио, за да изпращате съобщения'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..c5e7a674 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -2005,16 +2005,6 @@ class AppLocalizationsCs extends AppLocalizations { return 'Upravit kanál $index'; } - @override - String get channels_smazCompression => 'Komprese SMAZ'; - - @override - String get channels_cyr2latCompression => 'Komprese Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Při odesílání nahradí některé znaky cyrilice latinkou.'; - @override String get channels_cyr2latSettingsHeading => 'Nastavení Cyr2Lat'; @@ -2747,9 +2737,6 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chat_publicKey => 'Veřejný klíč'; - @override - String get chat_compressOutgoingMessages => 'Komprimovat odchozí zprávy'; - @override String get chat_floodForced => 'Flood (vynuceno)'; @@ -7552,4 +7539,51 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chat_composerOffline => 'Pro odesílání zpráv se připojte k rádiu'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..47298222 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2020,16 +2020,6 @@ class AppLocalizationsDe extends AppLocalizations { return 'Kanal $index bearbeiten'; } - @override - String get channels_smazCompression => 'SMAZ-Komprimierung'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat-Komprimierung'; - - @override - String get channels_cyr2latCompressionDscr => - 'Ersetzt beim Senden einige kyrillische Zeichen durch lateinische Zeichen.'; - @override String get channels_cyr2latSettingsHeading => 'Cyr2Lat-Einstellungen'; @@ -2759,10 +2749,6 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_publicKey => 'Öffentlicher Schlüssel'; - @override - String get chat_compressOutgoingMessages => - 'Komprimieren ausgehender Nachrichten'; - @override String get chat_floodForced => 'Flood (erzwungen)'; @@ -7597,4 +7583,51 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_composerOffline => 'Mit einem Funkgerät verbinden, um Nachrichten zu senden'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..55f25921 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1984,16 +1984,6 @@ class AppLocalizationsEn extends AppLocalizations { return 'Edit Channel $index'; } - @override - String get channels_smazCompression => 'SMAZ compression'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat compression'; - - @override - String get channels_cyr2latCompressionDscr => - 'Replaces some Cyrillic characters with Latin characters when sending.'; - @override String get channels_cyr2latSettingsHeading => 'Cyr2Lat Setup'; @@ -2711,9 +2701,6 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_publicKey => 'Public Key'; - @override - String get chat_compressOutgoingMessages => 'Compress outgoing messages'; - @override String get chat_floodForced => 'Flood (forced)'; @@ -7468,4 +7455,51 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_composerOffline => 'Connect to a radio to send messages'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..1e3a9f98 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2013,16 +2013,6 @@ class AppLocalizationsEs extends AppLocalizations { return 'Editar Canal $index'; } - @override - String get channels_smazCompression => 'Compresión SMAZ'; - - @override - String get channels_cyr2latCompression => 'Compresión Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Reemplaza algunos caracteres cirílicos con caracteres latinos al enviar.'; - @override String get channels_cyr2latSettingsHeading => 'Configuración de Cyr2Lat'; @@ -2749,9 +2739,6 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_publicKey => 'Clave pública'; - @override - String get chat_compressOutgoingMessages => 'Comprimir mensajes salientes'; - @override String get chat_floodForced => 'Flood (forzado)'; @@ -7573,4 +7560,51 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_composerOffline => 'Conéctate a una radio para enviar mensajes'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..a3006ad0 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2017,16 +2017,6 @@ class AppLocalizationsFr extends AppLocalizations { return 'Modifier le Canal $index'; } - @override - String get channels_smazCompression => 'Compression SMAZ'; - - @override - String get channels_cyr2latCompression => 'Compression Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Remplace certains caractères cyrilliques par des caractères latins lors de l\'envoi.'; - @override String get channels_cyr2latSettingsHeading => 'Paramètres Cyr2Lat'; @@ -2754,10 +2744,6 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_publicKey => 'Clé publique'; - @override - String get chat_compressOutgoingMessages => - 'Compresser les messages sortants'; - @override String get chat_floodForced => 'Flood (forcé)'; @@ -7602,4 +7588,51 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_composerOffline => 'Connectez-vous à une radio pour envoyer des messages'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..7781741b 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -2011,16 +2011,6 @@ class AppLocalizationsHu extends AppLocalizations { return 'Csatorna szerkesztése $index'; } - @override - String get channels_smazCompression => 'SMAZ tömörítés'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat tömörítés'; - - @override - String get channels_cyr2latCompressionDscr => - 'Küldéskor egyes cirill karaktereket latin karakterekre cserél.'; - @override String get channels_cyr2latSettingsHeading => 'Cyr2Lat beállítás'; @@ -2746,9 +2736,6 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_publicKey => 'Nyilvános kulcs'; - @override - String get chat_compressOutgoingMessages => 'A kimenő üzenetek tömörítése'; - @override String get chat_floodForced => 'Flood (kényszerített)'; @@ -7565,4 +7552,51 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_composerOffline => 'Üzenetküldéshez csatlakozzon rádióhoz'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..d34a068a 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2014,16 +2014,6 @@ class AppLocalizationsIt extends AppLocalizations { return 'Modifica Canale $index'; } - @override - String get channels_smazCompression => 'Compressione SMAZ'; - - @override - String get channels_cyr2latCompression => 'Compressione Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Sostituisce alcuni caratteri cirillici con caratteri latini durante l\'invio.'; - @override String get channels_cyr2latSettingsHeading => 'Impostazioni Cyr2Lat'; @@ -2754,9 +2744,6 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_publicKey => 'Chiave pubblica'; - @override - String get chat_compressOutgoingMessages => 'Comprimi messaggi in uscita'; - @override String get chat_floodForced => 'Flood (forzato)'; @@ -7585,4 +7572,51 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_composerOffline => 'Connettiti a una radio per inviare messaggi'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..88d6e946 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1919,15 +1919,6 @@ class AppLocalizationsJa extends AppLocalizations { return 'チャンネル $index の編集'; } - @override - String get channels_smazCompression => 'SMAZ 圧縮'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat 圧縮'; - - @override - String get channels_cyr2latCompressionDscr => '送信時に一部のキリル文字をラテン文字に置き換えます。'; - @override String get channels_cyr2latSettingsHeading => 'Cyr2Lat 設定'; @@ -2627,9 +2618,6 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_publicKey => '公開鍵'; - @override - String get chat_compressOutgoingMessages => '送信メッセージを圧縮する'; - @override String get chat_floodForced => 'フラッド(強制)'; @@ -7227,4 +7215,51 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_composerOffline => 'メッセージを送信するには無線機に接続してください'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..e8e29f0c 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1923,15 +1923,6 @@ class AppLocalizationsKo extends AppLocalizations { return '채널 $index 편집'; } - @override - String get channels_smazCompression => 'SMAZ 압축'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat 압축'; - - @override - String get channels_cyr2latCompressionDscr => '보낼 때 일부 키릴 문자를 라틴 문자로 바꿉니다.'; - @override String get channels_cyr2latSettingsHeading => 'Cyr2Lat 설정'; @@ -2630,9 +2621,6 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_publicKey => '공개 키'; - @override - String get chat_compressOutgoingMessages => '전송되는 메시지 압축'; - @override String get chat_floodForced => '플러딩 (강제)'; @@ -7240,4 +7228,51 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_composerOffline => '메시지를 보내려면 무전기에 연결하세요'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..ba6e9de4 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -2004,16 +2004,6 @@ class AppLocalizationsNl extends AppLocalizations { return 'Bewerk Kanaal $index'; } - @override - String get channels_smazCompression => 'SMAZ compressie'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat compressie'; - - @override - String get channels_cyr2latCompressionDscr => - 'Vervangt sommige Cyrillische tekens door Latijnse tekens bij het verzenden.'; - @override String get channels_cyr2latSettingsHeading => 'Instellingen Cyr2Lat'; @@ -2738,9 +2728,6 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_publicKey => 'Openbare Sleutel'; - @override - String get chat_compressOutgoingMessages => 'Uitgaande berichten comprimeren'; - @override String get chat_floodForced => 'Flood (afgedwongen)'; @@ -7541,4 +7528,51 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_composerOffline => 'Verbind met een radio om berichten te versturen'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..76abe1f3 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -2028,16 +2028,6 @@ class AppLocalizationsPl extends AppLocalizations { return 'Edytuj Kanał $index'; } - @override - String get channels_smazCompression => 'Kompresja SMAZ'; - - @override - String get channels_cyr2latCompression => 'Kompresja Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Zastępuje niektóre znaki cyrylicy alfabetem łacińskim podczas wysyłania.'; - @override String get channels_cyr2latSettingsHeading => 'Ustawienia Cyr2Lat'; @@ -2781,9 +2771,6 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_publicKey => 'Klucz Publiczny'; - @override - String get chat_compressOutgoingMessages => 'Kompresuj wychodzące wiadomości'; - @override String get chat_floodForced => 'Flood (wymuszony)'; @@ -7619,4 +7606,51 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_composerOffline => 'Połącz się z radiem, aby wysyłać wiadomości'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..e03a6a77 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2013,16 +2013,6 @@ class AppLocalizationsPt extends AppLocalizations { return 'Editar Canal $index'; } - @override - String get channels_smazCompression => 'Compressão SMAZ'; - - @override - String get channels_cyr2latCompression => 'Compressão Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Substitui alguns caracteres cirílicos por caracteres latinos ao enviar.'; - @override String get channels_cyr2latSettingsHeading => 'Configuração do Cyr2Lat'; @@ -2748,9 +2738,6 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_publicKey => 'Chave Pública'; - @override - String get chat_compressOutgoingMessages => 'Comprimir mensagens enviadas'; - @override String get chat_floodForced => 'Flood (forçado)'; @@ -7563,6 +7550,53 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_composerOffline => 'Conecte-se a um rádio para enviar mensagens'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). @@ -9564,16 +9598,6 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { return 'Editar canal $index'; } - @override - String get channels_smazCompression => 'Compressão SMAZ'; - - @override - String get channels_cyr2latCompression => 'Compressão Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Substitui alguns caracteres cirílicos por latinos ao enviar.'; - @override String get channels_cyr2latSettingsHeading => 'Configuração Cyr2Lat'; @@ -10273,9 +10297,6 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get chat_publicKey => 'Chave pública'; - @override - String get chat_compressOutgoingMessages => 'Comprimir mensagens enviadas'; - @override String get chat_floodForced => 'Flood (forçado)'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..65fa0d17 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2012,16 +2012,6 @@ class AppLocalizationsRu extends AppLocalizations { return 'Изменить канал $index'; } - @override - String get channels_smazCompression => 'Сжатие SMAZ'; - - @override - String get channels_cyr2latCompression => 'Сжатие Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Заменяет некоторые кириллические символы на латиницу при отправке.'; - @override String get channels_cyr2latSettingsHeading => 'Настройка Cyr2Lat'; @@ -2760,9 +2750,6 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_publicKey => 'Публичный ключ'; - @override - String get chat_compressOutgoingMessages => 'Сжимать исходящие сообщения'; - @override String get chat_floodForced => 'Flood (принудительно)'; @@ -7599,4 +7586,51 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_composerOffline => 'Подключитесь к радио, чтобы отправлять сообщения'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..531f0f42 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -2005,16 +2005,6 @@ class AppLocalizationsSk extends AppLocalizations { return 'Upraviť kanál $index'; } - @override - String get channels_smazCompression => 'Odstránenie kompresie SMAZ'; - - @override - String get channels_cyr2latCompression => 'Odstránenie kompresie Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Pri odosielaní nahradí niektoré znaky cyriliky latinskými znakmi.'; - @override String get channels_cyr2latSettingsHeading => 'Nastavenia Cyr2Lat'; @@ -2752,9 +2742,6 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_publicKey => 'Verejný kľúč'; - @override - String get chat_compressOutgoingMessages => 'Komprimovať odoslané správy'; - @override String get chat_floodForced => 'Flood (vynútený)'; @@ -7564,4 +7551,51 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_composerOffline => 'Na odosielanie správ sa pripojte k rádiu'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..9f3507f6 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -2003,16 +2003,6 @@ class AppLocalizationsSl extends AppLocalizations { return 'Uredi Kanal $index'; } - @override - String get channels_smazCompression => 'Kompresija SMAZ'; - - @override - String get channels_cyr2latCompression => 'Kompresija Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Pri pošiljanju nekatere cirilice nadomesti z latiničnimi.'; - @override String get channels_cyr2latSettingsHeading => 'Nastavitve Cyr2Lat'; @@ -2747,9 +2737,6 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_publicKey => 'Ključ javnega tipa'; - @override - String get chat_compressOutgoingMessages => 'Stisnite izhodne sporočila'; - @override String get chat_floodForced => 'Flood (vsiljeno)'; @@ -7558,4 +7545,51 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_composerOffline => 'Za pošiljanje sporočil se povežite z radiem'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..a1a1d60c 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1991,16 +1991,6 @@ class AppLocalizationsSv extends AppLocalizations { return 'Redigera Kanal $index'; } - @override - String get channels_smazCompression => 'SMAZ-komprimering'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat-komprimering'; - - @override - String get channels_cyr2latCompressionDscr => - 'Ersätter vissa kyrilliska tecken med latinska tecken när du skickar.'; - @override String get channels_cyr2latSettingsHeading => 'Inställningar för Cyr2Lat'; @@ -2726,9 +2716,6 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_publicKey => 'Publik nyckel'; - @override - String get chat_compressOutgoingMessages => 'Komprimera utgående meddelanden'; - @override String get chat_floodForced => 'Flood (tvingad)'; @@ -7518,4 +7505,51 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_composerOffline => 'Anslut till en radio för att skicka meddelanden'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..27db6d88 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -2008,16 +2008,6 @@ class AppLocalizationsUk extends AppLocalizations { return 'Редагувати канал $index'; } - @override - String get channels_smazCompression => 'Стиснення SMAZ'; - - @override - String get channels_cyr2latCompression => 'Стиснення Cyr2Lat'; - - @override - String get channels_cyr2latCompressionDscr => - 'Замінює деякі кириличні символи на латиницю при відправці.'; - @override String get channels_cyr2latSettingsHeading => 'Налаштування Cyr2Lat'; @@ -2757,9 +2747,6 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_publicKey => 'Відкритий ключ'; - @override - String get chat_compressOutgoingMessages => 'Стискати вихідні повідомлення'; - @override String get chat_floodForced => 'Flood (примусово)'; @@ -7611,4 +7598,51 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_composerOffline => 'Підключіться до радіо, щоб надсилати повідомлення'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..2c7eefd0 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1893,15 +1893,6 @@ class AppLocalizationsZh extends AppLocalizations { return '编辑频道 $index'; } - @override - String get channels_smazCompression => 'SMAZ 压缩'; - - @override - String get channels_cyr2latCompression => 'Cyr2Lat 压缩'; - - @override - String get channels_cyr2latCompressionDscr => '发送时将一些西里尔字符替换为拉丁字符。'; - @override String get channels_cyr2latSettingsHeading => 'Cyr2Lat 設定'; @@ -2586,9 +2577,6 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_publicKey => '公钥'; - @override - String get chat_compressOutgoingMessages => '压缩发送的消息'; - @override String get chat_floodForced => '泛洪(强制)'; @@ -7070,4 +7058,51 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_composerOffline => '连接到无线电后才能发送消息'; + + @override + String get chatCompression_title => 'Compression'; + + @override + String chatCompression_label(String mode) { + return 'Compression: $mode'; + } + + @override + String get chatCompression_off => 'Off'; + + @override + String get chatCompression_smaz => 'SMAZ'; + + @override + String get chatCompression_cyr2lat => 'Cyr2Lat'; + + @override + String get chatCompression_changeHint => 'Change compression for this chat'; + + @override + String get chatCompression_sheetSubtitle => + 'Applies to messages you send in this chat. Saved on this phone.'; + + @override + String get chatCompression_offDescription => + 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + + @override + String get chatCompression_smazDescription => + 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + + @override + String get chatCompression_cyr2latDescription => + 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + + @override + String get chatCompression_profile => 'Cyr2Lat profile'; + + @override + String get chatCompression_noStorageId => + 'Can\'t change compression until this channel has synced from the radio.'; + + @override + String get chatCompression_saveFailed => + 'Couldn\'t save the compression setting. Showing the saved setting.'; } diff --git a/lib/models/chat_compression_mode.dart b/lib/models/chat_compression_mode.dart new file mode 100644 index 00000000..fd2bd98b --- /dev/null +++ b/lib/models/chat_compression_mode.dart @@ -0,0 +1,3 @@ +/// Outgoing text transformation chosen for one contact or channel chat. +/// Stored as the existing SMAZ and Cyr2Lat flags, at most one of them on. +enum ChatCompressionMode { off, smaz, cyr2lat } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 67a397ab..32068471 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -53,6 +53,7 @@ import '../widgets/empty_state.dart'; import '../widgets/filter_rule_dialog.dart'; import '../widgets/filtered_message_ghost.dart'; import '../widgets/chat_composer.dart'; +import '../widgets/chat_compression_selector.dart'; import '../widgets/chat_send_pipeline.dart'; import '../widgets/chat_zoom_wrapper.dart'; import '../widgets/message_bubble_frame.dart'; @@ -845,6 +846,7 @@ class _ChannelChatScreenState extends State { top: false, child: Column( children: [ + _buildCompressionSelector(), Expanded( child: ChatBackdrop( key: _messageAreaKey, @@ -2753,6 +2755,32 @@ class _ChannelChatScreenState extends State { static String _replyPrefix(ChannelMessage replyTo) => '@[${replyTo.senderName}] '; + /// Compression is stored on this phone under the channel's storage ID, so + /// it can change while the radio is offline, but not before the slot has + /// one. + Widget _buildCompressionSelector() { + final slot = widget.channel.index; + return Consumer2( + builder: (context, connector, settingsService, _) { + final hasStorageId = connector.channelIdForSlot(slot) != null; + return ChatCompressionSelector( + mode: connector.channelCompressionMode(slot), + enabled: hasStorageId, + disabledReason: hasStorageId + ? null + : context.l10n.chatCompression_noStorageId, + profiles: settingsService.settings.cyr2latProfiles, + profileId: connector.getChannelCyr2LatProfileId(slot), + defaultProfileId: settingsService.settings.selectedCyr2latProfileId, + onModeChanged: (mode) => + connector.setChannelCompressionMode(slot, mode), + onProfileChanged: (id) => + connector.setChannelCyr2LatProfileId(slot, id), + ); + }, + ); + } + Widget _buildInputBar() { // Only the fields the composer depends on, so unrelated connector // notifications (adverts, other chats, radio stats) don't rebuild it. diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 6f247343..9131ed35 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1951,16 +1951,11 @@ void showEditChannelSheet( context, listen: false, ); - bool smazEnabled = connector.isChannelSmazEnabled(channel.index); - bool cyr2latEnabled = connector.isChannelCyr2LatEnabled(channel.index); final initialUrlImagesEnabled = connector.isChannelUrlImagesEnabled( channel.index, ); bool urlImagesEnabled = initialUrlImagesEnabled; final loadLinkImages = appSettingsService.settings.loadLinkImages; - String? selectedCyr2LatProfileId = connector.getChannelCyr2LatProfileId( - channel.index, - ); showMeshSheet( context, @@ -2018,62 +2013,6 @@ void showEditChannelSheet( ), ), const SizedBox(height: 16), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(sheetContext.l10n.channels_smazCompression), - value: smazEnabled, - onChanged: (value) => setSheetState(() { - smazEnabled = value; - if (smazEnabled) { - cyr2latEnabled = false; - } - }), - ), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text( - sheetContext.l10n.channels_cyr2latCompression, - ), - subtitle: Text( - sheetContext.l10n.channels_cyr2latCompressionDscr, - ), - value: cyr2latEnabled, - onChanged: (value) => setSheetState(() { - cyr2latEnabled = value; - if (cyr2latEnabled) { - smazEnabled = false; - } - }), - ), - if (cyr2latEnabled) ...[ - Padding( - padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), - child: DropdownButtonFormField( - isExpanded: true, - initialValue: selectedCyr2LatProfileId, - decoration: InputDecoration( - labelText: sheetContext - .l10n - .channels_cyr2latSettingsSubheading, - border: const OutlineInputBorder(), - ), - items: appSettingsService.settings.cyr2latProfiles - .map((profile) { - return DropdownMenuItem( - value: profile.id, - child: Text( - profile.name, - overflow: TextOverflow.ellipsis, - ), - ); - }) - .toList(), - onChanged: (value) => setSheetState(() { - selectedCyr2LatProfileId = value; - }), - ), - ), - ], SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(sheetContext.l10n.urlImage_enable), @@ -2135,30 +2074,38 @@ void showEditChannelSheet( } Navigator.pop(sheetContext); + // A new PSK gives the channel a new storage ID; + // its compression settings move with it. + final previousId = connector.channelIdForSlot( + channel.index, + ); + final compression = connector + .channelCompressionMode(channel.index); + final cyr2LatProfileId = connector + .getChannelCyr2LatProfileId(channel.index); try { await connector.setChannel( channel.index, name, psk, ); - await connector.setChannelSmazEnabled( - channel.index, - smazEnabled, - ); - await connector.setChannelCyr2LatEnabled( - channel.index, - cyr2latEnabled, - ); + if (connector.channelIdForSlot(channel.index) != + previousId) { + await connector.setChannelCompressionMode( + channel.index, + compression, + ); + await connector.setChannelCyr2LatProfileId( + channel.index, + cyr2LatProfileId, + ); + } if (urlImagesEnabled != initialUrlImagesEnabled) { await connector.setChannelUrlImagesEnabled( channel.index, urlImagesEnabled, ); } - await connector.setChannelCyr2LatProfileId( - channel.index, - selectedCyr2LatProfileId, - ); if (!context.mounted) return; showDismissibleSnackBar( context, diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index ad509b82..7b03ae03 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -37,6 +37,7 @@ import '../services/chat_text_scale_service.dart'; import '../services/path_history_service.dart'; import '../services/translation_service.dart'; import '../widgets/chat_composer.dart'; +import '../widgets/chat_compression_selector.dart'; import '../widgets/chat_send_pipeline.dart'; import '../widgets/chat_zoom_wrapper.dart'; import '../widgets/message_bubble_frame.dart'; @@ -622,6 +623,7 @@ class _ChatScreenState extends State { ); return Column( children: [ + _buildCompressionSelector(connector), Expanded( child: ChatBackdrop( key: _messageAreaKey, @@ -648,6 +650,27 @@ class _ChatScreenState extends State { ); } + /// Compression is stored on this phone per contact, so it can change + /// while the radio is offline. + Widget _buildCompressionSelector(MeshCoreConnector connector) { + final keyHex = widget.contact.publicKeyHex; + return Consumer( + builder: (context, settingsService, _) { + return ChatCompressionSelector( + mode: connector.contactCompressionMode(keyHex), + enabled: true, + profiles: settingsService.settings.cyr2latProfiles, + profileId: connector.getContactCyr2LatProfileId(keyHex), + defaultProfileId: settingsService.settings.selectedCyr2latProfileId, + onModeChanged: (mode) => + connector.setContactCompressionMode(keyHex, mode), + onProfileChanged: (id) => + connector.setContactCyr2LatProfileId(keyHex, id), + ); + }, + ); + } + Widget _buildEmptyState() { if (_showBookmarkedOnly) return _buildBookmarkEmptyState(); return EmptyState( @@ -1109,19 +1132,9 @@ class _ChatScreenState extends State { void _showContactSettings(BuildContext context) { final connector = Provider.of(context, listen: false); - final appSettingsService = Provider.of( - context, - listen: false, - ); - connector.ensureContactSmazSettingLoaded(widget.contact.publicKeyHex); - connector.ensureContactCyr2LatSettingLoaded(widget.contact.publicKeyHex); // The live contact carries the current telemetry flags; widget.contact // is the snapshot this screen was opened with. final contact = _resolveContact(connector); - bool smazEnabled = connector.isContactSmazEnabled(contact.publicKeyHex); - bool cyr2latEnabled = connector.isContactCyr2LatEnabled( - contact.publicKeyHex, - ); bool urlImagesEnabled = connector.isContactUrlImagesEnabled( contact.publicKeyHex, ); @@ -1129,14 +1142,11 @@ class _ChatScreenState extends State { .read() .settings .loadLinkImages; - String? selectedCyr2LatProfileId = connector.getContactCyr2LatProfileId( - contact.publicKeyHex, - ); bool teleBaseEnabled = contact.teleBaseEnabled; bool teleLocEnabled = contact.teleLocEnabled; bool teleEnvEnabled = contact.teleEnvEnabled; - // Each toggle is committed immediately, like the compression switches, - // so dismissing the dialog by tapping outside keeps the change. All three + // Each toggle is committed immediately, like the link-image switch, so + // dismissing the dialog by tapping outside keeps the change. All three // flags are sent every time so overlapping writes can't undo each other. void commitTelemetryFlags() { connector.setContactFlags( @@ -1164,86 +1174,6 @@ class _ChatScreenState extends State { ), const Divider(height: 8), ], - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(context.l10n.channels_smazCompression), - subtitle: Text(context.l10n.chat_compressOutgoingMessages), - value: smazEnabled, - onChanged: (value) { - connector.setContactSmazEnabled( - contact.publicKeyHex, - value, - ); - connector.setContactCyr2LatEnabled( - contact.publicKeyHex, - false, - ); - setDialogState(() { - smazEnabled = value; - if (smazEnabled) { - cyr2latEnabled = false; - } - }); - }, - ), - const Divider(height: 8), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(context.l10n.channels_cyr2latCompression), - subtitle: Text(context.l10n.channels_cyr2latCompressionDscr), - value: cyr2latEnabled, - onChanged: (value) { - connector.setContactCyr2LatEnabled( - contact.publicKeyHex, - value, - ); - connector.setContactSmazEnabled( - contact.publicKeyHex, - false, - ); - setDialogState(() { - cyr2latEnabled = value; - if (cyr2latEnabled) { - smazEnabled = false; - } - }); - }, - ), - if (cyr2latEnabled) ...[ - Padding( - padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), - child: DropdownButtonFormField( - isExpanded: true, - initialValue: selectedCyr2LatProfileId, - decoration: InputDecoration( - labelText: - context.l10n.channels_cyr2latSettingsSubheading, - border: const OutlineInputBorder(), - ), - items: appSettingsService.settings.cyr2latProfiles.map(( - profile, - ) { - return DropdownMenuItem( - value: profile.id, - child: Text( - profile.name, - overflow: TextOverflow.ellipsis, - ), - ); - }).toList(), - onChanged: (value) { - connector.setContactCyr2LatProfileId( - contact.publicKeyHex, - value, - ); - setDialogState(() { - selectedCyr2LatProfileId = value; - }); - }, - ), - ), - ], - const Divider(height: 8), SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(context.l10n.urlImage_enable), diff --git a/lib/widgets/chat_compression_selector.dart b/lib/widgets/chat_compression_selector.dart new file mode 100644 index 00000000..5bddf0cd --- /dev/null +++ b/lib/widgets/chat_compression_selector.dart @@ -0,0 +1,356 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +import '../l10n/l10n.dart'; +import '../models/app_settings.dart'; +import '../models/chat_compression_mode.dart'; +import '../theme/mesh_theme.dart'; +import 'mesh_nav_tile.dart'; +import 'mesh_ui.dart'; + +export '../models/chat_compression_mode.dart'; + +/// Always-visible "Compression: Off / SMAZ / Cyr2Lat" strip for the top of a +/// DM or channel chat. Tapping it opens one sheet with the three choices, +/// what each does, and the Cyr2Lat profile picker. +/// +/// The parent supplies the saved state and persists changes through the +/// callbacks; this widget only shows a new mode once the parent rebuilds it +/// with that mode. A callback that throws leaves the saved mode in place and +/// shows an error in the sheet. +class ChatCompressionSelector extends StatefulWidget { + final ChatCompressionMode mode; + + /// False disables the strip and the sheet; [disabledReason] says why. + final bool enabled; + final String? disabledReason; + + final List profiles; + + /// The Cyr2Lat profile saved for this chat, if any. + final String? profileId; + + /// The app-wide profile, which sending uses when [profileId] is unset or + /// no longer exists. + final String? defaultProfileId; + + final Future Function(ChatCompressionMode mode) onModeChanged; + final Future Function(String profileId) onProfileChanged; + + const ChatCompressionSelector({ + super.key, + required this.mode, + required this.enabled, + this.disabledReason, + required this.profiles, + required this.profileId, + this.defaultProfileId, + required this.onModeChanged, + required this.onProfileChanged, + }); + + /// The profile sending actually uses, matching the connector's fallback. + String? get effectiveProfileId { + bool known(String? id) => profiles.any((p) => p.id == id); + if (known(profileId)) return profileId; + if (known(defaultProfileId)) return defaultProfileId; + return profiles.isEmpty ? null : profiles.first.id; + } + + @override + State createState() => + _ChatCompressionSelectorState(); +} + +String chatCompressionModeLabel(BuildContext context, ChatCompressionMode m) { + final l10n = context.l10n; + return switch (m) { + ChatCompressionMode.off => l10n.chatCompression_off, + ChatCompressionMode.smaz => l10n.chatCompression_smaz, + ChatCompressionMode.cyr2lat => l10n.chatCompression_cyr2lat, + }; +} + +/// What the open sheet renders. The sheet is a separate route, so it listens +/// to this instead of rebuilding with the strip. +class _SelectorView { + final ChatCompressionMode mode; + final bool enabled; + final List profiles; + final String? profileId; + final bool busy; + final bool failed; + + const _SelectorView({ + required this.mode, + required this.enabled, + required this.profiles, + required this.profileId, + required this.busy, + required this.failed, + }); +} + +class _ChatCompressionSelectorState extends State { + late final ValueNotifier<_SelectorView> _view = ValueNotifier(_snapshot()); + bool _busy = false; + bool _failed = false; + + _SelectorView _snapshot() => _SelectorView( + mode: widget.mode, + enabled: widget.enabled, + profiles: widget.profiles, + profileId: widget.effectiveProfileId, + busy: _busy, + failed: _failed, + ); + + @override + void didUpdateWidget(covariant ChatCompressionSelector oldWidget) { + super.didUpdateWidget(oldWidget); + // The sheet route is not below this widget, so it can't be marked dirty + // during this build. + SchedulerBinding.instance.addPostFrameCallback((_) { + if (mounted) _view.value = _snapshot(); + }); + } + + @override + void dispose() { + _view.dispose(); + super.dispose(); + } + + void _setBusy(bool busy, {required bool failed}) { + setState(() { + _busy = busy; + _failed = failed; + }); + _view.value = _snapshot(); + } + + /// Runs one save; returns whether it succeeded. + Future _save(Future Function() write) async { + if (_busy || !widget.enabled) return false; + _setBusy(true, failed: false); + var ok = false; + try { + await write(); + ok = true; + } catch (e) { + debugPrint('[ChatCompressionSelector] save failed: $e'); + } + if (mounted) _setBusy(false, failed: !ok); + return ok; + } + + Future _openSheet() async { + if (_failed) _setBusy(false, failed: false); + await showMeshSheet( + context, + builder: (sheetContext) => ValueListenableBuilder<_SelectorView>( + valueListenable: _view, + builder: (sheetContext, view, _) => _buildSheet(sheetContext, view), + ), + ); + } + + Widget _buildSheet(BuildContext context, _SelectorView view) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final canChange = view.enabled && !view.busy; + + MeshSheetOption option(ChatCompressionMode mode, String description) { + return MeshSheetOption( + label: chatCompressionModeLabel(context, mode), + subtitle: description, + selected: view.mode == mode, + onTap: canChange + ? () async { + final ok = await _save(() => widget.onModeChanged(mode)); + // Cyr2Lat stays open so its profile can be picked. + if (ok && mode != ChatCompressionMode.cyr2lat) { + if (context.mounted) Navigator.of(context).maybePop(); + } + } + : null, + ); + } + + final profileValue = view.profileId; + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: l10n.chatCompression_title, + subtitle: l10n.chatCompression_sheetSubtitle, + trailing: view.busy + ? const Padding( + padding: EdgeInsets.all(8), + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ) + : null, + ), + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.only(bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (view.failed) + Container( + margin: const EdgeInsets.fromLTRB(16, 8, 16, 8), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: scheme.errorContainer, + borderRadius: BorderRadius.circular(MeshRadii.sm), + ), + child: Row( + children: [ + Icon( + Icons.error_outline, + color: scheme.onErrorContainer, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + l10n.chatCompression_saveFailed, + style: Theme.of(context).textTheme.bodyMedium + ?.copyWith(color: scheme.onErrorContainer), + ), + ), + ], + ), + ), + if (!view.enabled && widget.disabledReason != null) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Text( + widget.disabledReason!, + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + option( + ChatCompressionMode.off, + l10n.chatCompression_offDescription, + ), + option( + ChatCompressionMode.smaz, + l10n.chatCompression_smazDescription, + ), + option( + ChatCompressionMode.cyr2lat, + l10n.chatCompression_cyr2latDescription, + ), + if (view.mode == ChatCompressionMode.cyr2lat && + view.profiles.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: DropdownButtonFormField( + // Rebuild with the saved value after a change or failure. + key: ValueKey(profileValue), + isExpanded: true, + initialValue: profileValue, + decoration: InputDecoration( + labelText: l10n.chatCompression_profile, + border: const OutlineInputBorder(), + ), + items: [ + for (final profile in view.profiles) + DropdownMenuItem( + value: profile.id, + child: Text( + profile.name, + overflow: TextOverflow.ellipsis, + ), + ), + ], + onChanged: canChange + ? (id) { + if (id == null || id == profileValue) return; + _save(() => widget.onProfileChanged(id)); + } + : null, + ), + ), + ], + ), + ), + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final l10n = context.l10n; + final label = l10n.chatCompression_label( + chatCompressionModeLabel(context, widget.mode), + ); + final reason = widget.enabled ? null : widget.disabledReason; + + // One short row: the chat already leaves little room for messages at + // large text sizes, so a disabled strip explains itself in the sheet. + return Material( + color: scheme.surfaceContainerLow, + child: DecoratedBox( + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: scheme.outlineVariant)), + ), + child: MergeSemantics( + child: Semantics( + button: true, + enabled: !_busy, + label: reason == null ? label : '$label. $reason', + hint: l10n.chatCompression_changeHint, + child: InkWell( + onTap: _busy ? null : _openSheet, + child: ExcludeSemantics( + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 48), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Flexible( + child: Text( + label, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + ), + const SizedBox(width: 4), + if (_busy) + const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + else + Icon( + widget.enabled + ? Icons.arrow_drop_down + : Icons.lock_outline, + color: scheme.onSurfaceVariant, + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/mesh_nav_tile.dart b/lib/widgets/mesh_nav_tile.dart index 9838f4b2..f5771371 100644 --- a/lib/widgets/mesh_nav_tile.dart +++ b/lib/widgets/mesh_nav_tile.dart @@ -119,14 +119,18 @@ class MeshNavTile extends StatelessWidget { } /// One radio-style option row inside a bottom sheet picker. +/// The selected row shows a filled radio icon and a bold title, so the +/// choice never depends on colour alone. A null [onTap] disables the row. class MeshSheetOption extends StatelessWidget { final String label; + final String? subtitle; final bool selected; - final VoidCallback onTap; + final VoidCallback? onTap; const MeshSheetOption({ super.key, required this.label, + this.subtitle, required this.selected, required this.onTap, }); @@ -134,14 +138,23 @@ class MeshSheetOption extends StatelessWidget { @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; - return ListTile( - leading: Icon( - selected ? Icons.radio_button_checked : Icons.radio_button_unchecked, - size: 24, - color: selected ? scheme.primary : scheme.onSurfaceVariant, + return Semantics( + selected: selected, + inMutuallyExclusiveGroup: true, + child: ListTile( + leading: Icon( + selected ? Icons.radio_button_checked : Icons.radio_button_unchecked, + size: 24, + color: selected ? scheme.primary : scheme.onSurfaceVariant, + ), + title: Text( + label, + style: selected ? const TextStyle(fontWeight: FontWeight.w700) : null, + ), + subtitle: subtitle == null ? null : Text(subtitle!), + enabled: onTap != null, + onTap: onTap, ), - title: Text(label), - onTap: onTap, ); } } diff --git a/test/connector/channel_slot_map_test.dart b/test/connector/channel_slot_map_test.dart index cdcbafa7..870cc37a 100644 --- a/test/connector/channel_slot_map_test.dart +++ b/test/connector/channel_slot_map_test.dart @@ -7,6 +7,7 @@ import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/models/channel.dart'; import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/chat_compression_mode.dart'; import 'package:meshcore_open/review_mode/review_frames.dart'; import 'package:meshcore_open/review_mode/review_radio.dart'; import 'package:meshcore_open/review_mode/review_script.dart'; @@ -201,7 +202,7 @@ void main() { 'another slot brings its history back', () async { await _connect(_TestRadio()); await _waitFor(() => _texts(1).contains(_queuedHikingText)); - await _connector.setChannelSmazEnabled(1, true); + await _connector.setChannelCompressionMode(1, ChatCompressionMode.smaz); await _connector.setChannel(1, 'Hiking Group', ghostPsk); expect(_connector.channelIdForSlot(1), ghostId); @@ -408,7 +409,7 @@ void main() { expect(_texts(5), _texts(1)); // Settings are stored per channel, so both slots see a change. - await _connector.setChannelSmazEnabled(5, true); + await _connector.setChannelCompressionMode(5, ChatCompressionMode.smaz); expect(_connector.isChannelSmazEnabled(1), isTrue); await _connector.setChannelRegion(1, 'test-region'); expect(_connector.getChannelRegion(5), 'test-region'); diff --git a/test/connector/chat_compression_mode_test.dart b/test/connector/chat_compression_mode_test.dart new file mode 100644 index 00000000..2f3bc7a0 --- /dev/null +++ b/test/connector/chat_compression_mode_test.dart @@ -0,0 +1,163 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/chat_compression_mode.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/channel_settings_store.dart'; +import 'package:meshcore_open/storage/contact_settings_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _contactKey = + '1111111111111111111111111111111111111111111111111111111111111111'; + +Future _waitFor(bool Function() condition) async { + final end = DateTime.now().add(const Duration(seconds: 8)); + while (!condition()) { + if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); + await Future.delayed(const Duration(milliseconds: 20)); + } +} + +ContactSettingsStore _contactStore() => + ContactSettingsStore()..setPublicKeyHex = ReviewRadio.selfPublicKeyHex; + +ChannelSettingsStore _channelStore() => + ChannelSettingsStore()..setPublicKeyHex = ReviewRadio.selfPublicKeyHex; + +Future<(bool, bool)> _savedContactFlags() async => ( + await _contactStore().loadSmazEnabled(_contactKey), + await _contactStore().loadCyr2LatEnabled(_contactKey), +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MeshCoreConnector connector; + + // The connector's frame streams can only be listened to once per process, + // so the tests share one connected review radio. + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = MeshCoreConnector(); + final retryService = MessageRetryService(); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + await _waitFor(() => connector.channelMapConfirmed); + addTearDown(() async { + await connector.disconnect(); + connector.dispose(); + retryService.dispose(); + }); + }); + + test('contact modes are mutually exclusive and saved', () async { + expect( + connector.contactCompressionMode(_contactKey), + ChatCompressionMode.off, + ); + + await connector.setContactCompressionMode( + _contactKey, + ChatCompressionMode.smaz, + ); + expect(connector.isContactSmazEnabled(_contactKey), isTrue); + expect(connector.isContactCyr2LatEnabled(_contactKey), isFalse); + expect(await _savedContactFlags(), (true, false)); + + await connector.setContactCompressionMode( + _contactKey, + ChatCompressionMode.cyr2lat, + ); + expect( + connector.contactCompressionMode(_contactKey), + ChatCompressionMode.cyr2lat, + ); + expect(connector.isContactSmazEnabled(_contactKey), isFalse); + expect(await _savedContactFlags(), (false, true)); + + await connector.setContactCompressionMode( + _contactKey, + ChatCompressionMode.off, + ); + expect( + connector.contactCompressionMode(_contactKey), + ChatCompressionMode.off, + ); + expect(await _savedContactFlags(), (false, false)); + }); + + test('overlapping contact choices end on the last one, never both', () async { + final writes = [ + connector.setContactCompressionMode( + _contactKey, + ChatCompressionMode.smaz, + ), + connector.setContactCompressionMode( + _contactKey, + ChatCompressionMode.cyr2lat, + ), + connector.setContactCompressionMode( + _contactKey, + ChatCompressionMode.smaz, + ), + ]; + await Future.wait(writes); + expect( + connector.contactCompressionMode(_contactKey), + ChatCompressionMode.smaz, + ); + expect(connector.isContactCyr2LatEnabled(_contactKey), isFalse); + expect(await _savedContactFlags(), (true, false)); + }); + + test( + 'channel modes are mutually exclusive and saved by channel ID', + () async { + final channelId = connector.channelIdForSlot(1)!; + + await connector.setChannelCompressionMode(1, ChatCompressionMode.cyr2lat); + expect(connector.channelCompressionMode(1), ChatCompressionMode.cyr2lat); + expect(await _channelStore().loadCyr2LatEnabled(channelId), isTrue); + expect(await _channelStore().loadSmazEnabled(channelId), isFalse); + + await connector.setChannelCompressionMode(1, ChatCompressionMode.smaz); + expect(connector.channelCompressionMode(1), ChatCompressionMode.smaz); + expect(connector.isChannelCyr2LatEnabled(1), isFalse); + expect(await _channelStore().loadCyr2LatEnabled(channelId), isFalse); + expect(await _channelStore().loadSmazEnabled(channelId), isTrue); + + // Other channels are untouched. + expect(connector.channelCompressionMode(0), ChatCompressionMode.off); + }, + ); + + test('a channel slot without a storage ID is refused', () async { + const emptySlot = 30; + expect(connector.channelIdForSlot(emptySlot), isNull); + await expectLater( + connector.setChannelCompressionMode(emptySlot, ChatCompressionMode.smaz), + throwsStateError, + ); + expect( + connector.channelCompressionMode(emptySlot), + ChatCompressionMode.off, + ); + + // A refused write does not block later ones. + await connector.setChannelCompressionMode(1, ChatCompressionMode.smaz); + expect(connector.channelCompressionMode(1), ChatCompressionMode.smaz); + }); +} diff --git a/test/screens/offline_mode_test.dart b/test/screens/offline_mode_test.dart index a381d195..fb827588 100644 --- a/test/screens/offline_mode_test.dart +++ b/test/screens/offline_mode_test.dart @@ -34,13 +34,17 @@ import 'package:meshcore_open/services/timeout_prediction_service.dart'; import 'package:meshcore_open/services/translation_service.dart'; import 'package:meshcore_open/services/ui_view_state_service.dart'; import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_settings_store.dart'; +import 'package:meshcore_open/storage/contact_settings_store.dart'; import 'package:meshcore_open/storage/channel_store.dart'; import 'package:meshcore_open/storage/contact_store.dart'; import 'package:meshcore_open/storage/last_radio_store.dart'; import 'package:meshcore_open/storage/message_store.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/chat_background.dart'; import 'package:meshcore_open/widgets/chat_composer.dart'; +import 'package:meshcore_open/widgets/chat_compression_selector.dart'; import 'package:meshcore_open/widgets/connect_sheet.dart'; final _radioKey = Uint8List.fromList(List.generate(32, (i) => 0xA0 + i)); @@ -344,4 +348,246 @@ void main() { await tester.pumpWidget(const SizedBox()); await tester.pump(const Duration(minutes: 1)); }); + + group('compression selector', () { + Future choose(WidgetTester tester, String mode) async { + await tester.tap(find.byType(ChatCompressionSelector)); + await _settle(tester); + await tester.tap(find.text(mode)); + await _settle(tester); + // Connector notifications are debounced on a real timer. + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 200)), + ); + await _settle(tester); + } + + testWidgets('DM chat shows it at the top and saves offline', ( + tester, + ) async { + final connector = await _offlineConnector(tester); + final alice = connector.contacts.single; + final store = ContactSettingsStore()..setPublicKeyHex = _radioHex; + await tester.pumpWidget( + await _app(tester, connector, ChatScreen(contact: alice)), + ); + await _settle(tester); + + expect(find.byType(ChatCompressionSelector), findsOneWidget); + expect(find.text(_l10n.chatCompression_label('Off')), findsOneWidget); + // Above the transcript, outside its scroll view. + expect( + find.ancestor( + of: find.byType(ChatCompressionSelector), + matching: find.byType(Scrollable), + ), + findsNothing, + ); + expect( + tester.getBottomLeft(find.byType(ChatCompressionSelector)).dy, + lessThanOrEqualTo(tester.getTopLeft(find.byType(ChatBackdrop)).dy), + ); + + await choose(tester, _l10n.chatCompression_smaz); + expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget); + expect( + await tester.runAsync(() => store.loadSmazEnabled(alice.publicKeyHex)), + isTrue, + ); + + await choose(tester, _l10n.chatCompression_cyr2lat); + // Cyr2Lat keeps the sheet open for its profile picker. + await tester.tap(find.byTooltip('Close')); + await _settle(tester); + expect(find.text(_l10n.chatCompression_label('Cyr2Lat')), findsOneWidget); + expect( + connector.contactCompressionMode(alice.publicKeyHex), + ChatCompressionMode.cyr2lat, + ); + expect( + await tester.runAsync(() => store.loadSmazEnabled(alice.publicKeyHex)), + isFalse, + ); + expect( + await tester.runAsync( + () => store.loadCyr2LatEnabled(alice.publicKeyHex), + ), + isTrue, + ); + + // The settings dialog no longer carries the compression switches. + await tester.tap(find.byIcon(Icons.more_vert)); + await _settle(tester); + await tester.tap(find.text(_l10n.contact_settings).last); + await _settle(tester); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.textContaining(RegExp('SMAZ|Cyr2Lat')), + ), + findsNothing, + ); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('channel chat uses the same selector and saves offline', ( + tester, + ) async { + final connector = await _offlineConnector(tester); + final channel = connector.channels.single; + final store = ChannelSettingsStore()..setPublicKeyHex = _radioHex; + await tester.pumpWidget( + await _app(tester, connector, ChannelChatScreen(channel: channel)), + ); + await _settle(tester); + + expect(find.byType(ChatCompressionSelector), findsOneWidget); + expect(find.text(_l10n.chatCompression_label('Off')), findsOneWidget); + + await choose(tester, _l10n.chatCompression_smaz); + expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget); + expect( + await tester.runAsync(() => store.loadSmazEnabled(channel.storageId!)), + isTrue, + ); + expect( + await tester.runAsync( + () => store.loadCyr2LatEnabled(channel.storageId!), + ), + isFalse, + ); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('saving the channel edit sheet leaves compression alone', ( + tester, + ) async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await tester.runAsync(connector.connectReview); + await _waitFor(tester, () => connector.channelMapConfirmed); + final channel = connector.channels.firstWhere((c) => c.index == 1); + await tester.runAsync( + () => connector.setChannelCompressionMode(1, ChatCompressionMode.smaz), + ); + + await tester.pumpWidget( + await _app( + tester, + connector, + Builder( + builder: (context) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => + showEditChannelSheet(context, connector, channel), + child: const Text('edit'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('edit')); + await _settle(tester); + expect(find.text('SMAZ compression'), findsNothing); + + // The chat's selector changes the mode while the sheet is open. + await tester.runAsync( + () => + connector.setChannelCompressionMode(1, ChatCompressionMode.cyr2lat), + ); + await tester.enterText(find.byType(TextField).first, 'Hiking Crew'); + await tester.tap(find.text(_l10n.common_save)); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 500)), + ); + await _settle(tester); + + expect( + connector.channels.firstWhere((c) => c.index == 1).name, + 'Hiking Crew', + ); + expect(connector.channelCompressionMode(1), ChatCompressionMode.cyr2lat); + + await tester.runAsync(connector.disconnect); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); + }); + + testWidgets('a new PSK in the channel edit sheet keeps compression', ( + tester, + ) async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await tester.runAsync(connector.connectReview); + await _waitFor(tester, () => connector.channelMapConfirmed); + final channel = connector.channels.firstWhere((c) => c.index == 1); + final oldId = connector.channelIdForSlot(1); + await tester.runAsync( + () => connector.setChannelCompressionMode(1, ChatCompressionMode.smaz), + ); + + await tester.pumpWidget( + await _app( + tester, + connector, + Builder( + builder: (context) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => + showEditChannelSheet(context, connector, channel), + child: const Text('edit'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('edit')); + await _settle(tester); + await tester.enterText(find.byType(TextField).at(1), '0f' * 16); + await tester.tap(find.text(_l10n.common_save)); + // The save runs in the test zone and waits on the radio's real I/O. + for (var i = 0; i < 40; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pump(const Duration(milliseconds: 100)); + if (find + .text(_l10n.channels_channelUpdated(channel.name)) + .evaluate() + .isNotEmpty) { + break; + } + } + await _settle(tester); + + final newId = connector.channelIdForSlot(1); + expect(newId, isNot(oldId)); + expect(connector.channelCompressionMode(1), ChatCompressionMode.smaz); + final store = ChannelSettingsStore() + ..setPublicKeyHex = connector.selfPublicKeyHex; + expect( + await tester.runAsync(() => store.loadSmazEnabled(newId!)), + isTrue, + ); + + await tester.runAsync(connector.disconnect); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); + }); + }); } diff --git a/test/widgets/chat_compression_selector_test.dart b/test/widgets/chat_compression_selector_test.dart new file mode 100644 index 00000000..a3ad6633 --- /dev/null +++ b/test/widgets/chat_compression_selector_test.dart @@ -0,0 +1,313 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/chat_compression_selector.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +final _profiles = [ + Cyr2LatProfile(id: 'ru', name: 'Russian', charMap: const {'А': 'A'}), + Cyr2LatProfile(id: 'sr', name: 'Serbian', charMap: const {'З': '3'}), +]; + +/// Stands in for a chat screen: keeps the "saved" state and applies a change +/// only when the test completes the pending write. +class _Host extends StatefulWidget { + final ChatCompressionMode initialMode; + final bool enabled; + final String? initialProfileId; + final List modeCalls; + final List profileCalls; + final List> pending; + + const _Host({ + this.initialMode = ChatCompressionMode.off, + this.enabled = true, + this.initialProfileId, + required this.modeCalls, + required this.profileCalls, + required this.pending, + }); + + @override + State<_Host> createState() => _HostState(); +} + +class _HostState extends State<_Host> { + late ChatCompressionMode _mode = widget.initialMode; + late String? _profileId = widget.initialProfileId; + + Future _write(void Function() apply) async { + final completer = Completer(); + widget.pending.add(completer); + await completer.future; + if (mounted) setState(apply); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Chat')), + body: Column( + children: [ + ChatCompressionSelector( + mode: _mode, + enabled: widget.enabled, + disabledReason: widget.enabled + ? null + : _l10n.chatCompression_noStorageId, + profiles: _profiles, + profileId: _profileId, + defaultProfileId: 'ru', + onModeChanged: (mode) { + widget.modeCalls.add(mode); + return _write(() => _mode = mode); + }, + onProfileChanged: (id) { + widget.profileCalls.add(id); + return _write(() => _profileId = id); + }, + ), + const Expanded(child: Placeholder()), + ], + ), + ); + } +} + +void main() { + late List modeCalls; + late List profileCalls; + late List> pending; + + setUp(() { + modeCalls = []; + profileCalls = []; + pending = []; + }); + + Future pumpHost( + WidgetTester tester, { + ChatCompressionMode mode = ChatCompressionMode.off, + bool enabled = true, + String? profileId, + Size size = const Size(400, 800), + double textScale = 1.0, + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + theme: MeshTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: _Host( + initialMode: mode, + enabled: enabled, + initialProfileId: profileId, + modeCalls: modeCalls, + profileCalls: profileCalls, + pending: pending, + ), + ), + ); + } + + Future openSheet(WidgetTester tester) async { + await tester.tap(find.byType(ChatCompressionSelector)); + await tester.pumpAndSettle(); + } + + Finder optionRow(String label) => + find.ancestor(of: find.text(label), matching: find.byType(ListTile)); + + bool isSelected(WidgetTester tester, String label) { + final row = optionRow(label); + return find + .descendant(of: row, matching: find.byIcon(Icons.radio_button_checked)) + .evaluate() + .isNotEmpty; + } + + testWidgets('shows the saved mode and announces it', (tester) async { + final semantics = tester.ensureSemantics(); + await pumpHost(tester, mode: ChatCompressionMode.smaz); + + expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget); + expect( + tester.getSemantics( + find.bySemanticsLabel(_l10n.chatCompression_label('SMAZ')), + ), + isSemantics( + label: _l10n.chatCompression_label('SMAZ'), + hint: _l10n.chatCompression_changeHint, + isButton: true, + isEnabled: true, + hasTapAction: true, + ), + ); + expect( + tester.getSize(find.byType(ChatCompressionSelector)).height, + greaterThanOrEqualTo(48), + ); + semantics.dispose(); + }); + + testWidgets('one sheet lists the three modes with their explanations', ( + tester, + ) async { + await pumpHost(tester); + await openSheet(tester); + + expect(find.text(_l10n.chatCompression_title), findsOneWidget); + expect(find.text(_l10n.chatCompression_off), findsOneWidget); + expect(find.text(_l10n.chatCompression_smaz), findsOneWidget); + expect(find.text(_l10n.chatCompression_cyr2lat), findsOneWidget); + expect(find.text(_l10n.chatCompression_offDescription), findsOneWidget); + expect(find.text(_l10n.chatCompression_smazDescription), findsOneWidget); + expect(find.text(_l10n.chatCompression_cyr2latDescription), findsOneWidget); + expect(isSelected(tester, _l10n.chatCompression_off), isTrue); + expect(isSelected(tester, _l10n.chatCompression_smaz), isFalse); + // No profile picker unless Cyr2Lat is chosen. + expect(find.text(_l10n.chatCompression_profile), findsNothing); + expect(find.byType(Dialog), findsNothing); + }); + + testWidgets('a choice shows only after it is saved, then the sheet closes', ( + tester, + ) async { + await pumpHost(tester); + await openSheet(tester); + + await tester.tap(find.text(_l10n.chatCompression_smaz)); + await tester.pump(); + expect(modeCalls, [ChatCompressionMode.smaz]); + // Still saving: old mode shown, options locked against rapid taps. + expect(isSelected(tester, _l10n.chatCompression_off), isTrue); + expect( + tester.widget(optionRow(_l10n.chatCompression_cyr2lat)).enabled, + isFalse, + ); + await tester.tap(find.text(_l10n.chatCompression_cyr2lat)); + await tester.pump(); + expect(modeCalls, [ChatCompressionMode.smaz]); + + pending.single.complete(); + await tester.pumpAndSettle(); + expect(find.text(_l10n.chatCompression_title), findsNothing); + expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget); + }); + + testWidgets('Cyr2Lat keeps the sheet open with its profile picker', ( + tester, + ) async { + await pumpHost(tester); + await openSheet(tester); + + await tester.tap(find.text(_l10n.chatCompression_cyr2lat)); + await tester.pump(); + pending.removeAt(0).complete(); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.chatCompression_title), findsOneWidget); + expect(isSelected(tester, _l10n.chatCompression_cyr2lat), isTrue); + expect(find.text(_l10n.chatCompression_profile), findsOneWidget); + // No profile saved for the chat: the app-wide one is what sending uses. + expect(find.text('Russian'), findsOneWidget); + + await tester.ensureVisible(find.text('Russian')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Russian')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Serbian').last); + await tester.pump(); + expect(profileCalls, ['sr']); + pending.removeAt(0).complete(); + await tester.pumpAndSettle(); + expect(find.text('Serbian'), findsOneWidget); + expect(find.text(_l10n.chatCompression_label('Cyr2Lat')), findsOneWidget); + }); + + testWidgets('a failed save keeps the saved mode and says so', (tester) async { + await pumpHost(tester, mode: ChatCompressionMode.smaz); + await openSheet(tester); + + await tester.tap(find.text(_l10n.chatCompression_cyr2lat)); + await tester.pump(); + pending.single.completeError(StateError('disk full')); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget); + expect(isSelected(tester, _l10n.chatCompression_smaz), isTrue); + expect(isSelected(tester, _l10n.chatCompression_cyr2lat), isFalse); + expect( + tester.widget(optionRow(_l10n.chatCompression_off)).enabled, + isTrue, + ); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget); + }); + + testWidgets('disabled shows the saved mode, and the sheet says why and ' + 'allows no change', (tester) async { + final semantics = tester.ensureSemantics(); + await pumpHost(tester, mode: ChatCompressionMode.smaz, enabled: false); + + final label = _l10n.chatCompression_label('SMAZ'); + expect(find.text(label), findsOneWidget); + expect(find.byIcon(Icons.lock_outline), findsOneWidget); + expect( + find.bySemanticsLabel('$label. ${_l10n.chatCompression_noStorageId}'), + findsOneWidget, + ); + + await openSheet(tester); + expect(find.text(_l10n.chatCompression_noStorageId), findsOneWidget); + expect(isSelected(tester, _l10n.chatCompression_smaz), isTrue); + for (final mode in [ + _l10n.chatCompression_off, + _l10n.chatCompression_smaz, + _l10n.chatCompression_cyr2lat, + ]) { + expect(tester.widget(optionRow(mode)).enabled, isFalse); + } + await tester.tap(find.text(_l10n.chatCompression_off), warnIfMissed: false); + await tester.pumpAndSettle(); + expect(modeCalls, isEmpty); + semantics.dispose(); + }); + + for (final scale in [1.3, 2.0]) { + testWidgets('fits a 320dp phone at ${scale}x text', (tester) async { + await pumpHost( + tester, + mode: ChatCompressionMode.cyr2lat, + enabled: true, + size: const Size(320, 568), + textScale: scale, + ); + expect(tester.takeException(), isNull); + await openSheet(tester); + expect(tester.takeException(), isNull); + // The sheet scrolls to its last option and the profile picker. + await tester.scrollUntilVisible( + find.text(_l10n.chatCompression_profile), + 200, + scrollable: find.byType(Scrollable).last, + ); + expect(tester.takeException(), isNull); + }); + } +} From 7e04dda4d98a0e8f66dd6ecd128b81e1be28392b Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 11/50] Show current group members first in the group editor Members are listed first with a remove button each, followed by a searchable list of contacts that are not in the group yet. --- documentation/contacts.md | 6 +- documentation/design.md | 1 + lib/l10n/app_en.arb | 25 ++ lib/l10n/app_localizations.dart | 24 ++ lib/l10n/app_localizations_bg.dart | 18 ++ lib/l10n/app_localizations_cs.dart | 18 ++ lib/l10n/app_localizations_de.dart | 18 ++ lib/l10n/app_localizations_en.dart | 18 ++ lib/l10n/app_localizations_es.dart | 18 ++ lib/l10n/app_localizations_fr.dart | 18 ++ lib/l10n/app_localizations_hu.dart | 18 ++ lib/l10n/app_localizations_it.dart | 18 ++ lib/l10n/app_localizations_ja.dart | 18 ++ lib/l10n/app_localizations_ko.dart | 18 ++ lib/l10n/app_localizations_nl.dart | 18 ++ lib/l10n/app_localizations_pl.dart | 18 ++ lib/l10n/app_localizations_pt.dart | 18 ++ lib/l10n/app_localizations_ru.dart | 18 ++ lib/l10n/app_localizations_sk.dart | 18 ++ lib/l10n/app_localizations_sl.dart | 18 ++ lib/l10n/app_localizations_sv.dart | 18 ++ lib/l10n/app_localizations_uk.dart | 18 ++ lib/l10n/app_localizations_zh.dart | 18 ++ lib/screens/contacts_screen.dart | 239 +++--------------- lib/widgets/contact_group_editor_dialog.dart | 220 ++++++++++++++++ .../contact_group_editor_dialog_test.dart | 228 +++++++++++++++++ 26 files changed, 881 insertions(+), 204 deletions(-) create mode 100644 lib/widgets/contact_group_editor_dialog.dart create mode 100644 test/widgets/contact_group_editor_dialog_test.dart diff --git a/documentation/contacts.md b/documentation/contacts.md index 69559665..061f91f0 100644 --- a/documentation/contacts.md +++ b/documentation/contacts.md @@ -54,14 +54,16 @@ A toolbar at the top provides: Groups are a client-side organizational feature for grouping contacts. -- **Create a group**: Tap the group dropdown → "+" icon → enter name → select members → Save +- **Create a group**: Tap the group dropdown → "+" icon → enter name → add members → Save - **Edit a group**: Group dropdown → pencil icon next to the group - **Delete a group**: Group dropdown → trash icon next to the group - **Filter by group**: Select a group from the dropdown to show only its members Groups are stored per radio identity (scoped by public key). -**Validation rules**: Group names cannot be empty, cannot be "all" (reserved, case-insensitive), and must be unique (case-insensitive). The group creation dialog includes a built-in search field to filter contacts when selecting members. Creating a new group automatically selects it as the active filter. +The group editor lists **Current members (N)** first, each with a remove button. Below it, **Add contacts** has a search field and lists only contacts that are not members yet; tap a row or its add button to add it. Changes apply when you tap Save. Removing a member only changes the group; the contact stays on the radio. + +**Validation rules**: Group names cannot be empty, cannot be "all" (reserved, case-insensitive), and must be unique (case-insensitive). Creating a new group automatically selects it as the active filter. ## Tap Actions diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..7353a577 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -119,6 +119,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Settings switch | `SwitchListTile` inside `MeshSettingsTileTheme` | Wrap the settings screen body once in `MeshSettingsTileTheme` | | Radio-style choice in a sheet | `MeshSheetOption` | Used by the language picker and map time filter | | Choosing between images | Selectable thumbnail tiles in a centred `Wrap` | Image send versions (`_versionTile` in `image_send_preview_sheet.dart`). `InkWell` with `MeshRadii.sm`; selected tile gets a 3px `primary` border **and** a `primary` check badge (never colour alone); caption under the tile in `bodySmall`, w600 when selected; figures such as packet counts in `MeshTheme.mono` 12; wrap the tile in `Semantics(button: true, selected:, label:)` | +| Editing a set of members | Current items first, then a searchable add list | Group editor (`contact_group_editor_dialog.dart`). Wrapping upper-case section label with the count ("Current members (N)"); each member row has a trailing `IconButton` remove (`error` colour, tooltip names the item); the add list excludes current members, and tapping the row or its `primary` add button adds it | | Popup menu row | **always** `PopupMenuItem(child: MeshMenuItemRow(icon:, label:))` | Label wraps to 2 lines then ellipsizes; `leading:` for `ThemedIcon`; no icon keeps the 20px slot | | Segmented button label | **always** `ButtonSegment(label: MeshSegmentLabel(text))` | Shrinks to 12 (before system scale), then wraps at word boundaries onto 2 centred lines; never breaks a word | | Status | `StatusChip` | Mono label, coloured dot or icon | diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..2eda26f9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -843,6 +843,31 @@ "contacts_filterContacts": "Filter contacts...", "contacts_noContactsMatchFilter": "No contacts match your filter", "contacts_noMembers": "No members", + "contacts_groupCurrentMembers": "Current members ({count})", + "@contacts_groupCurrentMembers": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "contacts_groupAddContacts": "Add contacts", + "contacts_groupRemoveMember": "Remove {name} from group", + "@contacts_groupRemoveMember": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "contacts_groupAddMember": "Add {name} to group", + "@contacts_groupAddMember": { + "placeholders": { + "name": { + "type": "String" + } + } + }, "contacts_lastSeenNow": "recently", "contacts_lastSeenMinsAgo": "~ {minutes} min.", "@contacts_lastSeenMinsAgo": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..da59a735 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3289,6 +3289,30 @@ abstract class AppLocalizations { /// **'No members'** String get contacts_noMembers; + /// No description provided for @contacts_groupCurrentMembers. + /// + /// In en, this message translates to: + /// **'Current members ({count})'** + String contacts_groupCurrentMembers(int count); + + /// No description provided for @contacts_groupAddContacts. + /// + /// In en, this message translates to: + /// **'Add contacts'** + String get contacts_groupAddContacts; + + /// No description provided for @contacts_groupRemoveMember. + /// + /// In en, this message translates to: + /// **'Remove {name} from group'** + String contacts_groupRemoveMember(String name); + + /// No description provided for @contacts_groupAddMember. + /// + /// In en, this message translates to: + /// **'Add {name} to group'** + String contacts_groupAddMember(String name); + /// No description provided for @contacts_lastSeenNow. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..07f4e295 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1835,6 +1835,24 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_noMembers => 'Няма членове'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'наскоро'; diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..77537496 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -1822,6 +1822,24 @@ class AppLocalizationsCs extends AppLocalizations { @override String get contacts_noMembers => 'Žádní členové'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'nedávno'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..52c913a3 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1835,6 +1835,24 @@ class AppLocalizationsDe extends AppLocalizations { @override String get contacts_noMembers => 'Keine Mitglieder'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'gerade eben'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..6edcc376 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1802,6 +1802,24 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_noMembers => 'No members'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'recently'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..e8eb5b8a 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1827,6 +1827,24 @@ class AppLocalizationsEs extends AppLocalizations { @override String get contacts_noMembers => 'No miembros'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'Reciente'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..7039d5a8 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1832,6 +1832,24 @@ class AppLocalizationsFr extends AppLocalizations { @override String get contacts_noMembers => 'Aucun membre'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'À l\'instant'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..8f64ca41 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1825,6 +1825,24 @@ class AppLocalizationsHu extends AppLocalizations { @override String get contacts_noMembers => 'Nincsenek tagok'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'nemrég'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..64d6135a 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1829,6 +1829,24 @@ class AppLocalizationsIt extends AppLocalizations { @override String get contacts_noMembers => 'Nessun membro'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'Poco fa'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..9057225e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1738,6 +1738,24 @@ class AppLocalizationsJa extends AppLocalizations { @override String get contacts_noMembers => 'メンバーなし'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => '最近'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..bd9126f2 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1742,6 +1742,24 @@ class AppLocalizationsKo extends AppLocalizations { @override String get contacts_noMembers => '회원 없음'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => '최근'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..9a71a0e0 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1821,6 +1821,24 @@ class AppLocalizationsNl extends AppLocalizations { @override String get contacts_noMembers => 'Geen leden'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'recent'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..1354003b 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1843,6 +1843,24 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contacts_noMembers => 'Brak członków'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'niedawno'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..67226951 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1828,6 +1828,24 @@ class AppLocalizationsPt extends AppLocalizations { @override String get contacts_noMembers => 'Nenhum membro'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'Recente'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..2530d40f 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1827,6 +1827,24 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contacts_noMembers => 'Нет участников'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'недавно'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..9cdd8f60 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1821,6 +1821,24 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contacts_noMembers => 'Žiadni členovia'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'nedávno'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..b5b55f4c 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1819,6 +1819,24 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_noMembers => 'Ni članov.'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'pravkar'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..acf7aff5 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1809,6 +1809,24 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contacts_noMembers => 'Inga medlemmar'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'nyss'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..2dbd8b76 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1823,6 +1823,24 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_noMembers => 'Немає учасників'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => 'нещодавно'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..9fdf206b 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1712,6 +1712,24 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_noMembers => '暂无成员'; + @override + String contacts_groupCurrentMembers(int count) { + return 'Current members ($count)'; + } + + @override + String get contacts_groupAddContacts => 'Add contacts'; + + @override + String contacts_groupRemoveMember(String name) { + return 'Remove $name from group'; + } + + @override + String contacts_groupAddMember(String name) { + return 'Add $name to group'; + } + @override String get contacts_lastSeenNow => '刚刚'; diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 2d60dd3a..2384df24 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -25,6 +25,7 @@ import '../widgets/connect_sheet.dart'; import '../utils/radio_guard.dart'; import '../utils/emoji_utils.dart'; import '../utils/route_transitions.dart'; +import '../widgets/contact_group_editor_dialog.dart'; import '../widgets/contact_visuals.dart'; import '../widgets/list_filter_widget.dart'; import '../widgets/empty_state.dart'; @@ -1395,182 +1396,44 @@ class _ContactsScreenState extends State { return; } final isEditing = group != null; - final nameController = TextEditingController(text: group?.name ?? ''); - final selectedKeys = {...group?.memberKeys ?? []}; - String filterQuery = ''; - final sortedContacts = List.from(contacts) - ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); - showDialog( context: context, - builder: (dialogContext) => _DisposeControllerOnUnmount( - controller: nameController, - child: StatefulBuilder( - builder: (builderContext, setDialogState) { - final filteredContacts = filterQuery.isEmpty - ? sortedContacts - : sortedContacts - .where( - (contact) => matchesContactQuery(contact, filterQuery), - ) - .toList(); - return AlertDialog( - title: Text( - isEditing - ? context.l10n.contacts_editGroup - : context.l10n.contacts_newGroup, - ), - content: SizedBox( - width: double.maxFinite, - child: ConstrainedBox( - constraints: BoxConstraints( - maxHeight: MediaQuery.of(context).size.height * 0.8, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: nameController, - decoration: InputDecoration( - labelText: context.l10n.contacts_groupName, - border: const OutlineInputBorder(), - ), - ), - const SizedBox(height: 12), - TextField( - decoration: InputDecoration( - hintText: context.l10n.contacts_filterContacts, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: true, - ), - onChanged: (value) { - setDialogState(() { - filterQuery = value.toLowerCase(); - }); - }, - ), - const SizedBox(height: 12), - Expanded( - child: filteredContacts.isEmpty - ? Center( - child: Text( - context.l10n.contacts_noContactsMatchFilter, - ), - ) - : ListView.builder( - itemCount: filteredContacts.length, - itemBuilder: (context, index) { - final contact = filteredContacts[index]; - final isSelected = selectedKeys.contains( - contact.publicKeyHex, - ); - return CheckboxListTile( - value: isSelected, - title: Text(contact.name), - subtitle: Text( - contact.typeLabel(context.l10n), - ), - onChanged: (value) { - setDialogState(() { - if (value == true) { - selectedKeys.add( - contact.publicKeyHex, - ); - } else { - selectedKeys.remove( - contact.publicKeyHex, - ); - } - }); - }, - ); - }, - ), - ), - ], - ), - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () async { - final name = nameController.text.trim(); - if (name.isEmpty) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_groupNameRequired), - ); - return; - } - if (name.toLowerCase() == - contactsAllGroupsValue.toLowerCase()) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_groupNameReserved), - ); - return; - } - final exists = _groups.any((g) { - if (isEditing && g.name == group.name) return false; - return g.name.toLowerCase() == name.toLowerCase(); - }); - if (exists) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.contacts_groupAlreadyExists(name), - ), - ); - return; - } - setState(() { - final viewState = context.read(); - if (isEditing) { - final index = _groups.indexWhere( - (g) => g.name == group.name, - ); - if (index != -1) { - final wasSelected = - viewState.contactsSelectedGroupName == group.name; - _groups[index] = ContactGroup( - name: name, - memberKeys: selectedKeys.toList(), - ); - if (wasSelected) { - viewState.setContactsSelectedGroupName(name); - } - } - } else { - _groups.add( - ContactGroup( - name: name, - memberKeys: selectedKeys.toList(), - ), - ); - viewState.setContactsSelectedGroupName(name); - } - _ensureValidSelectedGroup(); - }); - await _saveGroups(); - if (dialogContext.mounted) { - Navigator.pop(dialogContext); - } - }, - child: Text( - isEditing - ? context.l10n.common_save - : context.l10n.common_create, - ), - ), - ], - ); - }, - ), + builder: (dialogContext) => ContactGroupEditorDialog( + contacts: contacts, + group: group, + validateName: (name) { + final l10n = dialogContext.l10n; + if (name.isEmpty) return l10n.contacts_groupNameRequired; + if (name.toLowerCase() == contactsAllGroupsValue.toLowerCase()) { + return l10n.contacts_groupNameReserved; + } + final exists = _groups.any((g) { + if (isEditing && g.name == group.name) return false; + return g.name.toLowerCase() == name.toLowerCase(); + }); + return exists ? l10n.contacts_groupAlreadyExists(name) : null; + }, + onSave: (updated) async { + setState(() { + final viewState = context.read(); + if (isEditing) { + final index = _groups.indexWhere((g) => g.name == group.name); + if (index != -1) { + final wasSelected = + viewState.contactsSelectedGroupName == group.name; + _groups[index] = updated; + if (wasSelected) { + viewState.setContactsSelectedGroupName(updated.name); + } + } + } else { + _groups.add(updated); + viewState.setContactsSelectedGroupName(updated.name); + } + _ensureValidSelectedGroup(); + }); + await _saveGroups(); + }, ), ); } @@ -2088,34 +1951,6 @@ class _KeyPrefixBadge extends StatelessWidget { } } -/// Disposes [controller] when the dialog content unmounts, i.e. after the -/// route's exit animation, so the TextField never sees a disposed controller. -class _DisposeControllerOnUnmount extends StatefulWidget { - final TextEditingController controller; - final Widget child; - - const _DisposeControllerOnUnmount({ - required this.controller, - required this.child, - }); - - @override - State<_DisposeControllerOnUnmount> createState() => - _DisposeControllerOnUnmountState(); -} - -class _DisposeControllerOnUnmountState - extends State<_DisposeControllerOnUnmount> { - @override - void dispose() { - widget.controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => widget.child; -} - // Wrap each contact tile with staggered entrance. class _ContactTileEntrance extends StatelessWidget { final int index; diff --git a/lib/widgets/contact_group_editor_dialog.dart b/lib/widgets/contact_group_editor_dialog.dart new file mode 100644 index 00000000..0fdfc61e --- /dev/null +++ b/lib/widgets/contact_group_editor_dialog.dart @@ -0,0 +1,220 @@ +import 'package:flutter/material.dart'; + +import '../helpers/snack_bar_builder.dart'; +import '../l10n/contact_localization.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import '../models/contact_group.dart'; +import '../theme/mesh_theme.dart'; +import '../utils/contact_search.dart'; + +/// Create/edit dialog for a phone-side contact group. Current members are +/// listed first with a remove button each; the searchable "Add contacts" +/// list below shows only contacts that are not members yet. +/// +/// Membership changes stay in the dialog until Save, which calls [onSave]. +/// Nothing here touches the contacts stored on the radio. +class ContactGroupEditorDialog extends StatefulWidget { + const ContactGroupEditorDialog({ + super.key, + required this.contacts, + required this.validateName, + required this.onSave, + this.group, + }); + + final List contacts; + final ContactGroup? group; + + /// Returns an error message for an invalid trimmed name, or null. + final String? Function(String name) validateName; + final Future Function(ContactGroup group) onSave; + + @override + State createState() => + _ContactGroupEditorDialogState(); +} + +class _ContactGroupEditorDialogState extends State { + late final TextEditingController _nameController; + // Insertion-ordered; keeps keys of contacts no longer on the radio. + late final Set _memberKeys; + late final List _sortedContacts; + String _query = ''; + + @override + void initState() { + super.initState(); + _nameController = TextEditingController(text: widget.group?.name ?? ''); + _memberKeys = {...?widget.group?.memberKeys}; + _sortedContacts = List.from(widget.contacts) + ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + } + + @override + void dispose() { + _nameController.dispose(); + super.dispose(); + } + + Future _save() async { + final name = _nameController.text.trim(); + final error = widget.validateName(name); + if (error != null) { + showDismissibleSnackBar(context, content: Text(error)); + return; + } + await widget.onSave( + ContactGroup(name: name, memberKeys: _memberKeys.toList()), + ); + if (mounted) Navigator.pop(context); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final members = _sortedContacts + .where((c) => _memberKeys.contains(c.publicKeyHex)) + .toList(); + final candidates = _sortedContacts + .where( + (c) => + !_memberKeys.contains(c.publicKeyHex) && + matchesContactQuery(c, _query), + ) + .toList(); + + Widget sectionLabel(String text) => Semantics( + header: true, + child: Padding( + padding: const EdgeInsets.fromLTRB(4, 16, 4, 4), + child: Text( + text.toUpperCase(), + style: MeshTheme.accentLabel( + color: scheme.onSurfaceVariant, + fontSize: 13, + ), + ), + ), + ); + + Widget contactTile(Contact contact, {required bool isMember}) { + return ListTile( + key: ValueKey( + 'group-${isMember ? 'member' : 'candidate'}-' + '${contact.publicKeyHex}', + ), + contentPadding: const EdgeInsetsDirectional.only(start: 4), + title: Text( + contact.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 16), + ), + subtitle: Text(contact.typeLabel(l10n)), + onTap: isMember + ? null + : () => setState(() => _memberKeys.add(contact.publicKeyHex)), + trailing: isMember + ? IconButton( + tooltip: l10n.contacts_groupRemoveMember(contact.name), + icon: Icon(Icons.remove_circle_outline, color: scheme.error), + onPressed: () => + setState(() => _memberKeys.remove(contact.publicKeyHex)), + ) + : IconButton( + tooltip: l10n.contacts_groupAddMember(contact.name), + icon: Icon(Icons.add_circle_outline, color: scheme.primary), + onPressed: () => + setState(() => _memberKeys.add(contact.publicKeyHex)), + ), + ); + } + + Widget emptyText(String text) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 12), + child: Text( + text, + style: TextStyle(fontSize: 16, color: scheme.onSurfaceVariant), + ), + ); + + return AlertDialog( + insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24), + contentPadding: const EdgeInsets.fromLTRB(16, 16, 16, 0), + title: Text( + widget.group != null ? l10n.contacts_editGroup : l10n.contacts_newGroup, + ), + content: SizedBox( + width: double.maxFinite, + height: MediaQuery.sizeOf(context).height * 0.7, + child: CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.contacts_groupName, + border: const OutlineInputBorder(), + ), + ), + ), + SliverToBoxAdapter( + child: sectionLabel( + l10n.contacts_groupCurrentMembers(members.length), + ), + ), + if (members.isEmpty) + SliverToBoxAdapter(child: emptyText(l10n.contacts_noMembers)) + else + SliverList.builder( + itemCount: members.length, + itemBuilder: (context, index) => + contactTile(members[index], isMember: true), + ), + SliverToBoxAdapter( + child: sectionLabel(l10n.contacts_groupAddContacts), + ), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.only(top: 4, bottom: 4), + child: TextField( + decoration: InputDecoration( + hintText: l10n.contacts_filterContacts, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: true, + ), + onChanged: (value) => setState(() => _query = value), + ), + ), + ), + if (candidates.isEmpty) + SliverToBoxAdapter( + child: emptyText(l10n.contacts_noContactsMatchFilter), + ) + else + SliverList.builder( + itemCount: candidates.length, + itemBuilder: (context, index) => + contactTile(candidates[index], isMember: false), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + TextButton( + onPressed: _save, + child: Text( + widget.group != null ? l10n.common_save : l10n.common_create, + ), + ), + ], + ); + } +} diff --git a/test/widgets/contact_group_editor_dialog_test.dart b/test/widgets/contact_group_editor_dialog_test.dart new file mode 100644 index 00000000..aa34a010 --- /dev/null +++ b/test/widgets/contact_group_editor_dialog_test.dart @@ -0,0 +1,228 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/contact_group.dart'; +import 'package:meshcore_open/storage/contact_group_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/widgets/contact_group_editor_dialog.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Contact _contact(int seed, String name) => Contact( + publicKey: Uint8List.fromList(List.filled(32, seed)), + name: name, + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), +); + +final _alice = _contact(1, 'Alice'); +final _bob = _contact(2, 'Bob'); +final _carol = _contact(3, 'Carol'); +final _dave = _contact(4, 'Dave'); + +Finder _member(Contact c) => + find.byKey(ValueKey('group-member-${c.publicKeyHex}')); +Finder _candidate(Contact c) => + find.byKey(ValueKey('group-candidate-${c.publicKeyHex}')); + +/// The whole IconButton, including its 48dp tap-target padding. +Finder _button(String tooltip) => find.ancestor( + of: find.byTooltip(tooltip), + matching: find.byType(IconButton), +); + +/// Opens the editor and returns the groups passed to onSave. +Future> _open( + WidgetTester tester, { + required List contacts, + ContactGroup? group, + double textScale = 1.0, +}) async { + final saved = []; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => ContactGroupEditorDialog( + contacts: contacts, + group: group, + validateName: (name) => name.isEmpty ? 'required' : null, + onSave: (g) async => saved.add(g), + ), + ), + child: const Text('open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + return saved; +} + +void main() { + final contacts = [_dave, _carol, _bob, _alice]; + final group = ContactGroup( + name: 'Team', + memberKeys: [_carol.publicKeyHex, _alice.publicKeyHex], + ); + + testWidgets('current members are listed first, before the add list', ( + tester, + ) async { + await _open(tester, contacts: contacts, group: group); + + expect(find.text('CURRENT MEMBERS (2)'), findsOneWidget); + final membersHeaderY = tester + .getTopLeft(find.text('CURRENT MEMBERS (2)')) + .dy; + final addHeaderY = tester.getTopLeft(find.text('ADD CONTACTS')).dy; + final aliceY = tester.getTopLeft(_member(_alice)).dy; + final carolY = tester.getTopLeft(_member(_carol)).dy; + expect(membersHeaderY, lessThan(aliceY)); + expect(aliceY, lessThan(carolY)); + expect(carolY, lessThan(addHeaderY)); + expect(tester.getTopLeft(_candidate(_bob)).dy, greaterThan(addHeaderY)); + }); + + testWidgets('members never appear again in the add list', (tester) async { + await _open(tester, contacts: contacts, group: group); + + expect(_candidate(_alice), findsNothing); + expect(_candidate(_carol), findsNothing); + expect(_candidate(_bob), findsOneWidget); + expect(_candidate(_dave), findsOneWidget); + expect(find.text('Alice'), findsOneWidget); + }); + + testWidgets('remove button drops the member and saves the rest', ( + tester, + ) async { + final saved = await _open(tester, contacts: contacts, group: group); + + final remove = _button('Remove Alice from group'); + expect(remove, findsOneWidget); + expect(tester.getSize(remove).width, greaterThanOrEqualTo(48)); + expect(tester.getSize(remove).height, greaterThanOrEqualTo(48)); + + await tester.tap(remove); + await tester.pumpAndSettle(); + + expect(find.text('CURRENT MEMBERS (1)'), findsOneWidget); + expect(_member(_alice), findsNothing); + // Still a contact: it moves back to the add list. + expect(_candidate(_alice), findsOneWidget); + + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(saved.single.name, 'Team'); + expect(saved.single.memberKeys, [_carol.publicKeyHex]); + expect(contacts, hasLength(4)); + expect(contacts, contains(_alice)); + }); + + testWidgets('search filters the add list and tapping adds a contact', ( + tester, + ) async { + final saved = await _open(tester, contacts: contacts, group: group); + + await tester.enterText(find.byType(TextField).last, 'da'); + await tester.pumpAndSettle(); + expect(_candidate(_dave), findsOneWidget); + expect(_candidate(_bob), findsNothing); + // Members stay visible while searching. + expect(_member(_alice), findsOneWidget); + + await tester.tap(find.text('Dave')); + await tester.pumpAndSettle(); + + expect(_member(_dave), findsOneWidget); + expect(_candidate(_dave), findsNothing); + expect(find.text('CURRENT MEMBERS (3)'), findsOneWidget); + + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(saved.single.memberKeys, [ + _carol.publicKeyHex, + _alice.publicKeyHex, + _dave.publicKeyHex, + ]); + expect(saved.single.memberKeys.toSet(), hasLength(3)); + }); + + testWidgets('keys of contacts not on the radio are kept on save', ( + tester, + ) async { + final stale = 'ff' * 32; + final saved = await _open( + tester, + contacts: contacts, + group: ContactGroup(name: 'Team', memberKeys: [stale]), + ); + + await tester.tap(find.byTooltip('Add Bob to group')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(saved.single.memberKeys, [stale, _bob.publicKeyHex]); + }); + + testWidgets('edited membership persists through the group store', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + final store = ContactGroupStore()..setPublicKeyHex = 'abcdef0123456789'; + + final saved = await _open(tester, contacts: contacts, group: group); + await tester.tap(find.byTooltip('Remove Carol from group')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + await tester.runAsync(() => store.saveGroups(saved)); + final loaded = await tester.runAsync(store.loadGroups); + expect(loaded!.single.name, 'Team'); + expect(loaded.single.memberKeys, [_alice.publicKeyHex]); + }); + + for (final scale in [1.3, 2.0]) { + testWidgets('fits a 320dp screen at ${scale}x text', (tester) async { + tester.view.physicalSize = const Size(320, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await _open(tester, contacts: contacts, group: group, textScale: scale); + + expect(tester.takeException(), isNull); + final remove = _button('Remove Alice from group'); + expect(remove, findsOneWidget); + expect(tester.getSize(remove).width, greaterThanOrEqualTo(48)); + expect(tester.getSize(remove).height, greaterThanOrEqualTo(48)); + await tester.tap(remove); + await tester.pumpAndSettle(); + expect(_member(_alice), findsNothing); + }); + } +} From bc0062363dbc31899bba898441b92328ff7c14bd Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 12/50] Restyle the chat composer Rounded borderless bubble that grows to five lines, one round button that switches between attach and send, reply and GIF previews inside the bubble, a byte counter shown only near the limit, and a transparent panel over chat wallpapers. Sending, limits and compression are unchanged. --- documentation/chat-and-messaging.md | 14 +- documentation/design.md | 11 +- lib/screens/channel_chat_screen.dart | 93 ++-- lib/screens/chat_screen.dart | 4 +- lib/widgets/byte_count_input.dart | 79 ++- lib/widgets/chat_background.dart | 61 ++- lib/widgets/chat_composer.dart | 520 +++++++++++++------ test/screens/chat_composer_screens_test.dart | 206 ++++++++ test/widgets/chat_composer_test.dart | 504 ++++++++++++++++++ 9 files changed, 1241 insertions(+), 251 deletions(-) create mode 100644 test/screens/chat_composer_screens_test.dart create mode 100644 test/widgets/chat_composer_test.dart diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 53a47331..68aec5f2 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -40,13 +40,17 @@ From the Contacts screen, tap any Chat-type contact to open the ChatScreen. ### Input Bar -- **Send action button** (left, ⊕ icon): Opens a menu with **Send GIF** (GIF picker bottom sheet) and **Share my location** +The composer is a rounded bubble at the bottom of the chat with one round button beside it. With a chat background set, the bubble floats over the background. + +- **Round button** (right): shows **+** while the field is empty and **Send** once you type. **+** opens the send action menu: **Send GIF** (GIF picker bottom sheet), **Share my location**, **Share contact**, and, when set up, image uploads - **Share my location**: Sends your radio's current position (from the radio, not the phone's GPS) as a location pin. You're asked for a label (default: your node name) before sending; the keyboard's Send key confirms. If the radio reports no usable position (none set, or 0,0), the item is hidden and a snackbar says "Your radio has no location set". Location shares follow the same send cooldown as typed messages and are never sent as a reply. In channel chat the menu also holds **Send low-res image over radio** when image messages are set up -- **Translation button** (optional, between GIF and text field): Shown only when translation is enabled in App Settings. Tap to configure outgoing-message translation language and on/off toggle. -- **Text field** (center): Auto-capitalization, enforces UTF-8 byte limit in real-time -- **Send button** (right): Submits the message +- **Text field**: Auto-capitalization, enforces the UTF-8 byte limit in real time. It grows to five lines (fewer with very large text while the keyboard is open), then scrolls +- **Byte counter**: appears in the bottom-right of the bubble once a message passes 70 % of the limit, and turns red near the limit +- **Translation button** (inside the bubble, right): Shown only when translation is enabled in App Settings. Tap to configure outgoing-message translation language and on/off toggle. +- **Reply preview**: In channel chat, replying shows the quoted message at the top of the bubble with a **✕** to cancel and, when the original had a region, the region chip - On desktop: Enter/Numpad Enter also submits -- When a GIF is selected, the text field shows an inline GIF preview with a dismiss button +- When a GIF is selected, the bubble shows a GIF preview with a remove button; Enter sends it +- With no radio connected, the bubble says so and a **Connect** button takes the place of the round button ## Message Types diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..ed6abd85 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -147,6 +147,15 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act **IconButton.** Always set `tooltip:` with a localized string. It is the accessible name. +**Chat composer.** Direct and channel chats share `ChatComposer` (`widgets/chat_composer.dart`); change it there, not per screen. + +- Panel: no divider; `scheme.surface` without a chat background, transparent over one (the screens pass the composer as `ChatBackdrop.footer`, and `ChatBackdrop.hasBackgroundOf` tells it a background is drawn). Margins 12 on the sides, 8 above and below. +- Bubble: radius `kComposerBubbleRadius` (20), no outline, `surfaceContainerHigh` fill, or the incoming-bubble colour (`MessageBubbleColors`, `surfaceContainerLow`) over a background. One line is 48 tall; the field grows to `kComposerMaxLines` (5), fewer when large text and the keyboard leave little room, then scrolls. Buttons stay bottom-aligned. +- Inside the bubble: a reply quote at the top (`ChatComposerQuote`: 4px leading bar in `primary`, title, one-line content, ✕), the field or the GIF preview, the translate button on the right, and the byte counter bottom-right only past 70 % of the limit (`ByteCountedTextField(counterOnlyNearLimit: true)`). +- One round button beside the bubble, 44 drawn in a 48 touch target: `+` (the action menu) while the field is empty, Send in `primary` once there is text. The swap fades and scales for 150 ms, instantly when `MediaQuery.disableAnimations` is set. +- Offline, `OfflineComposerBar` uses the same panel, bubble and height, with Connect in place of the round button (below the bubble on narrow or large-text layouts). +- Full-width strips that are not part of the draft (image send progress) go in `header`, above the bubble. + ## 6. Sheets, dialogs and pages What the code does: @@ -183,7 +192,7 @@ Rules for new UI: | Background sync | `SyncProgressAppBarBottom`. | | Empty | `EmptyState` with an icon, a short title, and an action when there is an obvious next step. Use a separate "no results" state (`Icons.search_off`) when a search or filter hides everything. | | Error | A snackbar for a failed action. `ErrorRetryCard` for a failed load the user can retry. Never show raw exception text alone. | -| Companion radio disconnected | Main and chat screens stay open, read-only ([offline mode](offline-mode.md)). Decide with `isRadioReadOnly(connector)` / `context.radioReadOnly` (`lib/utils/radio_guard.dart`): disable menu items (`PopupMenuItem(enabled: false)`, drop destructive colors) and buttons, hide FABs, and call `ensureRadioConnected(context)` as the safety net in handlers. The chat composer shows `OfflineComposerBar`. Repeater screens stay open with `RadioDisconnectedBanner` at the top and disable radio-dependent actions. Settings rows that need the radio pass `onTap: null` and show `settings_requiresConnection` as the subtitle (`settings_screen.dart`). | +| Companion radio disconnected | Main and chat screens stay open, read-only ([offline mode](offline-mode.md)). Decide with `isRadioReadOnly(connector)` / `context.radioReadOnly` (`lib/utils/radio_guard.dart`): disable menu items (`PopupMenuItem(enabled: false)`, drop destructive colors) and buttons, hide FABs, and call `ensureRadioConnected(context)` as the safety net in handlers. The chat composer shows `OfflineComposerBar` in the same bubble and margins. Repeater screens stay open with `RadioDisconnectedBanner` at the top and disable radio-dependent actions. Settings rows that need the radio pass `onTap: null` and show `settings_requiresConnection` as the subtitle (`settings_screen.dart`). | | Feature unsupported by firmware | Disabled row with a subtitle that says why (`settings_requiresFirmware('v1.10')`). | | Remote value not fetched yet | See below. | diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 67a397ab..99a214c7 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -843,12 +843,16 @@ class _ChannelChatScreenState extends State { ? _buildSearchResults(_loadSearchEntries) : SafeArea( top: false, + // The composer panel pads the bottom inset itself, so the + // background runs behind it to the screen edge. + bottom: false, child: Column( children: [ Expanded( child: ChatBackdrop( - key: _messageAreaKey, + contentKey: _messageAreaKey, chatKey: ChatBackgroundService.channelKey(widget.channel), + footer: _buildInputBar(), child: Consumer( builder: (context, connector, child) { final messages = connector.getChannelMessages( @@ -1064,7 +1068,6 @@ class _ChannelChatScreenState extends State { ), ), ), - _buildInputBar(), ], ), ), @@ -2633,47 +2636,23 @@ class _ChannelChatScreenState extends State { ); } - Widget _buildReplyBanner(double textScale) { + Widget _buildComposerReplyQuote(double textScale) { final message = _replyingToMessage!; final scheme = Theme.of(context).colorScheme; final replyRegion = message.region; - return Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: scheme.surfaceContainerHigh, - border: Border( - bottom: BorderSide(color: scheme.outlineVariant, width: 1), - ), + return ChatComposerQuote( + title: context.l10n.chat_replyingTo(message.senderName), + content: _buildReplyContent( + message.text, + textScale, + color: scheme.onSurfaceVariant, + maxLines: 1, + gifSize: 48, ), - child: Row( - children: [ - Icon(Icons.reply, size: 18, color: scheme.primary), - const SizedBox(width: 8), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.chat_replyingTo(message.senderName), - style: MeshTheme.mono( - fontSize: 12 * textScale, - fontWeight: FontWeight.w700, - color: scheme.primary, - ), - ), - _buildReplyContent( - message.text, - textScale, - color: scheme.onSurfaceVariant, - maxLines: 1, - gifSize: 48, - ), - ], - ), - ), - if (replyRegion?.isNotEmpty ?? false) - InkWell( + onDismiss: _cancelReply, + dismissTooltip: context.l10n.chat_cancelReply, + trailing: (replyRegion?.isNotEmpty ?? false) + ? InkWell( borderRadius: BorderRadius.circular(MeshRadii.xs), onTap: () => setState(() => _useReplyRegion = !_useReplyRegion), child: Container( @@ -2704,17 +2683,8 @@ class _ChannelChatScreenState extends State { ), ), ), - ), - const SizedBox(width: 4), - IconButton( - icon: const Icon(Icons.close, size: 18), - tooltip: context.l10n.chat_cancelReply, - onPressed: _cancelReply, - color: scheme.onSurfaceVariant, - constraints: const BoxConstraints(minWidth: 44, minHeight: 44), - ), - ], - ), + ) + : null, ); } @@ -2790,18 +2760,17 @@ class _ChannelChatScreenState extends State { : null, onSend: _sendMessage, sendTooltip: context.l10n.chat_sendMessage, - header: [ - if (replyTo != null) - Builder( - builder: (context) { - final textScale = context.select( - (service) => service.scale, - ); - return _buildReplyBanner(textScale); - }, - ), - if (_imageSendTotal > 0) _buildImageSendProgress(scheme), - ], + header: [if (_imageSendTotal > 0) _buildImageSendProgress(scheme)], + replyPreview: replyTo == null + ? null + : Builder( + builder: (context) { + final textScale = context.select( + (service) => service.scale, + ); + return _buildComposerReplyQuote(textScale); + }, + ), actionsBuilder: () { final connector = context.read(); return [ diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index ad509b82..ece6eb3f 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -624,10 +624,11 @@ class _ChatScreenState extends State { children: [ Expanded( child: ChatBackdrop( - key: _messageAreaKey, + contentKey: _messageAreaKey, chatKey: ChatBackgroundService.contactKey( widget.contact, ), + footer: _buildInputBar(connector), child: Stack( children: [ messages.isEmpty @@ -640,7 +641,6 @@ class _ChatScreenState extends State { ), ), ), - _buildInputBar(connector), ], ); }, diff --git a/lib/widgets/byte_count_input.dart b/lib/widgets/byte_count_input.dart index 5872b192..3fe70b5b 100644 --- a/lib/widgets/byte_count_input.dart +++ b/lib/widgets/byte_count_input.dart @@ -62,6 +62,14 @@ class ByteCountedTextField extends StatelessWidget { final int? softLimitBytes; final String? softLimitNote; + /// Lines the field grows to before it scrolls internally. Null (the + /// default) grows without limit. + final int? maxLines; + + /// Show the counter row only once usage passes [warningThreshold], and give + /// it no space until then. By default the row keeps its height while hidden. + final bool counterOnlyNearLimit; + const ByteCountedTextField({ super.key, required this.maxBytes, @@ -80,6 +88,8 @@ class ByteCountedTextField extends StatelessWidget { this.encoder, this.softLimitBytes, this.softLimitNote, + this.maxLines, + this.counterOnlyNearLimit = false, }); @override @@ -92,7 +102,9 @@ class ByteCountedTextField extends StatelessWidget { : value.text; final usedBytes = utf8.encode(effectiveText).length; final ratio = maxBytes > 0 ? usedBytes / maxBytes : 0.0; - final showCounter = !(hideCounterWhenEmpty && value.text.isEmpty); + final showCounter = counterOnlyNearLimit + ? ratio > warningThreshold + : !(hideCounterWhenEmpty && value.text.isEmpty); final showSoftLimitNote = softLimitNote != null && softLimitBytes != null && @@ -104,12 +116,27 @@ class ByteCountedTextField extends StatelessWidget { ? Theme.of(context).colorScheme.tertiary : Theme.of(context).colorScheme.onSurfaceVariant; + final softNote = showSoftLimitNote + ? Text( + softLimitNote!, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.tertiary, + ), + ) + : null; + final counter = Text( + '$usedBytes / $maxBytes', + style: TextStyle(fontSize: 12, color: counterColor), + ); + return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextField( - maxLines: null, + minLines: maxLines == null ? null : 1, + maxLines: maxLines, controller: controller, focusNode: focusNode, autofocus: autofocus, @@ -134,32 +161,32 @@ class ByteCountedTextField extends StatelessWidget { textInputAction: textInputAction, onSubmitted: onSubmitted, ), - Opacity( - opacity: showCounter ? 1 : 0, - child: Padding( - padding: const EdgeInsets.only(top: 4, right: 4), - child: Row( - children: [ - Expanded( - child: showSoftLimitNote - ? Text( - softLimitNote!, - style: TextStyle( - fontSize: 12, - color: Theme.of(context).colorScheme.tertiary, - ), - ) - : const SizedBox.shrink(), - ), - const SizedBox(width: 8), - Text( - '$usedBytes / $maxBytes', - style: TextStyle(fontSize: 12, color: counterColor), - ), - ], + if (counterOnlyNearLimit && showCounter) + // Right-aligned, and wraps rather than overflowing at large + // text sizes in a narrow field. + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 12, 8), + child: Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + children: [?softNote, counter], + ), + ) + else if (!counterOnlyNearLimit) + Opacity( + opacity: showCounter ? 1 : 0, + child: Padding( + padding: const EdgeInsets.only(top: 4, right: 4), + child: Row( + children: [ + Expanded(child: softNote ?? const SizedBox.shrink()), + const SizedBox(width: 8), + counter, + ], + ), ), ), - ), ], ); }, diff --git a/lib/widgets/chat_background.dart b/lib/widgets/chat_background.dart index fe56a12e..219ec7bd 100644 --- a/lib/widgets/chat_background.dart +++ b/lib/widgets/chat_background.dart @@ -42,26 +42,79 @@ ChatBackgroundService? _maybeService( } /// Draws [chatKey]'s background (its own, or the theme's) behind [child]. +/// +/// A [footer] (the chat composer) sits below [child] over the same +/// background and can ask [ChatBackdrop.hasBackgroundOf] whether one is +/// drawn. [contentKey] marks the message area above the footer. class ChatBackdrop extends StatelessWidget { final String chatKey; final Widget child; + final Widget? footer; + final Key? contentKey; - const ChatBackdrop({super.key, required this.chatKey, required this.child}); + const ChatBackdrop({ + super.key, + required this.chatKey, + required this.child, + this.footer, + this.contentKey, + }); + + /// Whether the nearest [ChatBackdrop] draws a background behind its footer. + static bool hasBackgroundOf(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType<_ChatBackdropScope>() + ?.hasBackground ?? + false; @override Widget build(BuildContext context) { final background = _maybeService(context)?.resolve(chatKey); - if (background == null) return child; + final footer = this.footer; + if (footer == null) { + if (background == null) return child; + return Stack( + fit: StackFit.expand, + children: [ + Positioned.fill(child: ChatBackgroundLayer(background: background)), + child, + ], + ); + } return Stack( fit: StackFit.expand, children: [ - Positioned.fill(child: ChatBackgroundLayer(background: background)), - child, + Positioned.fill( + child: background == null + ? const SizedBox.shrink() + : ChatBackgroundLayer(background: background), + ), + Column( + children: [ + Expanded( + child: KeyedSubtree(key: contentKey, child: child), + ), + _ChatBackdropScope( + hasBackground: background != null, + child: footer, + ), + ], + ), ], ); } } +class _ChatBackdropScope extends InheritedWidget { + final bool hasBackground; + + const _ChatBackdropScope({required this.hasBackground, required super.child}); + + @override + bool updateShouldNotify(_ChatBackdropScope oldWidget) => + hasBackground != oldWidget.hasBackground; +} + /// Paints one [ChatBackground], faded toward the theme's surface color. class ChatBackgroundLayer extends StatelessWidget { final ChatBackground background; diff --git a/lib/widgets/chat_composer.dart b/lib/widgets/chat_composer.dart index c988d215..8141e676 100644 --- a/lib/widgets/chat_composer.dart +++ b/lib/widgets/chat_composer.dart @@ -8,10 +8,12 @@ import '../services/app_settings_service.dart'; import '../theme/mesh_theme.dart'; import '../utils/radio_guard.dart'; import 'byte_count_input.dart'; +import 'chat_background.dart'; import 'connect_sheet.dart'; import 'gif_message.dart'; import 'gif_picker.dart'; import 'mesh_ui.dart'; +import 'message_bubble_frame.dart'; import 'message_translation_button.dart'; import '../theme/theme_icons.dart'; @@ -54,10 +56,60 @@ Future showComposerTranslationOptions(BuildContext context) async { ); } -/// The message composer shared by the direct and channel chat screens: -/// "+" action menu, optional translation toggle, byte-counted text field (or -/// GIF preview) and send button. [header] widgets (reply banner, progress) -/// are stacked above the row. +/// Corner radius of the compose bubble and the offline bar. +const double kComposerBubbleRadius = 20; + +/// Lines the compose field grows to before it scrolls. +const int kComposerMaxLines = 5; + +/// Fill of the compose bubble: the incoming-bubble colour over a chat +/// background so it stays readable, otherwise a raised surface. +Color composerBubbleColor(BuildContext context) { + return ChatBackdrop.hasBackgroundOf(context) + ? MessageBubbleColors.of(context, isOutgoing: false).background + : Theme.of(context).colorScheme.surfaceContainerHigh; +} + +/// The bottom panel holding the compose bubble: transparent over a chat +/// background, solid surface otherwise. 12dp side and 8dp vertical margins +/// (8dp on the trailing side, where the round button's touch target adds 2). +class _ComposerPanel extends StatelessWidget { + final List header; + final Widget child; + + const _ComposerPanel({this.header = const [], required this.child}); + + @override + Widget build(BuildContext context) { + final content = SafeArea( + top: false, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ...header, + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 10, 8), + child: child, + ), + ], + ), + ); + if (ChatBackdrop.hasBackgroundOf(context)) return content; + return ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: content, + ); + } +} + +/// The message composer shared by the direct and channel chat screens. +/// +/// A rounded compose bubble (optional [replyPreview], then the byte-counted +/// text field or a GIF preview, with the translation toggle on its right) +/// and one round button beside it: "+" (the [actionsBuilder] menu) while the +/// field is empty, Send once there is text. [header] widgets (e.g. image +/// send progress) are stacked full-width above the bubble. class ChatComposer extends StatelessWidget { final TextEditingController controller; final FocusNode focusNode; @@ -74,6 +126,12 @@ class ChatComposer extends StatelessWidget { final ValueChanged onAction; final List header; + /// Shown inside the top of the bubble, usually a [ChatComposerQuote]. + final Widget? replyPreview; + + /// Marks the compose bubble (and the offline bar's bubble). + static const bubbleKey = ValueKey('chat-composer-bubble'); + const ChatComposer({ super.key, required this.controller, @@ -87,6 +145,7 @@ class ChatComposer extends StatelessWidget { this.softLimitNote, this.encoder, this.header = const [], + this.replyPreview, }); Future _openActionMenu(BuildContext buttonContext) async { @@ -128,7 +187,6 @@ class ChatComposer extends StatelessWidget { @override Widget build(BuildContext context) { - final scheme = Theme.of(context).colorScheme; // Offline the chat is read-only. The draft stays in [controller] (owned // by the screen) and is back when the radio reconnects. if (context.radioReadOnly) return const OfflineComposerBar(); @@ -140,26 +198,40 @@ class ChatComposer extends StatelessWidget { s.settings.translationTargetLanguageCode, ), ); - return Container( + final scheme = Theme.of(context).colorScheme; + final replyPreview = this.replyPreview; + final bubble = DecoratedBox( + key: ChatComposer.bubbleKey, decoration: BoxDecoration( - color: scheme.surface, - border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), + color: composerBubbleColor(context), + borderRadius: BorderRadius.circular(kComposerBubbleRadius), ), - child: SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ...header, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (replyPreview != null) Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, + padding: const EdgeInsets.fromLTRB(6, 6, 6, 0), + child: replyPreview, + ), + ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final gifId = GifHelper.parseGif(value.text); + if (gifId != null) { + return _buildGifPreview(context, gifId, scheme); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.end, children: [ - Builder( - builder: (buttonContext) => IconButton( - icon: const Icon(Icons.add_circle_outline), - tooltip: context.l10n.chat_selectSendAction, - onPressed: () => _openActionMenu(buttonContext), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) => _buildTextField( + context, + scheme, + constraints.maxHeight, + ), ), ), if (translation.$1) @@ -168,50 +240,34 @@ class ChatComposer extends StatelessWidget { languageCode: translation.$3, onPressed: () => showComposerTranslationOptions(context), ), - Expanded( - child: ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - final gifId = GifHelper.parseGif(value.text); - if (gifId != null) { - return _buildGifPreview(context, gifId, scheme); - } - return _buildTextField(context, scheme); - }, - ), - ), - const SizedBox(width: 6), - ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - final hasText = value.text.trim().isNotEmpty; - return IconButton.filled( - icon: const ThemedIcon(ThemeIconSlot.send, size: 20), - tooltip: sendTooltip, - style: IconButton.styleFrom( - backgroundColor: hasText - ? scheme.primary - : scheme.surfaceContainerHighest, - foregroundColor: hasText - ? scheme.onPrimary - : scheme.onSurfaceVariant, - minimumSize: const Size(40, 40), - shape: const CircleBorder(), - ), - onPressed: hasText - ? () { - HapticFeedback.lightImpact(); - onSend(); - } - : null, - ); - }, - ), ], - ), + ); + }, + ), + ], + ), + ); + return _ComposerPanel( + header: header, + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded(child: bubble), + const SizedBox(width: 4), + ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) => _ComposerRoundButton( + hasText: value.text.trim().isNotEmpty, + sendTooltip: sendTooltip, + actionsTooltip: context.l10n.chat_selectSendAction, + onSend: () { + HapticFeedback.lightImpact(); + onSend(); + }, + onOpenActions: _openActionMenu, ), - ], - ), + ), + ], ), ); } @@ -232,39 +288,57 @@ class ChatComposer extends StatelessWidget { } return KeyEventResult.ignored; }, - child: Row( - children: [ - Expanded( - child: ClipRRect( - borderRadius: BorderRadius.circular(12), - child: GifMessage( - url: 'https://media.giphy.com/media/$gifId/giphy.gif', - backgroundColor: scheme.surfaceContainerHighest, - fallbackTextColor: scheme.onSurface.withValues(alpha: 0.6), - maxSize: 160, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 8, 0, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Align( + alignment: AlignmentDirectional.centerStart, + child: ClipRRect( + borderRadius: BorderRadius.circular(MeshRadii.md), + child: GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: scheme.surfaceContainerHighest, + fallbackTextColor: scheme.onSurfaceVariant, + maxSize: 160, + ), + ), ), ), - ), - const SizedBox(width: 8), - IconButton( - icon: const Icon(Icons.close), - tooltip: context.l10n.chat_removeGif, - onPressed: () { - controller.clear(); - focusNode.requestFocus(); - }, - ), - ], + IconButton( + icon: const Icon(Icons.close), + tooltip: context.l10n.chat_removeGif, + onPressed: () { + controller.clear(); + focusNode.requestFocus(); + }, + ), + ], + ), ), ); } - Widget _buildTextField(BuildContext context, ColorScheme scheme) { - OutlineInputBorder border(Color color, [double width = 1]) => - OutlineInputBorder( - borderRadius: BorderRadius.circular(MeshRadii.md), - borderSide: BorderSide(color: color, width: width), - ); + /// [maxHeight] is the room the chat leaves the composer: above the + /// keyboard, since the screen's body resizes for it. + Widget _buildTextField( + BuildContext context, + ColorScheme scheme, + double maxHeight, + ) { + // Five lines, or fewer when large text and a short window leave little + // room, so the field takes no more than about a quarter of the chat. + // Never one line: that stops wrapping and the keyboard's newline key. + final room = maxHeight.isFinite + ? maxHeight + : MediaQuery.sizeOf(context).height; + final lineHeight = MediaQuery.textScalerOf(context).scale(16) * 1.5; + final maxLines = (room / 4 / lineHeight).floor().clamp( + 2, + kComposerMaxLines, + ); return ByteCountedTextField( maxBytes: maxBytes, softLimitBytes: softLimitBytes, @@ -274,85 +348,229 @@ class ChatComposer extends StatelessWidget { hintText: context.l10n.chat_typeMessage, onSubmitted: (_) => onSend(), encoder: encoder, + maxLines: maxLines, + counterOnlyNearLimit: true, decoration: InputDecoration( hintText: context.l10n.chat_typeMessage, - border: border(scheme.outlineVariant), - enabledBorder: border(scheme.outlineVariant), - focusedBorder: border(scheme.primary, 1.5), - filled: true, - fillColor: scheme.surfaceContainerLow, - contentPadding: const EdgeInsets.symmetric( - horizontal: 18, - vertical: 12, - ), + hintStyle: TextStyle(color: scheme.onSurfaceVariant), + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + filled: false, + isDense: true, + // A 24dp line plus 12 above and below: 48dp on one line, level with + // the round button beside the bubble. + contentPadding: const EdgeInsetsDirectional.fromSTEB(16, 12, 8, 12), ), ); } } -/// Stands in for the composer while no radio is connected. -class OfflineComposerBar extends StatelessWidget { - const OfflineComposerBar({super.key}); +/// The round button beside the compose bubble: "+" while the field is +/// empty, Send once there is text. Drawn at 44dp in a 48dp touch target. +class _ComposerRoundButton extends StatelessWidget { + final bool hasText; + final String sendTooltip; + final String actionsTooltip; + final VoidCallback onSend; + final ValueChanged onOpenActions; + + const _ComposerRoundButton({ + required this.hasText, + required this.sendTooltip, + required this.actionsTooltip, + required this.onSend, + required this.onOpenActions, + }); + + static const _visualSize = Size(44, 44); @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; - return Container( - decoration: BoxDecoration( - color: scheme.surfaceContainerLow, - border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), + ButtonStyle style(Color background, Color foreground) => + IconButton.styleFrom( + backgroundColor: background, + foregroundColor: foreground, + fixedSize: _visualSize, + minimumSize: _visualSize, + padding: EdgeInsets.zero, + tapTargetSize: MaterialTapTargetSize.padded, + shape: const CircleBorder(), + ); + final Widget button = hasText + ? IconButton.filled( + key: const ValueKey('composer-send'), + icon: const ThemedIcon(ThemeIconSlot.send, size: 22), + tooltip: sendTooltip, + style: style(scheme.primary, scheme.onPrimary), + onPressed: onSend, + ) + : Builder( + key: const ValueKey('composer-actions'), + builder: (buttonContext) => IconButton.filled( + icon: const Icon(Icons.add, size: 28), + tooltip: actionsTooltip, + style: style(composerBubbleColor(context), scheme.onSurface), + onPressed: () => onOpenActions(buttonContext), + ), + ); + return SizedBox.square( + dimension: kMinInteractiveDimension, + child: AnimatedSwitcher( + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 150), + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.6, end: 1).animate(animation), + child: child, + ), + ), + child: button, ), - child: SafeArea( + ); + } +} + +/// A quoted message inside the top of the compose bubble ("Replying to +/// Bob"): a coloured bar on the leading edge, [title], [content], optional +/// [trailing] controls and a dismiss button. +class ChatComposerQuote extends StatelessWidget { + final String title; + final Widget content; + final Widget? trailing; + final VoidCallback onDismiss; + final String dismissTooltip; + + const ChatComposerQuote({ + super.key, + required this.title, + required this.content, + required this.onDismiss, + required this.dismissTooltip, + this.trailing, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final background = scheme.surfaceContainerHighest; + final accent = readableAccent(scheme.primary, background); + final trailing = this.trailing; + return ClipRRect( + borderRadius: BorderRadius.circular(MeshRadii.md), + child: DecoratedBox( + decoration: BoxDecoration( + color: background, + border: BorderDirectional(start: BorderSide(color: accent, width: 4)), + ), child: Padding( - padding: const EdgeInsets.fromLTRB(16, 10, 12, 10), - child: LayoutBuilder( - builder: (context, constraints) { - final message = Row( - children: [ - Icon( - Icons.cloud_off, - color: scheme.onSurfaceVariant, - size: 24, - ), - const SizedBox(width: 12), - Expanded( - child: Text( - context.l10n.chat_composerOffline, - style: Theme.of( - context, - ).textTheme.bodyLarge?.copyWith(color: scheme.onSurface), - ), - ), - ], - ); - // Side by side when there is room; otherwise the button goes - // under the message so large text never squeezes it. - final roomy = - constraints.maxWidth / - MediaQuery.textScalerOf(context).scale(1) >= - 420; - if (roomy) { - return Row( + padding: const EdgeInsetsDirectional.fromSTEB(10, 6, 0, 6), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - Expanded(child: message), - const SizedBox(width: 8), - const ConnectButton(), + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w700, + color: accent, + ), + ), + content, ], - ); - } - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - message, - const SizedBox(height: 8), - const ConnectButton(), - ], - ); - }, + ), + ), + ?trailing, + IconButton( + icon: const Icon(Icons.close), + tooltip: dismissTooltip, + color: scheme.onSurfaceVariant, + onPressed: onDismiss, + ), + ], ), ), ), ); } } + +/// Stands in for the composer while no radio is connected, in the same +/// bubble and margins so the chat doesn't jump on connect or disconnect. +class OfflineComposerBar extends StatelessWidget { + const OfflineComposerBar({super.key}); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final message = ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: DecoratedBox( + key: ChatComposer.bubbleKey, + decoration: BoxDecoration( + color: composerBubbleColor(context), + borderRadius: BorderRadius.circular(kComposerBubbleRadius), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Icon(Icons.cloud_off, color: scheme.onSurfaceVariant, size: 24), + const SizedBox(width: 12), + Expanded( + child: Text( + context.l10n.chat_composerOffline, + style: Theme.of( + context, + ).textTheme.bodyLarge?.copyWith(color: scheme.onSurface), + ), + ), + ], + ), + ), + ), + ); + return _ComposerPanel( + child: LayoutBuilder( + builder: (context, constraints) { + // Side by side when there is room; otherwise the button goes + // under the message so large text never squeezes it. + final roomy = + constraints.maxWidth / + MediaQuery.textScalerOf(context).scale(1) >= + 420; + if (roomy) { + return Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded(child: message), + const SizedBox(width: 4), + const ConnectButton(), + ], + ); + } + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + message, + const SizedBox(height: 8), + const Align( + alignment: AlignmentDirectional.centerEnd, + child: ConnectButton(), + ), + ], + ); + }, + ), + ); + } +} diff --git a/test/screens/chat_composer_screens_test.dart b/test/screens/chat_composer_screens_test.dart new file mode 100644 index 00000000..2dea12ce --- /dev/null +++ b/test/screens/chat_composer_screens_test.dart @@ -0,0 +1,206 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/chat_background.dart'; +import 'package:meshcore_open/widgets/chat_composer.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +/// Both chat screens show the same composer, as the footer of the chat +/// background, and the channel reply preview sits inside its bubble. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('chat_composer_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + Finder composerIn(Type screen) => find.descendant( + of: find.descendant( + of: find.byType(screen), + matching: find.byType(ChatBackdrop), + ), + matching: find.byType(ChatComposer), + ); + + testWidgets('DM chat shows the redesigned composer', (tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat); + await _pump(tester, providers, ChatScreen(contact: contact)); + + expect(composerIn(ChatScreen), findsOneWidget); + expect(find.byTooltip(_l10n.chat_selectSendAction), findsOneWidget); + expect(find.byIcon(Icons.add_circle_outline), findsNothing); + + await tester.enterText(find.byType(TextField), 'hello'); + await _settle(tester); + expect(find.byTooltip(_l10n.chat_selectSendAction), findsNothing); + expect(find.byTooltip(_l10n.chat_sendMessageTo(contact.name)), findsOne); + await _tearDown(tester); + }); + + testWidgets('channel chat shows the same composer with the reply preview ' + 'inside the bubble', (tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + final channel = connector.channels[0]; + await _pump(tester, providers, ChannelChatScreen(channel: channel)); + + expect(composerIn(ChannelChatScreen), findsOneWidget); + expect(find.byTooltip(_l10n.chat_selectSendAction), findsOneWidget); + expect(find.byType(ChatComposerQuote), findsNothing); + + final incoming = connector + .getChannelMessages(channel) + .lastWhere((m) => !m.isOutgoing); + final bubble = find.ancestor( + of: find.textContaining(incoming.text, findRichText: true), + matching: find.byType(MessageBubbleFrame), + ); + await tester.longPressAt(tester.getTopLeft(bubble) + const Offset(4, 4)); + await _settle(tester); + await tester.tap(find.text(_l10n.chat_reply)); + await _settle(tester); + + final quote = find.byType(ChatComposerQuote); + expect( + find.descendant(of: find.byKey(ChatComposer.bubbleKey), matching: quote), + findsOneWidget, + ); + expect(find.text(_l10n.chat_replyingTo(incoming.senderName)), findsOne); + + await tester.tap(find.byTooltip(_l10n.chat_cancelReply)); + await _settle(tester); + expect(quote, findsNothing); + await _tearDown(tester); + }); +} + +Future _pump( + WidgetTester tester, + List providers, + Widget home, +) async { + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ), + ); + await _settle(tester); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +/// One review-radio connection shared by the tests. +(MeshCoreConnector, List)? _shared; + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || connector.channels.isEmpty) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels, isNotEmpty); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/widgets/chat_composer_test.dart b/test/widgets/chat_composer_test.dart new file mode 100644 index 00000000..e75a590c --- /dev/null +++ b/test/widgets/chat_composer_test.dart @@ -0,0 +1,504 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/helpers/gif_helper.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/chat_background.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/chat_background_service.dart'; +import 'package:meshcore_open/services/chat_background_image_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/byte_count_input.dart'; +import 'package:meshcore_open/widgets/chat_background.dart'; +import 'package:meshcore_open/widgets/chat_composer.dart'; +import 'package:meshcore_open/widgets/connect_sheet.dart'; +import 'package:meshcore_open/widgets/gif_message.dart'; +import 'package:meshcore_open/widgets/message_translation_button.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +class _Connector extends MeshCoreConnector { + bool connected = true; + + @override + bool get isConnected => connected; +} + +class _Harness { + final controller = TextEditingController(); + final focusNode = FocusNode(); + final connector = _Connector(); + late final AppSettingsService settings; + late final ChatBackgroundService backgrounds; + int sends = 0; + final actions = []; + + void dispose() { + controller.dispose(); + focusNode.dispose(); + connector.dispose(); + } +} + +Future<_Harness> _harness(WidgetTester tester) async { + final h = _Harness(); + // A date with no holiday nearby, so no holiday chat background applies. + h.settings = AppSettingsService(clock: () => DateTime(2026, 7, 1)); + await tester.runAsync(h.settings.loadSettings); + h.backgrounds = ChatBackgroundService( + h.settings, + imageStore: InMemoryChatBackgroundImageStore(), + ); + addTearDown(h.dispose); + return h; +} + +Widget _app( + _Harness h, { + int maxBytes = 160, + Widget? replyPreview, + bool disableAnimations = false, + Brightness brightness = Brightness.light, +}) { + final composer = ChatComposer( + controller: h.controller, + focusNode: h.focusNode, + maxBytes: maxBytes, + onSend: () => h.sends++, + sendTooltip: _l10n.chat_sendMessage, + actionsBuilder: () => [ + ChatComposerAction( + id: 'gif', + icon: Icons.gif_box, + label: _l10n.chat_sendGif, + ), + ], + onAction: h.actions.add, + replyPreview: replyPreview, + ); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: h.connector), + ChangeNotifierProvider.value(value: h.settings), + ChangeNotifierProvider.value(value: h.backgrounds), + ], + child: MaterialApp( + theme: brightness == Brightness.light + ? MeshTheme.light() + : MeshTheme.dark(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(disableAnimations: disableAnimations), + child: child!, + ), + home: Scaffold( + body: ChatBackdrop( + chatKey: 'contact:test', + footer: composer, + child: const SizedBox.expand(), + ), + ), + ), + ); +} + +Finder get _plus => find.byTooltip(_l10n.chat_selectSendAction); +Finder get _send => find.byTooltip(_l10n.chat_sendMessage); +Finder get _bubble => find.byKey(ChatComposer.bubbleKey); + +Future _type(WidgetTester tester, String text) async { + await tester.enterText(find.byType(TextField), text); + await tester.pumpAndSettle(); +} + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + testWidgets('right circle is + when empty and Send with text', ( + tester, + ) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + // No separate "+" on the left: one round button only. + expect(_plus, findsOneWidget); + expect(_send, findsNothing); + expect(find.byIcon(Icons.add_circle_outline), findsNothing); + + // "+" opens the screen's action menu. + await tester.tap(_plus); + await tester.pumpAndSettle(); + await tester.tap(find.text(_l10n.chat_sendGif)); + await tester.pumpAndSettle(); + expect(h.actions, ['gif']); + + // Whitespace doesn't count as text. + await _type(tester, ' '); + expect(_plus, findsOneWidget); + + await _type(tester, 'On my way'); + expect(_plus, findsNothing); + expect(_send, findsOneWidget); + await tester.tap(_send); + expect(h.sends, 1); + + await _type(tester, ''); + expect(_plus, findsOneWidget); + expect(_send, findsNothing); + }); + + testWidgets('round button has a 48dp touch target and sits right of the ' + 'bubble', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + final plus = find.widgetWithIcon(IconButton, Icons.add); + final size = tester.getSize(plus); + expect(size.width, greaterThanOrEqualTo(48)); + expect(size.height, greaterThanOrEqualTo(48)); + expect( + tester.getTopLeft(plus).dx, + greaterThanOrEqualTo(tester.getTopRight(_bubble).dx), + ); + // Single-line bubble is about one touch target tall. + expect(tester.getSize(_bubble).height, inInclusiveRange(44, 52)); + }); + + testWidgets('swap animates, and is instant with animations disabled', ( + tester, + ) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'hi'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + // Mid-transition both icons are on screen. + expect(_plus, findsOneWidget); + expect(_send, findsOneWidget); + await tester.pumpAndSettle(); + expect(_plus, findsNothing); + + final reduced = await _harness(tester); + await tester.pumpWidget(_app(reduced, disableAnimations: true)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'hi'); + await tester.pump(); + await tester.pump(); + expect(_plus, findsNothing); + expect(_send, findsOneWidget); + }); + + testWidgets('field grows to 5 lines then scrolls, buttons stay at the ' + 'bottom', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h, maxBytes: 1000)); + await tester.pumpAndSettle(); + + final field = tester.widget(find.byType(TextField)); + expect(field.minLines, 1); + expect(field.maxLines, kComposerMaxLines); + + await _type(tester, 'one'); + final oneLine = tester.getSize(find.byType(TextField)).height; + final sendBottom = tester.getBottomLeft(_send).dy; + final bubbleBottom = tester.getBottomLeft(_bubble).dy; + + await _type(tester, List.filled(5, 'line').join('\n')); + final fiveLines = tester.getSize(find.byType(TextField)).height; + expect(fiveLines, greaterThan(oneLine * 2)); + + await _type(tester, List.filled(12, 'line').join('\n')); + expect(tester.getSize(find.byType(TextField)).height, fiveLines); + + // The panel grows upwards; the send button keeps its place at the + // bottom of the bubble. + expect(tester.getBottomLeft(_send).dy, sendBottom); + expect(tester.getBottomLeft(_bubble).dy, bubbleBottom); + }); + + testWidgets('a short window still lets the field wrap onto two lines', ( + tester, + ) async { + tester.view.physicalSize = const Size(600, 260); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = 2.0; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final h = await _harness(tester); + await tester.pumpWidget(_app(h, maxBytes: 1000)); + await tester.pumpAndSettle(); + + expect( + tester.widget(find.byType(TextField)).maxLines, + greaterThanOrEqualTo(2), + ); + }); + + testWidgets('byte counter shows only past the warning threshold and ' + 'takes no space before', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h, maxBytes: 20)); + await tester.pumpAndSettle(); + final emptyHeight = tester.getSize(_bubble).height; + + await _type(tester, 'a' * 14); // 70 %: not past the threshold + expect(find.text('14 / 20'), findsNothing); + expect(tester.getSize(_bubble).height, emptyHeight); + + await _type(tester, 'a' * 15); + final counter = find.text('15 / 20'); + expect(counter, findsOneWidget); + expect(find.descendant(of: _bubble, matching: counter), findsOneWidget); + // Bottom-right of the bubble. + expect( + tester.getCenter(counter).dx, + greaterThan(tester.getCenter(_bubble).dx), + ); + expect( + tester.getCenter(counter).dy, + greaterThan(tester.getCenter(find.byType(TextField)).dy), + ); + + // The byte limit itself is unchanged. + await _type(tester, 'a' * 30); + expect(h.controller.text.length, 20); + }); + + testWidgets('ByteCountedTextField defaults are unchanged for other ' + 'screens', (tester) async { + final controller = TextEditingController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ByteCountedTextField(maxBytes: 20, controller: controller), + ), + ), + ); + final field = tester.widget(find.byType(TextField)); + expect(field.maxLines, isNull); + // The counter row keeps its place while hidden. + expect(find.text('0 / 20'), findsOneWidget); + }); + + testWidgets('reply preview renders inside the top of the bubble and can ' + 'be dismissed', (tester) async { + final h = await _harness(tester); + var dismissed = false; + await tester.pumpWidget( + _app( + h, + replyPreview: ChatComposerQuote( + title: _l10n.chat_replyingTo('Bob'), + content: const Text('see you at camp'), + onDismiss: () => dismissed = true, + dismissTooltip: _l10n.chat_cancelReply, + ), + ), + ); + await tester.pumpAndSettle(); + + final quote = find.byType(ChatComposerQuote); + expect(find.descendant(of: _bubble, matching: quote), findsOneWidget); + expect(find.text(_l10n.chat_replyingTo('Bob')), findsOneWidget); + expect( + tester.getBottomLeft(quote).dy, + lessThanOrEqualTo(tester.getTopLeft(find.byType(TextField)).dy), + ); + + await tester.tap(find.byTooltip(_l10n.chat_cancelReply)); + expect(dismissed, isTrue); + }); + + testWidgets('GIF preview sits in the bubble, sends on Enter and can be ' + 'removed', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + h.controller.text = GifHelper.encodeGif('abc123'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + + expect( + find.descendant(of: _bubble, matching: find.byType(GifMessage)), + findsOneWidget, + ); + expect(find.byType(TextField), findsNothing); + expect(_send, findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(h.sends, 1); + + await tester.tap(find.byTooltip(_l10n.chat_removeGif)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + expect(h.controller.text, isEmpty); + expect(find.byType(TextField), findsOneWidget); + expect(_plus, findsOneWidget); + }); + + testWidgets('translate button sits inside the bubble when enabled', ( + tester, + ) async { + final h = await _harness(tester); + await tester.runAsync(() => h.settings.setTranslationEnabled(true)); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + final translate = find.byType(MessageTranslationButton); + expect(find.descendant(of: _bubble, matching: translate), findsOneWidget); + expect( + tester.getCenter(translate).dx, + greaterThan(tester.getCenter(find.byType(TextField)).dx), + ); + expect( + find.descendant(of: translate, matching: find.byType(Tooltip)), + findsOneWidget, + ); + }); + + testWidgets('panel is solid without a chat background and transparent ' + 'over one', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + final scheme = MeshTheme.light().colorScheme; + Color bubbleColor() => + ((tester.widget(_bubble).decoration as BoxDecoration) + .color) + as Color; + final panelFill = find.ancestor( + of: _bubble, + matching: find.byWidgetPredicate( + (w) => w is ColoredBox && w.color == scheme.surface, + ), + ); + expect(panelFill, findsOneWidget); + expect(bubbleColor(), scheme.surfaceContainerHigh); + + await tester.runAsync( + () => h.backgrounds.setChatBackground( + 'contact:test', + const ChatBackground.color(Color(0xFF1E3A8A)), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(ChatBackgroundLayer), findsOneWidget); + expect(panelFill, findsNothing); + // Incoming-bubble colour keeps the text readable over the background. + expect(bubbleColor(), scheme.surfaceContainerLow); + }); + + testWidgets('offline bar uses the same bubble and height as the composer', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + final composerTop = tester.getTopLeft(_bubble).dy; + final composerHeight = tester.getSize(_bubble).height; + + h.connector.connected = false; + h.connector.notifyListeners(); + await tester.pumpAndSettle(); + + expect(find.byType(OfflineComposerBar), findsOneWidget); + expect(find.byType(TextField), findsNothing); + expect(find.byType(ConnectButton), findsOneWidget); + expect(find.text(_l10n.chat_composerOffline), findsOneWidget); + final decoration = + tester.widget(_bubble).decoration as BoxDecoration; + expect( + decoration.borderRadius, + BorderRadius.circular(kComposerBubbleRadius), + ); + expect(tester.getSize(_bubble).height, composerHeight); + expect(tester.getTopLeft(_bubble).dy, composerTop); + + // The draft survives and comes back with the radio. + h.controller.text = 'draft'; + h.connector.connected = true; + h.connector.notifyListeners(); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(TextField)).controller?.text, + 'draft', + ); + }); + + for (final scale in [1.3, 2.0]) { + for (final brightness in Brightness.values) { + testWidgets('fits 320dp at ${scale}x text (${brightness.name})', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = scale; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final h = await _harness(tester); + await tester.runAsync(() => h.settings.setTranslationEnabled(true)); + await tester.pumpWidget( + _app( + h, + maxBytes: 20, + brightness: brightness, + replyPreview: ChatComposerQuote( + title: _l10n.chat_replyingTo('A very long sender name here'), + content: const Text( + 'a long quoted message that must ellipsize', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + onDismiss: () {}, + dismissTooltip: _l10n.chat_cancelReply, + ), + ), + ); + await tester.pumpAndSettle(); + await _type(tester, 'a' * 19); + expect(tester.takeException(), isNull); + + // With the keyboard up, a long draft still fits: the field caps its + // lines to the room left. + tester.view.viewInsets = const FakeViewPadding(bottom: 260); + await _type(tester, List.filled(8, 'line').join('\n')); + expect(tester.takeException(), isNull); + tester.view.resetViewInsets(); + await tester.pumpAndSettle(); + + h.connector.connected = false; + h.connector.notifyListeners(); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); + } + } +} From d7fff0533eba145744e7e1db5fb6e919b3ca0b39 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:49 -0700 Subject: [PATCH 13/50] Allow building without ONNX Runtime flutter_onnxruntime downloads ORT natively at build time, and the Linux and Windows downloads from github.com/microsoft/onnxruntime are unavailable. scripts/onnx.sh off swaps in a pure-Dart stub via pubspec_overrides.yaml, so no platform pulls ORT; image messages then show as unavailable, as on web. Linux CI builds use this mode for now. --- .github/workflows/build.yml | 10 +++- .github/workflows/flutter_dart.yml | 6 +++ .gitignore | 3 ++ README.md | 20 +++++++ documentation/image-messages.md | 6 ++- lib/services/image_codec_backend.dart | 29 ++++++++-- lib/services/image_codec_service.dart | 12 +++-- scripts/appimage/test_runtime.sh | 7 ++- scripts/onnx.sh | 54 +++++++++++++++++++ test/services/image_codec_runtime_test.dart | 35 ++++++++++++ .../lib/flutter_onnxruntime.dart | 37 +++++++++++++ .../flutter_onnxruntime_stub/pubspec.yaml | 9 ++++ 12 files changed, 215 insertions(+), 13 deletions(-) create mode 100755 scripts/onnx.sh create mode 100644 test/services/image_codec_runtime_test.dart create mode 100644 third_party/flutter_onnxruntime_stub/lib/flutter_onnxruntime.dart create mode 100644 third_party/flutter_onnxruntime_stub/pubspec.yaml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6c9db6f6..022e1a4f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,6 +12,12 @@ on: - 'v*' pull_request: +env: + # ONNX Runtime for the Linux jobs. Its Linux downloads from + # github.com/microsoft/onnxruntime currently 404, so tagged Linux AppImages + # ship without image messages until this is set back to "on". + MESHCORE_LINUX_ONNX: "off" + jobs: android: runs-on: ubuntu-latest @@ -71,7 +77,7 @@ jobs: run: | shellcheck scripts/build_appimage.sh scripts/appimage/*.sh scripts/appimage/AppRun bash scripts/appimage/test_packaging.sh - - run: flutter pub get + - run: scripts/onnx.sh "$MESHCORE_LINUX_ONNX" - run: flutter build linux --release --no-pub - uses: docker/setup-buildx-action@v3 - name: Read AppImage base image @@ -141,7 +147,7 @@ jobs: run: | shellcheck scripts/build_appimage.sh scripts/appimage/*.sh scripts/appimage/AppRun bash scripts/appimage/test_packaging.sh - - run: flutter pub get + - run: scripts/onnx.sh "$MESHCORE_LINUX_ONNX" - run: flutter test --reporter expanded - name: Build ARM64 Linux release run: | diff --git a/.github/workflows/flutter_dart.yml b/.github/workflows/flutter_dart.yml index 93fdd230..3ac94bcc 100644 --- a/.github/workflows/flutter_dart.yml +++ b/.github/workflows/flutter_dart.yml @@ -38,3 +38,9 @@ jobs: - name: Run tests run: flutter test -r github + + - name: Analyze and test without ONNX Runtime + run: | + scripts/onnx.sh off + flutter analyze --fatal-infos --fatal-warnings + flutter test -r github diff --git a/.gitignore b/.gitignore index 6e4fb526..43dcc50b 100644 --- a/.gitignore +++ b/.gitignore @@ -94,3 +94,6 @@ keystore.properties # Claude Code local working dir (worktrees, jobs, settings) .claude/ + +# Written by scripts/onnx.sh off (ONNX-free build) +/pubspec_overrides.yaml diff --git a/README.md b/README.md index 958589d7..b05e7449 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,26 @@ The matrix describes implemented functionality, not a guarantee that every featu flutter run ``` +### Building without ONNX Runtime + +ONNX Runtime (ORT) runs only the [image message](documentation/image-messages.md) codec, and every platform build fetches it: Linux and Windows from GitHub releases, Android from Maven Central, iOS and macOS from CocoaPods/SwiftPM. If those downloads fail, build without it: + +```bash +scripts/onnx.sh off # stub flutter_onnxruntime, then flutter pub get +flutter build apk --release # or linux, windows, ios, macos +scripts/onnx.sh on # back to the default build +``` + +`off` writes a git-ignored `pubspec_overrides.yaml` that points `flutter_onnxruntime` at the pure-Dart stub in `third_party/flutter_onnxruntime_stub`, so no native plugin or ORT library is built, downloaded or bundled. On Windows without bash, create that file by hand: + +```yaml +dependency_overrides: + flutter_onnxruntime: + path: third_party/flutter_onnxruntime_stub +``` + +Image messages then behave as on web: the app cannot send them or reconstruct received ones, and Settings says the build has no ONNX Runtime. Everything else is unchanged. While the override is active, `flutter pub get` also rewrites the committed plugin registrants (`linux/`, `windows/`, `macos/Flutter/`); switch back before committing. Linux builds in CI (`.github/workflows/build.yml`) currently use this mode because the ORT Linux release downloads are unavailable. + ### Linux AppImage `flutter build linux --release` produces the regular Flutter bundle and an diff --git a/documentation/image-messages.md b/documentation/image-messages.md index 935dd398..1881ba0a 100644 --- a/documentation/image-messages.md +++ b/documentation/image-messages.md @@ -5,12 +5,16 @@ MeshCore Open can send a highly compressed image as channel GRP_DATA packets. Un ## Requirements and setup - Companion firmware version code **11 or later** (identified in the connector as v1.15.0) for the current channel-data layout. -- A native runtime with a working ONNX backend. The web build has no image codec backend. +- A native runtime with a working ONNX backend. The web build has no image codec backend, and neither does a native build made without ONNX Runtime (see below). - The image model bundle installed through App Settings → Image model, and Enable image messages turned on. - Enough storage for the roughly 1 GB bundle and enough available memory for reconstruction, which can peak above 2 GB. Actual latency and memory usage depend on hardware. Downloads use the configured Hugging Face model bundle, support resume, and verify file checksums. Download the model while internet is available. Once installed, encoding and reconstruction run locally; photos are not uploaded for inference. Compatible recipients need the same supported codec/model format. +### Builds without ONNX Runtime + +`scripts/onnx.sh off` builds the app with a pure-Dart stub in place of `flutter_onnxruntime`, so no platform downloads or bundles ORT ([how to build](../README.md#building-without-onnx-runtime)). In that build image messages are unavailable, exactly as on web: the image button and Settings explain that the build has no ONNX Runtime, the model cannot be downloaded, and received images cannot be reconstructed. `scripts/onnx.sh on` restores the default build. The app detects the stub because its `OnnxRuntime()` constructor throws (`imageCodecRuntimeAvailable` in [image_codec_backend.dart](../lib/services/image_codec_backend.dart)). + ## Send an image 1. Open channel chat and tap the image button beside the composer. diff --git a/lib/services/image_codec_backend.dart b/lib/services/image_codec_backend.dart index e453f565..8335acde 100644 --- a/lib/services/image_codec_backend.dart +++ b/lib/services/image_codec_backend.dart @@ -871,14 +871,33 @@ class ImageCodecCancelled implements Exception { String toString() => 'Image processing stopped.'; } +/// Whether this build can run the image codec at all. +/// +/// False on web and in a build made with `scripts/onnx.sh off`, where +/// `flutter_onnxruntime` is the pure-Dart stub whose [OnnxRuntime] constructor +/// throws [UnsupportedError]. The real constructor has no side effects. +final bool imageCodecRuntimeAvailable = _probeOnnxRuntime(); + +bool _probeOnnxRuntime() { + if (kIsWeb) { + return false; + } + try { + OnnxRuntime(); + return true; + } on UnsupportedError { + return false; + } +} + /// Factory used by the codec worker isolate. /// -/// Returns `null` on web, where there is no local model file and no isolate. -/// Everywhere else it returns the real [OnnxImageCodecBackend]; the session -/// turns a `null` here into an [ImageCodecUnimplemented], which the service -/// surfaces as `lastError` and maps to `ImageCodecAvailability.unavailable`. +/// Returns `null` when [imageCodecRuntimeAvailable] is false. Everywhere else +/// it returns the real [OnnxImageCodecBackend]; the session turns a `null` +/// here into an [ImageCodecUnimplemented], which the service surfaces as +/// `lastError` and maps to `ImageCodecAvailability.unavailable`. ImageCodecBackend? createImageCodecBackend() { - if (kIsWeb) { + if (!imageCodecRuntimeAvailable) { return null; } return OnnxImageCodecBackend(); diff --git a/lib/services/image_codec_service.dart b/lib/services/image_codec_service.dart index 932d90d7..2c5443a4 100644 --- a/lib/services/image_codec_service.dart +++ b/lib/services/image_codec_service.dart @@ -8,7 +8,8 @@ import '../models/image_codec_support.dart'; import '../utils/app_logger.dart'; import '../widgets/image_send_codec_binding.dart'; import 'app_settings_service.dart'; -import 'image_codec_backend.dart' show kImageCodecBitstreamPathAvailable; +import 'image_codec_backend.dart' + show imageCodecRuntimeAvailable, kImageCodecBitstreamPathAvailable; import 'image_codec_file_store.dart'; import 'image_codec_session.dart'; import 'image_codec_settings_store.dart'; @@ -177,9 +178,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec { /// Why [availability] is `unavailable`, or null when it is not. /// - /// EXACTLY THREE CAUSES, all of them permanent properties of the build or the + /// EXACTLY FOUR CAUSES, all of them permanent properties of the build or the /// platform, none of them fixable by the user: /// * web, which has no native inference runtime; + /// * a build made without ONNX Runtime ([imageCodecRuntimeAvailable]); /// * a build compiled without the entropy path /// ([kImageCodecBitstreamPathAvailable]); /// * a backend that failed to load. @@ -194,6 +196,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec { return 'The image codec needs a native inference runtime, which the web ' 'build does not have.'; } + if (!imageCodecRuntimeAvailable) { + return 'This build was made without ONNX Runtime, so it cannot send or ' + 'show image messages.'; + } if (!kImageCodecBitstreamPathAvailable) { return 'This build ships the image decoder only. Encoding and decoding a ' 'bitstream also needs the entropy-side graph and the rANS coder, ' @@ -510,7 +516,7 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec { /// works. [canEncode]/[canDecode] additionally require the entropy path. bool get canRunInference { final model = selectedModel; - return !kIsWeb && + return imageCodecRuntimeAvailable && !_backendMissing && model != null && model.localPath.isNotEmpty; diff --git a/scripts/appimage/test_runtime.sh b/scripts/appimage/test_runtime.sh index c09e60f1..2bcf6ec5 100644 --- a/scripts/appimage/test_runtime.sh +++ b/scripts/appimage/test_runtime.sh @@ -72,8 +72,11 @@ appdir="$workspace/squashfs-root" log 'Checking extracted AppImage structure' [[ -x "$appdir/AppRun" && -f "$appdir/usr/bin/lib/libapp.so" && \ -f "$appdir/usr/bin/data/icudtl.dat" && -d "$appdir/usr/bin/data/flutter_assets" ]] -[[ -f "$appdir/usr/bin/lib/libonnxruntime.so.1" && \ - -f "$appdir/usr/share/glib-2.0/schemas/gschemas.compiled" ]] +[[ -f "$appdir/usr/share/glib-2.0/schemas/gschemas.compiled" ]] +# ONNX-free builds (scripts/onnx.sh off) have neither the plugin nor ORT. +if [[ -f "$appdir/usr/bin/lib/libflutter_onnxruntime_plugin.so" ]]; then + [[ -f "$appdir/usr/bin/lib/libonnxruntime.so.1" ]] +fi log 'Starting bundled ELF architecture audit' elf_count=0 diff --git a/scripts/onnx.sh b/scripts/onnx.sh new file mode 100755 index 00000000..5f3b9cdd --- /dev/null +++ b/scripts/onnx.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Switch ONNX Runtime (the image codec's inference engine) on or off. +# +# scripts/onnx.sh off build without ORT: no native plugin, no downloads +# scripts/onnx.sh on default build with ORT +# scripts/onnx.sh status print the current mode +# +# "off" writes pubspec_overrides.yaml, pointing flutter_onnxruntime at the +# pure-Dart stub in third_party/flutter_onnxruntime_stub; "on" removes it. +# Both run `flutter pub get` (set FLUTTER to use another flutter binary). +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +overrides="$root/pubspec_overrides.yaml" +marker='# Written by scripts/onnx.sh' +flutter_bin="${FLUTTER:-flutter}" + +is_ours() { + [[ -f "$overrides" ]] && grep -Fq "$marker" "$overrides" +} + +case "${1:-}" in + off) + if [[ -f "$overrides" ]] && ! is_ours; then + echo "pubspec_overrides.yaml exists and was not written by this script; edit it by hand." >&2 + exit 1 + fi + cat > "$overrides" <&2 + exit 1 + fi + rm -f "$overrides" + ;; + status) + if is_ours; then echo off; else echo on; fi + exit 0 + ;; + *) + echo "usage: $0 off|on|status" >&2 + exit 2 + ;; +esac + +cd "$root" +"$flutter_bin" pub get +echo "ONNX Runtime: $1" diff --git a/test/services/image_codec_runtime_test.dart b/test/services/image_codec_runtime_test.dart new file mode 100644 index 00000000..e175903f --- /dev/null +++ b/test/services/image_codec_runtime_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/image_codec_backend.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/image_codec_settings_store.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; + +/// Runs in both build modes; each half skips in the other (`scripts/onnx.sh`). +void main() { + ImageCodecService newService() { + final service = ImageCodecService( + AppSettingsService(), + settingsStore: InMemoryImageCodecSettingsStore( + const ImageCodecPreferences(enabled: true), + ), + ); + addTearDown(service.dispose); + return service; + } + + test('ONNX-free build reports the image codec unavailable', () { + final service = newService(); + expect(createImageCodecBackend(), isNull); + expect(service.availability, ImageCodecAvailability.unavailable); + expect(service.unavailableReason, contains('without ONNX Runtime')); + expect(service.canRunInference, isFalse); + }, skip: imageCodecRuntimeAvailable ? 'ONNX Runtime is compiled in' : false); + + test('ONNX build has a codec backend', () { + final service = newService(); + expect(createImageCodecBackend(), isA()); + expect(service.unavailableReason, isNull); + }, skip: imageCodecRuntimeAvailable ? false : 'built without ONNX Runtime'); +} diff --git a/third_party/flutter_onnxruntime_stub/lib/flutter_onnxruntime.dart b/third_party/flutter_onnxruntime_stub/lib/flutter_onnxruntime.dart new file mode 100644 index 00000000..64bb6461 --- /dev/null +++ b/third_party/flutter_onnxruntime_stub/lib/flutter_onnxruntime.dart @@ -0,0 +1,37 @@ +/// Stand-in for `flutter_onnxruntime` in builds made without ONNX Runtime. +/// +/// Mirrors only the API MeshCore Open uses. [OnnxRuntime] cannot be +/// constructed, which is how the app detects this build. +library; + +UnsupportedError _unsupported() => + UnsupportedError('This build was made without ONNX Runtime.'); + +class OnnxRuntime { + OnnxRuntime() { + throw _unsupported(); + } + + Future createSession(String modelPath) => throw _unsupported(); +} + +abstract class OrtSession { + List get inputNames; + + List get outputNames; + + Future> run(Map inputs); + + Future close(); +} + +abstract class OrtValue { + List get shape; + + static Future fromList(dynamic data, List shape) => + throw _unsupported(); + + Future> asFlattenedList(); + + Future dispose(); +} diff --git a/third_party/flutter_onnxruntime_stub/pubspec.yaml b/third_party/flutter_onnxruntime_stub/pubspec.yaml new file mode 100644 index 00000000..4027cb5a --- /dev/null +++ b/third_party/flutter_onnxruntime_stub/pubspec.yaml @@ -0,0 +1,9 @@ +name: flutter_onnxruntime +description: >- + Pure-Dart stand-in for flutter_onnxruntime, used by `scripts/onnx.sh off` to + build MeshCore Open without ONNX Runtime. No native plugin, no downloads. +version: 1.9.0 +publish_to: none + +environment: + sdk: ^3.7.0 From 9ffdbaae09e19f7bb019c47e2fe6f0b2995cb84b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 00:05:39 +0000 Subject: [PATCH 14/50] Use one model row for image and translation downloads Image settings, translation settings, and the restore prompt each listed models differently. Share ModelDownloadList so every model shows the same name, size, status, selection, and download, cancel, or remove action. Co-authored-by: zjs81 --- documentation/design.md | 17 + documentation/image-messages.md | 2 +- documentation/settings.md | 6 +- lib/l10n/app_bg.arb | 13 +- lib/l10n/app_cs.arb | 13 +- lib/l10n/app_de.arb | 13 +- lib/l10n/app_en.arb | 28 +- lib/l10n/app_es.arb | 13 +- lib/l10n/app_fr.arb | 13 +- lib/l10n/app_hu.arb | 13 +- lib/l10n/app_it.arb | 13 +- lib/l10n/app_ja.arb | 13 +- lib/l10n/app_ko.arb | 13 +- lib/l10n/app_localizations.dart | 58 +- lib/l10n/app_localizations_bg.dart | 36 +- lib/l10n/app_localizations_cs.dart | 36 +- lib/l10n/app_localizations_de.dart | 36 +- lib/l10n/app_localizations_en.dart | 36 +- lib/l10n/app_localizations_es.dart | 36 +- lib/l10n/app_localizations_fr.dart | 36 +- lib/l10n/app_localizations_hu.dart | 36 +- lib/l10n/app_localizations_it.dart | 36 +- lib/l10n/app_localizations_ja.dart | 36 +- lib/l10n/app_localizations_ko.dart | 36 +- lib/l10n/app_localizations_nl.dart | 36 +- lib/l10n/app_localizations_pl.dart | 36 +- lib/l10n/app_localizations_pt.dart | 72 +- lib/l10n/app_localizations_ru.dart | 36 +- lib/l10n/app_localizations_sk.dart | 36 +- lib/l10n/app_localizations_sl.dart | 36 +- lib/l10n/app_localizations_sv.dart | 36 +- lib/l10n/app_localizations_uk.dart | 36 +- lib/l10n/app_localizations_zh.dart | 35 +- lib/l10n/app_nl.arb | 13 +- lib/l10n/app_pl.arb | 13 +- lib/l10n/app_pt.arb | 13 +- lib/l10n/app_pt_PT.arb | 13 +- lib/l10n/app_ru.arb | 13 +- lib/l10n/app_sk.arb | 13 +- lib/l10n/app_sl.arb | 13 +- lib/l10n/app_sv.arb | 13 +- lib/l10n/app_uk.arb | 13 +- lib/l10n/app_zh.arb | 13 +- lib/screens/app_settings_screen.dart | 168 +---- lib/screens/backup_restore_screen.dart | 143 +++- lib/widgets/image_codec_models_section.dart | 297 ++++++++ lib/widgets/model_download_list.dart | 338 +++++++++ lib/widgets/translation_settings_section.dart | 688 ++++++++++-------- test/widgets/model_download_list_test.dart | 302 ++++++++ untranslated.json | 344 ++++----- 50 files changed, 2524 insertions(+), 833 deletions(-) create mode 100644 lib/widgets/image_codec_models_section.dart create mode 100644 lib/widgets/model_download_list.dart create mode 100644 test/widgets/model_download_list_test.dart diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..4121061e 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -122,6 +122,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Popup menu row | **always** `PopupMenuItem(child: MeshMenuItemRow(icon:, label:))` | Label wraps to 2 lines then ellipsizes; `leading:` for `ThemedIcon`; no icon keeps the 20px slot | | Segmented button label | **always** `ButtonSegment(label: MeshSegmentLabel(text))` | Shrinks to 12 (before system scale), then wraps at word boundaries onto 2 centred lines; never breaks a word | | Status | `StatusChip` | Mono label, coloured dot or icon | +| On-device model | `ModelDownloadList` | Name, size, status, selection and one action. See [Model downloads](#model-downloads). | | Metric | `StatTile` | Label wraps to 2 lines; value wraps | | Signal | `SignalBars`, `MeshTheme.snrColor` | | | Route kind | `RouteChip` | Direct / hop count / Flood | @@ -147,6 +148,22 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act **IconButton.** Always set `tooltip:` with a localized string. It is the accessible name. +### Model downloads + +Image models, translation models, and the restore prompt that fetches missing models all use `ModelDownloadList` (`lib/widgets/model_download_list.dart`). Do not add a second download form (a dropdown of presets, a separate filename row, or a one-off progress bar). + +One model is one row inside the existing `MeshCard`, rows separated by `Divider(height: 1, indent: 16)`: + +| Part | What it shows | +|---|---| +| Title | Friendly name, `meshTileTitleStyle` (`bodyLarge` w600). It wraps. Never a raw filename or URL. | +| Subtitle | Size via the `mapCache_size*` strings when known, then the status: Not downloaded, Downloading, Ready, or Couldn't download. The model in use also says Active. An install that stopped part-way says Incomplete. The words stay `onSurfaceVariant` (Active is w600). The leading icon carries the colour: `primary` when that model is active or downloading, `error` on failure, `onSurfaceVariant` otherwise. | +| Progress | While downloading, a `LinearProgressIndicator` (indeterminate when the total is unknown, or while chunks are merged or the file is verified) and a mono 12 caption of bytes and percent. | +| Action | One `IconButton` with a localized tooltip: Download, Cancel, or Remove model. An install that already has files but is not ready shows both Download and Remove. Tap a Ready row to select it when more than one model can be active. A row the user cannot use is dimmed to 50 %, same as a disabled `MeshNavTile`. | +| Manual URL | When the feature accepts one (translation), put a single text field under the list. Its download control is the same Download icon. The file joins this list. | + +A dialog that offers several missing models (backup restore) uses the same rows for name, size, status and progress, and keeps its own confirm button. + ## 6. Sheets, dialogs and pages What the code does: diff --git a/documentation/image-messages.md b/documentation/image-messages.md index 935dd398..2725ed4d 100644 --- a/documentation/image-messages.md +++ b/documentation/image-messages.md @@ -9,7 +9,7 @@ MeshCore Open can send a highly compressed image as channel GRP_DATA packets. Un - The image model bundle installed through App Settings → Image model, and Enable image messages turned on. - Enough storage for the roughly 1 GB bundle and enough available memory for reconstruction, which can peak above 2 GB. Actual latency and memory usage depend on hardware. -Downloads use the configured Hugging Face model bundle, support resume, and verify file checksums. Download the model while internet is available. Once installed, encoding and reconstruction run locally; photos are not uploaded for inference. Compatible recipients need the same supported codec/model format. +Downloads use the configured Hugging Face model bundle, support resume, and verify file checksums. App Settings shows that bundle as one model row — name, size, and status — the same row used for translation models. Download the model while internet is available. Once installed, encoding and reconstruction run locally; photos are not uploaded for inference. Compatible recipients need the same supported codec/model format. ## Send an image diff --git a/documentation/settings.md b/documentation/settings.md index 3f101f07..a785b4dd 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -153,9 +153,7 @@ Not shown on web. Controls on-device message translation powered by a locally-do - **Auto-translate incoming messages**: Automatically translates incoming messages for chat/channel display and notifications - **Translate before sending**: Sets the default state of the composer's translate icon (on means messages are translated before sending) - **Target language**: Language to translate into (searchable list; defaults to the app language) -- **Downloaded model**: Dropdown to select among already-downloaded translation models -- **Preset Hugging Face model**: Download a curated preset model with one tap -- **Manual model URL**: Enter a URL to download a custom GGUF-format model; shows download progress and a cancel button +- **Models**: The same model rows used for the image codec. Each preset is one row with its name, size once known, and status (not downloaded, downloading with progress, ready, or couldn't download). The model in use is marked Active; tap another ready row to switch. Download, cancel, and remove are the row's action. A manual model URL under the list downloads a custom GGUF file into the same list. The auto-translate and composer toggles are disabled until **Enable translation** is on. @@ -175,7 +173,7 @@ Save the settings before sharing. The upload action is shown in the chat compose ### Image Messages -Image message controls live in App Settings → Messaging. Turn on **Enable image messages** first; **Process images automatically** and the image model download/cancel/removal controls then appear. Automatic processing reconstructs every image as it arrives and uses about 2 GB of memory for a second each time; leave it off to reconstruct with a tap. See [Image Messages](image-messages.md) for firmware, native-runtime, storage, and memory requirements. +Image message controls live in App Settings → Messaging. Turn on **Enable image messages** first; **Process images automatically** and the image model row then appear. That row is the same model list used for translation: name, size, status (not downloaded, downloading with progress, ready, or couldn't download), and one action (download, cancel, or remove). A finished install is marked Active. Automatic processing reconstructs every image as it arrives and uses about 2 GB of memory for a second each time; leave it off to reconstruct with a tap. See [Image Messages](image-messages.md) for firmware, native-runtime, storage, and memory requirements. ### Cyrillic-to-Latin (Cyr2Lat) Controls character substitution profiles used to render Cyrillic text in Latin characters. A dropdown selects the active profile; Add, Edit, and Delete buttons manage the profile list (the last remaining profile cannot be deleted). Each profile stores a JSON character map. diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 913a0815..90289d2c 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3756,7 +3756,7 @@ "backupRestore_backupComplete": "Файлът с резервно копие е създаден.", "backupRestore_restoreComplete": "Възстановяването приключи. Свържете се отново, ако сте възстановили идентичността на радиото.", "backupRestore_missingModelsTitle": "Моделите не са изтеглени", - "backupRestore_missingModelsMessage": "Възстановените настройки избират модели, които не са налични на това устройство:\n{models}\n\nДа се изтеглят ли сега?", + "backupRestore_missingModelsMessage": "Възстановените настройки избират модели, които не са налични на това устройство. Да се изтеглят ли сега?", "backupRestore_downloadModels": "Изтегли модели", "backupRestore_downloading": "Изтегляне…", "backupRestore_cancelDownload": "Отмени изтеглянето", @@ -3776,5 +3776,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB или TCP", "connectSheet_stopReconnecting": "Спри повторното свързване", "connectSheet_reconnectFailed": "Няма връзка с {name}. Уверете се, че е включено и наблизо.", - "chat_composerOffline": "Свържете се с радио, за да изпращате съобщения" + "chat_composerOffline": "Свържете се с радио, за да изпращате съобщения", + "modelDownload_notDownloaded": "Не е изтеглен", + "modelDownload_downloading": "Изтегляне", + "modelDownload_active": "Активен", + "modelDownload_failed": "Неуспешно изтегляне", + "modelDownload_incomplete": "Непълен", + "modelDownload_verifying": "Проверка на изтеглянето", + "modelDownload_useModel": "Използвай този модел", + "modelDownload_removeFailed": "Моделът не можа да бъде премахнат: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index f72e9821..04ead9b8 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -4369,7 +4369,7 @@ "backupRestore_backupComplete": "Soubor zálohy byl vytvořen.", "backupRestore_restoreComplete": "Obnovení dokončeno. Pokud jste obnovili identitu rádia, připojte se znovu.", "backupRestore_missingModelsTitle": "Modely nejsou stažené", - "backupRestore_missingModelsMessage": "Obnovené nastavení vybírá modely, které nejsou v tomto zařízení k dispozici:\n{models}\n\nStáhnout je nyní?", + "backupRestore_missingModelsMessage": "Obnovené nastavení vybírá modely, které nejsou v tomto zařízení k dispozici. Stáhnout je nyní?", "backupRestore_downloadModels": "Stáhnout modely", "backupRestore_downloading": "Stahování…", "backupRestore_cancelDownload": "Zrušit stahování", @@ -4389,5 +4389,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB nebo TCP", "connectSheet_stopReconnecting": "Zastavit připojování", "connectSheet_reconnectFailed": "Nelze se spojit s {name}. Ujistěte se, že je zapnuté a nablízku.", - "chat_composerOffline": "Pro odesílání zpráv se připojte k rádiu" + "chat_composerOffline": "Pro odesílání zpráv se připojte k rádiu", + "modelDownload_notDownloaded": "Nestaženo", + "modelDownload_downloading": "Stahování", + "modelDownload_active": "Aktivní", + "modelDownload_failed": "Stažení se nezdařilo", + "modelDownload_incomplete": "Neúplné", + "modelDownload_verifying": "Ověřování stažení", + "modelDownload_useModel": "Použít tento model", + "modelDownload_removeFailed": "Model se nepodařilo odebrat: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 40d00f84..6a8faacd 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3891,7 +3891,7 @@ "backupRestore_backupComplete": "Sicherungsdatei erstellt.", "backupRestore_restoreComplete": "Wiederherstellung abgeschlossen. Verbinden Sie sich erneut, wenn Sie die Funkidentität wiederhergestellt haben.", "backupRestore_missingModelsTitle": "Modelle nicht heruntergeladen", - "backupRestore_missingModelsMessage": "Die wiederhergestellten Einstellungen wählen Modelle aus, die auf diesem Gerät nicht verfügbar sind:\n{models}\n\nJetzt herunterladen?", + "backupRestore_missingModelsMessage": "Die wiederhergestellten Einstellungen wählen Modelle aus, die auf diesem Gerät nicht verfügbar sind. Jetzt herunterladen?", "backupRestore_downloadModels": "Modelle herunterladen", "backupRestore_downloading": "Wird heruntergeladen…", "backupRestore_cancelDownload": "Download abbrechen", @@ -3911,5 +3911,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB oder TCP", "connectSheet_stopReconnecting": "Wiederverbindung abbrechen", "connectSheet_reconnectFailed": "{name} ist nicht erreichbar. Stellen Sie sicher, dass es eingeschaltet und in der Nähe ist.", - "chat_composerOffline": "Mit einem Funkgerät verbinden, um Nachrichten zu senden" + "chat_composerOffline": "Mit einem Funkgerät verbinden, um Nachrichten zu senden", + "modelDownload_notDownloaded": "Nicht heruntergeladen", + "modelDownload_downloading": "Wird heruntergeladen", + "modelDownload_active": "Aktiv", + "modelDownload_failed": "Download fehlgeschlagen", + "modelDownload_incomplete": "Unvollständig", + "modelDownload_verifying": "Download wird geprüft", + "modelDownload_useModel": "Dieses Modell verwenden", + "modelDownload_removeFailed": "Das Modell konnte nicht entfernt werden: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..72b1dcde 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -237,12 +237,7 @@ "backupRestore_backupComplete": "Backup file created.", "backupRestore_restoreComplete": "Restore complete. Reconnect if you restored the radio identity.", "backupRestore_missingModelsTitle": "Models Not Downloaded", - "backupRestore_missingModelsMessage": "The restored settings select models that are not available on this device:\n{models}\n\nDownload them now?", - "@backupRestore_missingModelsMessage": { - "placeholders": { - "models": {"type": "String"} - } - }, + "backupRestore_missingModelsMessage": "The restored settings select models that are not on this device. Download them now?", "backupRestore_downloadModels": "Download Models", "backupRestore_downloading": "Downloading…", "backupRestore_cancelDownload": "Cancel Download", @@ -4341,5 +4336,26 @@ "chat_composerOffline": "Connect to a radio to send messages", "@chat_composerOffline": { "description": "Shown in place of the message box while no radio is connected" + }, + "modelDownload_notDownloaded": "Not downloaded", + "modelDownload_downloading": "Downloading", + "modelDownload_active": "Active", + "modelDownload_failed": "Couldn't download", + "modelDownload_incomplete": "Incomplete", + "modelDownload_verifying": "Verifying the download", + "modelDownload_useModel": "Use this model", + "modelDownload_removeFailed": "Couldn't remove the model: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)", + "@modelDownload_removeFailed": { + "placeholders": { + "error": {"type": "String"} + } + }, + "@modelDownload_progress": { + "placeholders": { + "current": {"type": "String"}, + "total": {"type": "String"}, + "percent": {"type": "String"} + } } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 1b0ddb11..17893440 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3942,7 +3942,7 @@ "backupRestore_backupComplete": "Archivo de copia de seguridad creado.", "backupRestore_restoreComplete": "Restauración completada. Reconecta si restauraste la identidad de la radio.", "backupRestore_missingModelsTitle": "Modelos no descargados", - "backupRestore_missingModelsMessage": "Los ajustes restaurados seleccionan modelos que no están disponibles en este dispositivo:\n{models}\n\n¿Descargarlos ahora?", + "backupRestore_missingModelsMessage": "Los ajustes restaurados seleccionan modelos que no están disponibles en este dispositivo. ¿Descargarlos ahora?", "backupRestore_downloadModels": "Descargar modelos", "backupRestore_downloading": "Descargando…", "backupRestore_cancelDownload": "Cancelar descarga", @@ -3962,5 +3962,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB o TCP", "connectSheet_stopReconnecting": "Dejar de reconectar", "connectSheet_reconnectFailed": "No se pudo conectar con {name}. Comprueba que esté encendida y cerca.", - "chat_composerOffline": "Conéctate a una radio para enviar mensajes" + "chat_composerOffline": "Conéctate a una radio para enviar mensajes", + "modelDownload_notDownloaded": "No descargado", + "modelDownload_downloading": "Descargando", + "modelDownload_active": "Activo", + "modelDownload_failed": "No se pudo descargar", + "modelDownload_incomplete": "Incompleto", + "modelDownload_verifying": "Comprobando la descarga", + "modelDownload_useModel": "Usar este modelo", + "modelDownload_removeFailed": "No se pudo quitar el modelo: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index de3c1be3..fb3a3cd2 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3890,7 +3890,7 @@ "backupRestore_backupComplete": "Fichier de sauvegarde créé.", "backupRestore_restoreComplete": "Restauration terminée. Reconnectez-vous si vous avez restauré l'identité de la radio.", "backupRestore_missingModelsTitle": "Modèles non téléchargés", - "backupRestore_missingModelsMessage": "Les réglages restaurés sélectionnent des modèles indisponibles sur cet appareil :\n{models}\n\nLes télécharger maintenant ?", + "backupRestore_missingModelsMessage": "Les réglages restaurés sélectionnent des modèles indisponibles sur cet appareil. Les télécharger maintenant ?", "backupRestore_downloadModels": "Télécharger les modèles", "backupRestore_downloading": "Téléchargement…", "backupRestore_cancelDownload": "Annuler le téléchargement", @@ -3910,5 +3910,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ou TCP", "connectSheet_stopReconnecting": "Arrêter la reconnexion", "connectSheet_reconnectFailed": "Impossible de joindre {name}. Vérifiez qu'elle est allumée et à proximité.", - "chat_composerOffline": "Connectez-vous à une radio pour envoyer des messages" + "chat_composerOffline": "Connectez-vous à une radio pour envoyer des messages", + "modelDownload_notDownloaded": "Non téléchargé", + "modelDownload_downloading": "Téléchargement", + "modelDownload_active": "Actif", + "modelDownload_failed": "Échec du téléchargement", + "modelDownload_incomplete": "Incomplet", + "modelDownload_verifying": "Vérification du téléchargement", + "modelDownload_useModel": "Utiliser ce modèle", + "modelDownload_removeFailed": "Impossible de retirer le modèle : {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index ba73a0d6..4d279f40 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3847,7 +3847,7 @@ "backupRestore_backupComplete": "A mentési fájl elkészült.", "backupRestore_restoreComplete": "A visszaállítás kész. Csatlakozzon újra, ha a rádió azonosítóját is visszaállította.", "backupRestore_missingModelsTitle": "A modellek nincsenek letöltve", - "backupRestore_missingModelsMessage": "A visszaállított beállítások olyan modelleket választanak, amelyek nem érhetők el ezen az eszközön:\n{models}\n\nLetölti őket most?", + "backupRestore_missingModelsMessage": "A visszaállított beállítások olyan modelleket választanak, amelyek nem érhetők el ezen az eszközön. Letölti őket most?", "backupRestore_downloadModels": "Modellek letöltése", "backupRestore_downloading": "Letöltés…", "backupRestore_cancelDownload": "Letöltés megszakítása", @@ -3867,5 +3867,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB vagy TCP", "connectSheet_stopReconnecting": "Újracsatlakozás leállítása", "connectSheet_reconnectFailed": "Nem érhető el: {name}. Ellenőrizze, hogy be van-e kapcsolva és a közelben van-e.", - "chat_composerOffline": "Üzenetküldéshez csatlakozzon rádióhoz" + "chat_composerOffline": "Üzenetküldéshez csatlakozzon rádióhoz", + "modelDownload_notDownloaded": "Nincs letöltve", + "modelDownload_downloading": "Letöltés", + "modelDownload_active": "Aktív", + "modelDownload_failed": "A letöltés sikertelen", + "modelDownload_incomplete": "Hiányos", + "modelDownload_verifying": "A letöltés ellenőrzése", + "modelDownload_useModel": "Ezt a modellt használja", + "modelDownload_removeFailed": "A modellt nem sikerült eltávolítani: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 8d6bd2ec..f23bd6ef 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3890,7 +3890,7 @@ "backupRestore_backupComplete": "File di backup creato.", "backupRestore_restoreComplete": "Ripristino completato. Riconnettiti se hai ripristinato l'identità della radio.", "backupRestore_missingModelsTitle": "Modelli non scaricati", - "backupRestore_missingModelsMessage": "Le impostazioni ripristinate selezionano modelli non disponibili su questo dispositivo:\n{models}\n\nScaricarli ora?", + "backupRestore_missingModelsMessage": "Le impostazioni ripristinate selezionano modelli non disponibili su questo dispositivo. Scaricarli ora?", "backupRestore_downloadModels": "Scarica modelli", "backupRestore_downloading": "Download in corso…", "backupRestore_cancelDownload": "Annulla download", @@ -3910,5 +3910,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB o TCP", "connectSheet_stopReconnecting": "Interrompi la riconnessione", "connectSheet_reconnectFailed": "Impossibile raggiungere {name}. Assicurati che sia acceso e nelle vicinanze.", - "chat_composerOffline": "Connettiti a una radio per inviare messaggi" + "chat_composerOffline": "Connettiti a una radio per inviare messaggi", + "modelDownload_notDownloaded": "Non scaricato", + "modelDownload_downloading": "Download in corso", + "modelDownload_active": "Attivo", + "modelDownload_failed": "Download non riuscito", + "modelDownload_incomplete": "Incompleto", + "modelDownload_verifying": "Verifica del download", + "modelDownload_useModel": "Usa questo modello", + "modelDownload_removeFailed": "Impossibile rimuovere il modello: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 0a3b8931..926d2f6a 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -4096,7 +4096,7 @@ "backupRestore_backupComplete": "バックアップファイルを作成しました。", "backupRestore_restoreComplete": "復元が完了しました。無線機のIDを復元した場合は再接続してください。", "backupRestore_missingModelsTitle": "モデル未ダウンロード", - "backupRestore_missingModelsMessage": "復元された設定で選択されているモデルが、このデバイスにありません:\n{models}\n\n今すぐダウンロードしますか?", + "backupRestore_missingModelsMessage": "復元された設定で選択されているモデルが、このデバイスにありません。今すぐダウンロードしますか?", "backupRestore_downloadModels": "モデルをダウンロード", "backupRestore_downloading": "ダウンロード中…", "backupRestore_cancelDownload": "ダウンロードをキャンセル", @@ -4116,5 +4116,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth、USB、またはTCP", "connectSheet_stopReconnecting": "再接続を停止", "connectSheet_reconnectFailed": "{name} に接続できませんでした。電源が入っていて近くにあることを確認してください。", - "chat_composerOffline": "メッセージを送信するには無線機に接続してください" + "chat_composerOffline": "メッセージを送信するには無線機に接続してください", + "modelDownload_notDownloaded": "未ダウンロード", + "modelDownload_downloading": "ダウンロード中", + "modelDownload_active": "使用中", + "modelDownload_failed": "ダウンロードできませんでした", + "modelDownload_incomplete": "未完了", + "modelDownload_verifying": "ダウンロードを確認しています", + "modelDownload_useModel": "このモデルを使う", + "modelDownload_removeFailed": "モデルを削除できませんでした: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index dcaf27a3..26567d26 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -4096,7 +4096,7 @@ "backupRestore_backupComplete": "백업 파일을 만들었습니다.", "backupRestore_restoreComplete": "복원이 완료되었습니다. 무전기 ID를 복원했다면 다시 연결하세요.", "backupRestore_missingModelsTitle": "모델이 다운로드되지 않음", - "backupRestore_missingModelsMessage": "복원된 설정에서 선택한 모델이 이 기기에 없습니다:\n{models}\n\n지금 다운로드할까요?", + "backupRestore_missingModelsMessage": "복원된 설정에서 선택한 모델이 이 기기에 없습니다. 지금 다운로드할까요?", "backupRestore_downloadModels": "모델 다운로드", "backupRestore_downloading": "다운로드 중…", "backupRestore_cancelDownload": "다운로드 취소", @@ -4116,5 +4116,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB 또는 TCP", "connectSheet_stopReconnecting": "재연결 중지", "connectSheet_reconnectFailed": "{name}에 연결할 수 없습니다. 전원이 켜져 있고 가까이 있는지 확인하세요.", - "chat_composerOffline": "메시지를 보내려면 무전기에 연결하세요" + "chat_composerOffline": "메시지를 보내려면 무전기에 연결하세요", + "modelDownload_notDownloaded": "다운로드되지 않음", + "modelDownload_downloading": "다운로드 중", + "modelDownload_active": "사용 중", + "modelDownload_failed": "다운로드하지 못했습니다", + "modelDownload_incomplete": "불완전", + "modelDownload_verifying": "다운로드를 확인하는 중", + "modelDownload_useModel": "이 모델 사용", + "modelDownload_removeFailed": "모델을 제거하지 못했습니다: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..49389905 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1102,8 +1102,8 @@ abstract class AppLocalizations { /// No description provided for @backupRestore_missingModelsMessage. /// /// In en, this message translates to: - /// **'The restored settings select models that are not available on this device:\n{models}\n\nDownload them now?'** - String backupRestore_missingModelsMessage(String models); + /// **'The restored settings select models that are not on this device. Download them now?'** + String get backupRestore_missingModelsMessage; /// No description provided for @backupRestore_downloadModels. /// @@ -12633,6 +12633,60 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Connect to a radio to send messages'** String get chat_composerOffline; + + /// No description provided for @modelDownload_notDownloaded. + /// + /// In en, this message translates to: + /// **'Not downloaded'** + String get modelDownload_notDownloaded; + + /// No description provided for @modelDownload_downloading. + /// + /// In en, this message translates to: + /// **'Downloading'** + String get modelDownload_downloading; + + /// No description provided for @modelDownload_active. + /// + /// In en, this message translates to: + /// **'Active'** + String get modelDownload_active; + + /// No description provided for @modelDownload_failed. + /// + /// In en, this message translates to: + /// **'Couldn\'t download'** + String get modelDownload_failed; + + /// No description provided for @modelDownload_incomplete. + /// + /// In en, this message translates to: + /// **'Incomplete'** + String get modelDownload_incomplete; + + /// No description provided for @modelDownload_verifying. + /// + /// In en, this message translates to: + /// **'Verifying the download'** + String get modelDownload_verifying; + + /// No description provided for @modelDownload_useModel. + /// + /// In en, this message translates to: + /// **'Use this model'** + String get modelDownload_useModel; + + /// No description provided for @modelDownload_removeFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t remove the model: {error}'** + String modelDownload_removeFailed(String error); + + /// No description provided for @modelDownload_progress. + /// + /// In en, this message translates to: + /// **'{current} / {total} MB ({percent}%)'** + String modelDownload_progress(String current, String total, String percent); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..f500aa6a 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -557,9 +557,8 @@ class AppLocalizationsBg extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Моделите не са изтеглени'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Възстановените настройки избират модели, които не са налични на това устройство:\n$models\n\nДа се изтеглят ли сега?'; - } + String get backupRestore_missingModelsMessage => + 'Възстановените настройки избират модели, които не са налични на това устройство. Да се изтеглят ли сега?'; @override String get backupRestore_downloadModels => 'Изтегли модели'; @@ -7582,4 +7581,35 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_composerOffline => 'Свържете се с радио, за да изпращате съобщения'; + + @override + String get modelDownload_notDownloaded => 'Не е изтеглен'; + + @override + String get modelDownload_downloading => 'Изтегляне'; + + @override + String get modelDownload_active => 'Активен'; + + @override + String get modelDownload_failed => 'Неуспешно изтегляне'; + + @override + String get modelDownload_incomplete => 'Непълен'; + + @override + String get modelDownload_verifying => 'Проверка на изтеглянето'; + + @override + String get modelDownload_useModel => 'Използвай този модел'; + + @override + String modelDownload_removeFailed(String error) { + return 'Моделът не можа да бъде премахнат: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..9f813b1e 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -551,9 +551,8 @@ class AppLocalizationsCs extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modely nejsou stažené'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Obnovené nastavení vybírá modely, které nejsou v tomto zařízení k dispozici:\n$models\n\nStáhnout je nyní?'; - } + String get backupRestore_missingModelsMessage => + 'Obnovené nastavení vybírá modely, které nejsou v tomto zařízení k dispozici. Stáhnout je nyní?'; @override String get backupRestore_downloadModels => 'Stáhnout modely'; @@ -7552,4 +7551,35 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chat_composerOffline => 'Pro odesílání zpráv se připojte k rádiu'; + + @override + String get modelDownload_notDownloaded => 'Nestaženo'; + + @override + String get modelDownload_downloading => 'Stahování'; + + @override + String get modelDownload_active => 'Aktivní'; + + @override + String get modelDownload_failed => 'Stažení se nezdařilo'; + + @override + String get modelDownload_incomplete => 'Neúplné'; + + @override + String get modelDownload_verifying => 'Ověřování stažení'; + + @override + String get modelDownload_useModel => 'Použít tento model'; + + @override + String modelDownload_removeFailed(String error) { + return 'Model se nepodařilo odebrat: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..882f2740 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -559,9 +559,8 @@ class AppLocalizationsDe extends AppLocalizations { 'Modelle nicht heruntergeladen'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Die wiederhergestellten Einstellungen wählen Modelle aus, die auf diesem Gerät nicht verfügbar sind:\n$models\n\nJetzt herunterladen?'; - } + String get backupRestore_missingModelsMessage => + 'Die wiederhergestellten Einstellungen wählen Modelle aus, die auf diesem Gerät nicht verfügbar sind. Jetzt herunterladen?'; @override String get backupRestore_downloadModels => 'Modelle herunterladen'; @@ -7597,4 +7596,35 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_composerOffline => 'Mit einem Funkgerät verbinden, um Nachrichten zu senden'; + + @override + String get modelDownload_notDownloaded => 'Nicht heruntergeladen'; + + @override + String get modelDownload_downloading => 'Wird heruntergeladen'; + + @override + String get modelDownload_active => 'Aktiv'; + + @override + String get modelDownload_failed => 'Download fehlgeschlagen'; + + @override + String get modelDownload_incomplete => 'Unvollständig'; + + @override + String get modelDownload_verifying => 'Download wird geprüft'; + + @override + String get modelDownload_useModel => 'Dieses Modell verwenden'; + + @override + String modelDownload_removeFailed(String error) { + return 'Das Modell konnte nicht entfernt werden: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..d46c8fa6 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -547,9 +547,8 @@ class AppLocalizationsEn extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Models Not Downloaded'; @override - String backupRestore_missingModelsMessage(String models) { - return 'The restored settings select models that are not available on this device:\n$models\n\nDownload them now?'; - } + String get backupRestore_missingModelsMessage => + 'The restored settings select models that are not on this device. Download them now?'; @override String get backupRestore_downloadModels => 'Download Models'; @@ -7468,4 +7467,35 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_composerOffline => 'Connect to a radio to send messages'; + + @override + String get modelDownload_notDownloaded => 'Not downloaded'; + + @override + String get modelDownload_downloading => 'Downloading'; + + @override + String get modelDownload_active => 'Active'; + + @override + String get modelDownload_failed => 'Couldn\'t download'; + + @override + String get modelDownload_incomplete => 'Incomplete'; + + @override + String get modelDownload_verifying => 'Verifying the download'; + + @override + String get modelDownload_useModel => 'Use this model'; + + @override + String modelDownload_removeFailed(String error) { + return 'Couldn\'t remove the model: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..67112b9d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -557,9 +557,8 @@ class AppLocalizationsEs extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modelos no descargados'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Los ajustes restaurados seleccionan modelos que no están disponibles en este dispositivo:\n$models\n\n¿Descargarlos ahora?'; - } + String get backupRestore_missingModelsMessage => + 'Los ajustes restaurados seleccionan modelos que no están disponibles en este dispositivo. ¿Descargarlos ahora?'; @override String get backupRestore_downloadModels => 'Descargar modelos'; @@ -7573,4 +7572,35 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_composerOffline => 'Conéctate a una radio para enviar mensajes'; + + @override + String get modelDownload_notDownloaded => 'No descargado'; + + @override + String get modelDownload_downloading => 'Descargando'; + + @override + String get modelDownload_active => 'Activo'; + + @override + String get modelDownload_failed => 'No se pudo descargar'; + + @override + String get modelDownload_incomplete => 'Incompleto'; + + @override + String get modelDownload_verifying => 'Comprobando la descarga'; + + @override + String get modelDownload_useModel => 'Usar este modelo'; + + @override + String modelDownload_removeFailed(String error) { + return 'No se pudo quitar el modelo: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..e18b6375 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -556,9 +556,8 @@ class AppLocalizationsFr extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modèles non téléchargés'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Les réglages restaurés sélectionnent des modèles indisponibles sur cet appareil :\n$models\n\nLes télécharger maintenant ?'; - } + String get backupRestore_missingModelsMessage => + 'Les réglages restaurés sélectionnent des modèles indisponibles sur cet appareil. Les télécharger maintenant ?'; @override String get backupRestore_downloadModels => 'Télécharger les modèles'; @@ -7602,4 +7601,35 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_composerOffline => 'Connectez-vous à une radio pour envoyer des messages'; + + @override + String get modelDownload_notDownloaded => 'Non téléchargé'; + + @override + String get modelDownload_downloading => 'Téléchargement'; + + @override + String get modelDownload_active => 'Actif'; + + @override + String get modelDownload_failed => 'Échec du téléchargement'; + + @override + String get modelDownload_incomplete => 'Incomplet'; + + @override + String get modelDownload_verifying => 'Vérification du téléchargement'; + + @override + String get modelDownload_useModel => 'Utiliser ce modèle'; + + @override + String modelDownload_removeFailed(String error) { + return 'Impossible de retirer le modèle : $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..a738147f 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -552,9 +552,8 @@ class AppLocalizationsHu extends AppLocalizations { 'A modellek nincsenek letöltve'; @override - String backupRestore_missingModelsMessage(String models) { - return 'A visszaállított beállítások olyan modelleket választanak, amelyek nem érhetők el ezen az eszközön:\n$models\n\nLetölti őket most?'; - } + String get backupRestore_missingModelsMessage => + 'A visszaállított beállítások olyan modelleket választanak, amelyek nem érhetők el ezen az eszközön. Letölti őket most?'; @override String get backupRestore_downloadModels => 'Modellek letöltése'; @@ -7565,4 +7564,35 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_composerOffline => 'Üzenetküldéshez csatlakozzon rádióhoz'; + + @override + String get modelDownload_notDownloaded => 'Nincs letöltve'; + + @override + String get modelDownload_downloading => 'Letöltés'; + + @override + String get modelDownload_active => 'Aktív'; + + @override + String get modelDownload_failed => 'A letöltés sikertelen'; + + @override + String get modelDownload_incomplete => 'Hiányos'; + + @override + String get modelDownload_verifying => 'A letöltés ellenőrzése'; + + @override + String get modelDownload_useModel => 'Ezt a modellt használja'; + + @override + String modelDownload_removeFailed(String error) { + return 'A modellt nem sikerült eltávolítani: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..d498db18 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -556,9 +556,8 @@ class AppLocalizationsIt extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modelli non scaricati'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Le impostazioni ripristinate selezionano modelli non disponibili su questo dispositivo:\n$models\n\nScaricarli ora?'; - } + String get backupRestore_missingModelsMessage => + 'Le impostazioni ripristinate selezionano modelli non disponibili su questo dispositivo. Scaricarli ora?'; @override String get backupRestore_downloadModels => 'Scarica modelli'; @@ -7585,4 +7584,35 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_composerOffline => 'Connettiti a una radio per inviare messaggi'; + + @override + String get modelDownload_notDownloaded => 'Non scaricato'; + + @override + String get modelDownload_downloading => 'Download in corso'; + + @override + String get modelDownload_active => 'Attivo'; + + @override + String get modelDownload_failed => 'Download non riuscito'; + + @override + String get modelDownload_incomplete => 'Incompleto'; + + @override + String get modelDownload_verifying => 'Verifica del download'; + + @override + String get modelDownload_useModel => 'Usa questo modello'; + + @override + String modelDownload_removeFailed(String error) { + return 'Impossibile rimuovere il modello: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..6084fd6a 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -531,9 +531,8 @@ class AppLocalizationsJa extends AppLocalizations { String get backupRestore_missingModelsTitle => 'モデル未ダウンロード'; @override - String backupRestore_missingModelsMessage(String models) { - return '復元された設定で選択されているモデルが、このデバイスにありません:\n$models\n\n今すぐダウンロードしますか?'; - } + String get backupRestore_missingModelsMessage => + '復元された設定で選択されているモデルが、このデバイスにありません。今すぐダウンロードしますか?'; @override String get backupRestore_downloadModels => 'モデルをダウンロード'; @@ -7227,4 +7226,35 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_composerOffline => 'メッセージを送信するには無線機に接続してください'; + + @override + String get modelDownload_notDownloaded => '未ダウンロード'; + + @override + String get modelDownload_downloading => 'ダウンロード中'; + + @override + String get modelDownload_active => '使用中'; + + @override + String get modelDownload_failed => 'ダウンロードできませんでした'; + + @override + String get modelDownload_incomplete => '未完了'; + + @override + String get modelDownload_verifying => 'ダウンロードを確認しています'; + + @override + String get modelDownload_useModel => 'このモデルを使う'; + + @override + String modelDownload_removeFailed(String error) { + return 'モデルを削除できませんでした: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..169fa074 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -531,9 +531,8 @@ class AppLocalizationsKo extends AppLocalizations { String get backupRestore_missingModelsTitle => '모델이 다운로드되지 않음'; @override - String backupRestore_missingModelsMessage(String models) { - return '복원된 설정에서 선택한 모델이 이 기기에 없습니다:\n$models\n\n지금 다운로드할까요?'; - } + String get backupRestore_missingModelsMessage => + '복원된 설정에서 선택한 모델이 이 기기에 없습니다. 지금 다운로드할까요?'; @override String get backupRestore_downloadModels => '모델 다운로드'; @@ -7240,4 +7239,35 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_composerOffline => '메시지를 보내려면 무전기에 연결하세요'; + + @override + String get modelDownload_notDownloaded => '다운로드되지 않음'; + + @override + String get modelDownload_downloading => '다운로드 중'; + + @override + String get modelDownload_active => '사용 중'; + + @override + String get modelDownload_failed => '다운로드하지 못했습니다'; + + @override + String get modelDownload_incomplete => '불완전'; + + @override + String get modelDownload_verifying => '다운로드를 확인하는 중'; + + @override + String get modelDownload_useModel => '이 모델 사용'; + + @override + String modelDownload_removeFailed(String error) { + return '모델을 제거하지 못했습니다: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..22ea472a 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -552,9 +552,8 @@ class AppLocalizationsNl extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modellen niet gedownload'; @override - String backupRestore_missingModelsMessage(String models) { - return 'De herstelde instellingen selecteren modellen die op dit apparaat niet beschikbaar zijn:\n$models\n\nNu downloaden?'; - } + String get backupRestore_missingModelsMessage => + 'De herstelde instellingen selecteren modellen die op dit apparaat niet beschikbaar zijn. Nu downloaden?'; @override String get backupRestore_downloadModels => 'Modellen downloaden'; @@ -7541,4 +7540,35 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_composerOffline => 'Verbind met een radio om berichten te versturen'; + + @override + String get modelDownload_notDownloaded => 'Niet gedownload'; + + @override + String get modelDownload_downloading => 'Downloaden'; + + @override + String get modelDownload_active => 'Actief'; + + @override + String get modelDownload_failed => 'Downloaden mislukt'; + + @override + String get modelDownload_incomplete => 'Onvolledig'; + + @override + String get modelDownload_verifying => 'Download controleren'; + + @override + String get modelDownload_useModel => 'Dit model gebruiken'; + + @override + String modelDownload_removeFailed(String error) { + return 'Het model kon niet worden verwijderd: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..077362d4 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -560,9 +560,8 @@ class AppLocalizationsPl extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modele nie zostały pobrane'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Przywrócone ustawienia wybierają modele, które nie są dostępne na tym urządzeniu:\n$models\n\nPobrać je teraz?'; - } + String get backupRestore_missingModelsMessage => + 'Przywrócone ustawienia wybierają modele, które nie są dostępne na tym urządzeniu. Pobrać je teraz?'; @override String get backupRestore_downloadModels => 'Pobierz modele'; @@ -7619,4 +7618,35 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_composerOffline => 'Połącz się z radiem, aby wysyłać wiadomości'; + + @override + String get modelDownload_notDownloaded => 'Nie pobrano'; + + @override + String get modelDownload_downloading => 'Pobieranie'; + + @override + String get modelDownload_active => 'Aktywny'; + + @override + String get modelDownload_failed => 'Nie udało się pobrać'; + + @override + String get modelDownload_incomplete => 'Niekompletny'; + + @override + String get modelDownload_verifying => 'Sprawdzanie pobierania'; + + @override + String get modelDownload_useModel => 'Użyj tego modelu'; + + @override + String modelDownload_removeFailed(String error) { + return 'Nie udało się usunąć modelu: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..65b872a8 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -557,9 +557,8 @@ class AppLocalizationsPt extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modelos não baixados'; @override - String backupRestore_missingModelsMessage(String models) { - return 'As configurações restauradas selecionam modelos que não estão disponíveis neste dispositivo:\n$models\n\nBaixar agora?'; - } + String get backupRestore_missingModelsMessage => + 'As configurações restauradas selecionam modelos que não estão disponíveis neste dispositivo. Baixar agora?'; @override String get backupRestore_downloadModels => 'Baixar modelos'; @@ -7563,6 +7562,37 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_composerOffline => 'Conecte-se a um rádio para enviar mensagens'; + + @override + String get modelDownload_notDownloaded => 'Não baixado'; + + @override + String get modelDownload_downloading => 'Baixando'; + + @override + String get modelDownload_active => 'Ativo'; + + @override + String get modelDownload_failed => 'Não foi possível baixar'; + + @override + String get modelDownload_incomplete => 'Incompleto'; + + @override + String get modelDownload_verifying => 'Verificando o download'; + + @override + String get modelDownload_useModel => 'Usar este modelo'; + + @override + String modelDownload_removeFailed(String error) { + return 'Não foi possível remover o modelo: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } /// The translations for Portuguese, as used in Portugal (`pt_PT`). @@ -8112,9 +8142,8 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { String get backupRestore_missingModelsTitle => 'Modelos não transferidos'; @override - String backupRestore_missingModelsMessage(String models) { - return 'As definições restauradas selecionam modelos que não estão disponíveis neste dispositivo:\n$models\n\nTransferi-los agora?'; - } + String get backupRestore_missingModelsMessage => + 'As definições restauradas selecionam modelos que não estão disponíveis neste dispositivo. Transferi-los agora?'; @override String get backupRestore_downloadModels => 'Transferir modelos'; @@ -15015,4 +15044,35 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get chat_composerOffline => 'Ligue-se a um rádio para enviar mensagens'; + + @override + String get modelDownload_notDownloaded => 'Não transferido'; + + @override + String get modelDownload_downloading => 'A transferir'; + + @override + String get modelDownload_active => 'Ativo'; + + @override + String get modelDownload_failed => 'Não foi possível transferir'; + + @override + String get modelDownload_incomplete => 'Incompleto'; + + @override + String get modelDownload_verifying => 'A verificar a transferência'; + + @override + String get modelDownload_useModel => 'Utilizar este modelo'; + + @override + String modelDownload_removeFailed(String error) { + return 'Não foi possível remover o modelo: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..253fcc4a 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -554,9 +554,8 @@ class AppLocalizationsRu extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Модели не загружены'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Восстановленные настройки выбирают модели, которых нет на этом устройстве:\n$models\n\nЗагрузить их сейчас?'; - } + String get backupRestore_missingModelsMessage => + 'Восстановленные настройки выбирают модели, которых нет на этом устройстве. Загрузить их сейчас?'; @override String get backupRestore_downloadModels => 'Загрузить модели'; @@ -7599,4 +7598,35 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_composerOffline => 'Подключитесь к радио, чтобы отправлять сообщения'; + + @override + String get modelDownload_notDownloaded => 'Не скачано'; + + @override + String get modelDownload_downloading => 'Загрузка'; + + @override + String get modelDownload_active => 'Активна'; + + @override + String get modelDownload_failed => 'Не удалось скачать'; + + @override + String get modelDownload_incomplete => 'Неполная'; + + @override + String get modelDownload_verifying => 'Проверка загрузки'; + + @override + String get modelDownload_useModel => 'Использовать эту модель'; + + @override + String modelDownload_removeFailed(String error) { + return 'Не удалось удалить модель: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..c6e2170b 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -555,9 +555,8 @@ class AppLocalizationsSk extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modely nie sú stiahnuté'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Obnovené nastavenia vyberajú modely, ktoré nie sú v tomto zariadení k dispozícii:\n$models\n\nStiahnuť ich teraz?'; - } + String get backupRestore_missingModelsMessage => + 'Obnovené nastavenia vyberajú modely, ktoré nie sú v tomto zariadení k dispozícii. Stiahnuť ich teraz?'; @override String get backupRestore_downloadModels => 'Stiahnuť modely'; @@ -7564,4 +7563,35 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_composerOffline => 'Na odosielanie správ sa pripojte k rádiu'; + + @override + String get modelDownload_notDownloaded => 'Nestiahnuté'; + + @override + String get modelDownload_downloading => 'Sťahovanie'; + + @override + String get modelDownload_active => 'Aktívny'; + + @override + String get modelDownload_failed => 'Sťahovanie zlyhalo'; + + @override + String get modelDownload_incomplete => 'Nekompletné'; + + @override + String get modelDownload_verifying => 'Overuje sa sťahovanie'; + + @override + String get modelDownload_useModel => 'Použiť tento model'; + + @override + String modelDownload_removeFailed(String error) { + return 'Model sa nepodarilo odstrániť: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..1981b559 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -554,9 +554,8 @@ class AppLocalizationsSl extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modeli niso preneseni'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Obnovljene nastavitve izbirajo modele, ki niso na voljo v tej napravi:\n$models\n\nJih želite prenesti zdaj?'; - } + String get backupRestore_missingModelsMessage => + 'Obnovljene nastavitve izbirajo modele, ki niso na voljo v tej napravi. Jih želite prenesti zdaj?'; @override String get backupRestore_downloadModels => 'Prenesi modele'; @@ -7558,4 +7557,35 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_composerOffline => 'Za pošiljanje sporočil se povežite z radiem'; + + @override + String get modelDownload_notDownloaded => 'Ni preneseno'; + + @override + String get modelDownload_downloading => 'Prenašanje'; + + @override + String get modelDownload_active => 'Aktiven'; + + @override + String get modelDownload_failed => 'Prenos ni uspel'; + + @override + String get modelDownload_incomplete => 'Nepopolno'; + + @override + String get modelDownload_verifying => 'Preverjanje prenosa'; + + @override + String get modelDownload_useModel => 'Uporabi ta model'; + + @override + String modelDownload_removeFailed(String error) { + return 'Modela ni bilo mogoče odstraniti: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..b64474ed 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -553,9 +553,8 @@ class AppLocalizationsSv extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Modeller inte nedladdade'; @override - String backupRestore_missingModelsMessage(String models) { - return 'De återställda inställningarna väljer modeller som inte finns på den här enheten:\n$models\n\nLadda ned dem nu?'; - } + String get backupRestore_missingModelsMessage => + 'De återställda inställningarna väljer modeller som inte finns på den här enheten. Ladda ned dem nu?'; @override String get backupRestore_downloadModels => 'Ladda ned modeller'; @@ -7518,4 +7517,35 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_composerOffline => 'Anslut till en radio för att skicka meddelanden'; + + @override + String get modelDownload_notDownloaded => 'Inte nedladdad'; + + @override + String get modelDownload_downloading => 'Laddar ner'; + + @override + String get modelDownload_active => 'Aktiv'; + + @override + String get modelDownload_failed => 'Kunde inte ladda ner'; + + @override + String get modelDownload_incomplete => 'Ofullständig'; + + @override + String get modelDownload_verifying => 'Verifierar nedladdningen'; + + @override + String get modelDownload_useModel => 'Använd den här modellen'; + + @override + String modelDownload_removeFailed(String error) { + return 'Det gick inte att ta bort modellen: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..d8a201eb 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -553,9 +553,8 @@ class AppLocalizationsUk extends AppLocalizations { String get backupRestore_missingModelsTitle => 'Моделі не завантажено'; @override - String backupRestore_missingModelsMessage(String models) { - return 'Відновлені налаштування вибирають моделі, яких немає на цьому пристрої:\n$models\n\nЗавантажити їх зараз?'; - } + String get backupRestore_missingModelsMessage => + 'Відновлені налаштування вибирають моделі, яких немає на цьому пристрої. Завантажити їх зараз?'; @override String get backupRestore_downloadModels => 'Завантажити моделі'; @@ -7611,4 +7610,35 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_composerOffline => 'Підключіться до радіо, щоб надсилати повідомлення'; + + @override + String get modelDownload_notDownloaded => 'Не завантажено'; + + @override + String get modelDownload_downloading => 'Завантаження'; + + @override + String get modelDownload_active => 'Активна'; + + @override + String get modelDownload_failed => 'Не вдалося завантажити'; + + @override + String get modelDownload_incomplete => 'Неповна'; + + @override + String get modelDownload_verifying => 'Перевірка завантаження'; + + @override + String get modelDownload_useModel => 'Використовувати цю модель'; + + @override + String modelDownload_removeFailed(String error) { + return 'Не вдалося видалити модель: $error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..813bb0e6 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -520,9 +520,7 @@ class AppLocalizationsZh extends AppLocalizations { String get backupRestore_missingModelsTitle => '模型未下载'; @override - String backupRestore_missingModelsMessage(String models) { - return '恢复的设置所选用的模型在此设备上不可用:\n$models\n\n现在下载吗?'; - } + String get backupRestore_missingModelsMessage => '恢复的设置所选用的模型在此设备上不可用。现在下载吗?'; @override String get backupRestore_downloadModels => '下载模型'; @@ -7070,4 +7068,35 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_composerOffline => '连接到无线电后才能发送消息'; + + @override + String get modelDownload_notDownloaded => '未下载'; + + @override + String get modelDownload_downloading => '正在下载'; + + @override + String get modelDownload_active => '当前使用'; + + @override + String get modelDownload_failed => '下载失败'; + + @override + String get modelDownload_incomplete => '不完整'; + + @override + String get modelDownload_verifying => '正在校验下载'; + + @override + String get modelDownload_useModel => '使用此模型'; + + @override + String modelDownload_removeFailed(String error) { + return '无法移除模型:$error'; + } + + @override + String modelDownload_progress(String current, String total, String percent) { + return '$current / $total MB ($percent%)'; + } } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 2f192869..e042f095 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -3657,7 +3657,7 @@ "backupRestore_backupComplete": "Back-upbestand gemaakt.", "backupRestore_restoreComplete": "Herstel voltooid. Verbind opnieuw als je de radio-identiteit hebt hersteld.", "backupRestore_missingModelsTitle": "Modellen niet gedownload", - "backupRestore_missingModelsMessage": "De herstelde instellingen selecteren modellen die op dit apparaat niet beschikbaar zijn:\n{models}\n\nNu downloaden?", + "backupRestore_missingModelsMessage": "De herstelde instellingen selecteren modellen die op dit apparaat niet beschikbaar zijn. Nu downloaden?", "backupRestore_downloadModels": "Modellen downloaden", "backupRestore_downloading": "Downloaden…", "backupRestore_cancelDownload": "Download annuleren", @@ -3677,5 +3677,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB of TCP", "connectSheet_stopReconnecting": "Opnieuw verbinden stoppen", "connectSheet_reconnectFailed": "Kan {name} niet bereiken. Controleer of het aan staat en in de buurt is.", - "chat_composerOffline": "Verbind met een radio om berichten te versturen" + "chat_composerOffline": "Verbind met een radio om berichten te versturen", + "modelDownload_notDownloaded": "Niet gedownload", + "modelDownload_downloading": "Downloaden", + "modelDownload_active": "Actief", + "modelDownload_failed": "Downloaden mislukt", + "modelDownload_incomplete": "Onvolledig", + "modelDownload_verifying": "Download controleren", + "modelDownload_useModel": "Dit model gebruiken", + "modelDownload_removeFailed": "Het model kon niet worden verwijderd: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index af3783a1..2f17da61 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3995,7 +3995,7 @@ "backupRestore_backupComplete": "Plik kopii zapasowej został utworzony.", "backupRestore_restoreComplete": "Przywracanie zakończone. Połącz się ponownie, jeśli przywrócono tożsamość radia.", "backupRestore_missingModelsTitle": "Modele nie zostały pobrane", - "backupRestore_missingModelsMessage": "Przywrócone ustawienia wybierają modele, które nie są dostępne na tym urządzeniu:\n{models}\n\nPobrać je teraz?", + "backupRestore_missingModelsMessage": "Przywrócone ustawienia wybierają modele, które nie są dostępne na tym urządzeniu. Pobrać je teraz?", "backupRestore_downloadModels": "Pobierz modele", "backupRestore_downloading": "Pobieranie…", "backupRestore_cancelDownload": "Anuluj pobieranie", @@ -4015,5 +4015,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB lub TCP", "connectSheet_stopReconnecting": "Zatrzymaj ponowne łączenie", "connectSheet_reconnectFailed": "Nie można połączyć z {name}. Upewnij się, że jest włączone i w pobliżu.", - "chat_composerOffline": "Połącz się z radiem, aby wysyłać wiadomości" + "chat_composerOffline": "Połącz się z radiem, aby wysyłać wiadomości", + "modelDownload_notDownloaded": "Nie pobrano", + "modelDownload_downloading": "Pobieranie", + "modelDownload_active": "Aktywny", + "modelDownload_failed": "Nie udało się pobrać", + "modelDownload_incomplete": "Niekompletny", + "modelDownload_verifying": "Sprawdzanie pobierania", + "modelDownload_useModel": "Użyj tego modelu", + "modelDownload_removeFailed": "Nie udało się usunąć modelu: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index ad24e07a..c8290e33 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3808,7 +3808,7 @@ "backupRestore_backupComplete": "Arquivo de backup criado.", "backupRestore_restoreComplete": "Restauração concluída. Reconecte se você restaurou a identidade do rádio.", "backupRestore_missingModelsTitle": "Modelos não baixados", - "backupRestore_missingModelsMessage": "As configurações restauradas selecionam modelos que não estão disponíveis neste dispositivo:\n{models}\n\nBaixar agora?", + "backupRestore_missingModelsMessage": "As configurações restauradas selecionam modelos que não estão disponíveis neste dispositivo. Baixar agora?", "backupRestore_downloadModels": "Baixar modelos", "backupRestore_downloading": "Baixando…", "backupRestore_cancelDownload": "Cancelar download", @@ -3828,5 +3828,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ou TCP", "connectSheet_stopReconnecting": "Parar de reconectar", "connectSheet_reconnectFailed": "Não foi possível alcançar {name}. Verifique se está ligado e por perto.", - "chat_composerOffline": "Conecte-se a um rádio para enviar mensagens" + "chat_composerOffline": "Conecte-se a um rádio para enviar mensagens", + "modelDownload_notDownloaded": "Não baixado", + "modelDownload_downloading": "Baixando", + "modelDownload_active": "Ativo", + "modelDownload_failed": "Não foi possível baixar", + "modelDownload_incomplete": "Incompleto", + "modelDownload_verifying": "Verificando o download", + "modelDownload_useModel": "Usar este modelo", + "modelDownload_removeFailed": "Não foi possível remover o modelo: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_pt_PT.arb b/lib/l10n/app_pt_PT.arb index 80218599..727d5453 100644 --- a/lib/l10n/app_pt_PT.arb +++ b/lib/l10n/app_pt_PT.arb @@ -160,7 +160,7 @@ "backupRestore_backupComplete": "Ficheiro de cópia criado.", "backupRestore_restoreComplete": "Restauro concluído. Volte a ligar se restaurou a identidade do rádio.", "backupRestore_missingModelsTitle": "Modelos não transferidos", - "backupRestore_missingModelsMessage": "As definições restauradas selecionam modelos que não estão disponíveis neste dispositivo:\n{models}\n\nTransferi-los agora?", + "backupRestore_missingModelsMessage": "As definições restauradas selecionam modelos que não estão disponíveis neste dispositivo. Transferi-los agora?", "backupRestore_downloadModels": "Transferir modelos", "backupRestore_downloading": "A transferir…", "backupRestore_cancelDownload": "Cancelar transferência", @@ -2055,5 +2055,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ou TCP", "connectSheet_stopReconnecting": "Parar de religar", "connectSheet_reconnectFailed": "Não foi possível contactar {name}. Verifique se está ligado e por perto.", - "chat_composerOffline": "Ligue-se a um rádio para enviar mensagens" + "chat_composerOffline": "Ligue-se a um rádio para enviar mensagens", + "modelDownload_notDownloaded": "Não transferido", + "modelDownload_downloading": "A transferir", + "modelDownload_active": "Ativo", + "modelDownload_failed": "Não foi possível transferir", + "modelDownload_incomplete": "Incompleto", + "modelDownload_verifying": "A verificar a transferência", + "modelDownload_useModel": "Utilizar este modelo", + "modelDownload_removeFailed": "Não foi possível remover o modelo: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index f5ff336c..e373cc42 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -3053,7 +3053,7 @@ "backupRestore_backupComplete": "Файл резервной копии создан.", "backupRestore_restoreComplete": "Восстановление завершено. Переподключитесь, если вы восстановили идентификатор радио.", "backupRestore_missingModelsTitle": "Модели не загружены", - "backupRestore_missingModelsMessage": "Восстановленные настройки выбирают модели, которых нет на этом устройстве:\n{models}\n\nЗагрузить их сейчас?", + "backupRestore_missingModelsMessage": "Восстановленные настройки выбирают модели, которых нет на этом устройстве. Загрузить их сейчас?", "backupRestore_downloadModels": "Загрузить модели", "backupRestore_downloading": "Загрузка…", "backupRestore_cancelDownload": "Отменить загрузку", @@ -3073,5 +3073,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB или TCP", "connectSheet_stopReconnecting": "Остановить переподключение", "connectSheet_reconnectFailed": "Не удалось связаться с {name}. Убедитесь, что оно включено и находится рядом.", - "chat_composerOffline": "Подключитесь к радио, чтобы отправлять сообщения" + "chat_composerOffline": "Подключитесь к радио, чтобы отправлять сообщения", + "modelDownload_notDownloaded": "Не скачано", + "modelDownload_downloading": "Загрузка", + "modelDownload_active": "Активна", + "modelDownload_failed": "Не удалось скачать", + "modelDownload_incomplete": "Неполная", + "modelDownload_verifying": "Проверка загрузки", + "modelDownload_useModel": "Использовать эту модель", + "modelDownload_removeFailed": "Не удалось удалить модель: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index c582c8f4..9c99b28d 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3809,7 +3809,7 @@ "backupRestore_backupComplete": "Súbor zálohy bol vytvorený.", "backupRestore_restoreComplete": "Obnovenie dokončené. Ak ste obnovili identitu rádia, pripojte sa znova.", "backupRestore_missingModelsTitle": "Modely nie sú stiahnuté", - "backupRestore_missingModelsMessage": "Obnovené nastavenia vyberajú modely, ktoré nie sú v tomto zariadení k dispozícii:\n{models}\n\nStiahnuť ich teraz?", + "backupRestore_missingModelsMessage": "Obnovené nastavenia vyberajú modely, ktoré nie sú v tomto zariadení k dispozícii. Stiahnuť ich teraz?", "backupRestore_downloadModels": "Stiahnuť modely", "backupRestore_downloading": "Sťahovanie…", "backupRestore_cancelDownload": "Zrušiť sťahovanie", @@ -3829,5 +3829,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB alebo TCP", "connectSheet_stopReconnecting": "Zastaviť pripájanie", "connectSheet_reconnectFailed": "Nedá sa spojiť s {name}. Uistite sa, že je zapnuté a nablízku.", - "chat_composerOffline": "Na odosielanie správ sa pripojte k rádiu" + "chat_composerOffline": "Na odosielanie správ sa pripojte k rádiu", + "modelDownload_notDownloaded": "Nestiahnuté", + "modelDownload_downloading": "Sťahovanie", + "modelDownload_active": "Aktívny", + "modelDownload_failed": "Sťahovanie zlyhalo", + "modelDownload_incomplete": "Nekompletné", + "modelDownload_verifying": "Overuje sa sťahovanie", + "modelDownload_useModel": "Použiť tento model", + "modelDownload_removeFailed": "Model sa nepodarilo odstrániť: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 3dcbeb94..066e800a 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3963,7 +3963,7 @@ "backupRestore_backupComplete": "Datoteka varnostne kopije je ustvarjena.", "backupRestore_restoreComplete": "Obnovitev je končana. Če ste obnovili identiteto radia, se znova povežite.", "backupRestore_missingModelsTitle": "Modeli niso preneseni", - "backupRestore_missingModelsMessage": "Obnovljene nastavitve izbirajo modele, ki niso na voljo v tej napravi:\n{models}\n\nJih želite prenesti zdaj?", + "backupRestore_missingModelsMessage": "Obnovljene nastavitve izbirajo modele, ki niso na voljo v tej napravi. Jih želite prenesti zdaj?", "backupRestore_downloadModels": "Prenesi modele", "backupRestore_downloading": "Prenašanje…", "backupRestore_cancelDownload": "Prekliči prenos", @@ -3983,5 +3983,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ali TCP", "connectSheet_stopReconnecting": "Ustavi ponovno povezovanje", "connectSheet_reconnectFailed": "Ni mogoče doseči {name}. Preverite, ali je vklopljen in v bližini.", - "chat_composerOffline": "Za pošiljanje sporočil se povežite z radiem" + "chat_composerOffline": "Za pošiljanje sporočil se povežite z radiem", + "modelDownload_notDownloaded": "Ni preneseno", + "modelDownload_downloading": "Prenašanje", + "modelDownload_active": "Aktiven", + "modelDownload_failed": "Prenos ni uspel", + "modelDownload_incomplete": "Nepopolno", + "modelDownload_verifying": "Preverjanje prenosa", + "modelDownload_useModel": "Uporabi ta model", + "modelDownload_removeFailed": "Modela ni bilo mogoče odstraniti: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 7ec4e120..3beec8a0 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3803,7 +3803,7 @@ "backupRestore_backupComplete": "Säkerhetskopia skapad.", "backupRestore_restoreComplete": "Återställningen är klar. Återanslut om du återställde radions identitet.", "backupRestore_missingModelsTitle": "Modeller inte nedladdade", - "backupRestore_missingModelsMessage": "De återställda inställningarna väljer modeller som inte finns på den här enheten:\n{models}\n\nLadda ned dem nu?", + "backupRestore_missingModelsMessage": "De återställda inställningarna väljer modeller som inte finns på den här enheten. Ladda ned dem nu?", "backupRestore_downloadModels": "Ladda ned modeller", "backupRestore_downloading": "Laddar ned…", "backupRestore_cancelDownload": "Avbryt nedladdning", @@ -3823,5 +3823,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB eller TCP", "connectSheet_stopReconnecting": "Sluta återansluta", "connectSheet_reconnectFailed": "Kunde inte nå {name}. Kontrollera att den är påslagen och i närheten.", - "chat_composerOffline": "Anslut till en radio för att skicka meddelanden" + "chat_composerOffline": "Anslut till en radio för att skicka meddelanden", + "modelDownload_notDownloaded": "Inte nedladdad", + "modelDownload_downloading": "Laddar ner", + "modelDownload_active": "Aktiv", + "modelDownload_failed": "Kunde inte ladda ner", + "modelDownload_incomplete": "Ofullständig", + "modelDownload_verifying": "Verifierar nedladdningen", + "modelDownload_useModel": "Använd den här modellen", + "modelDownload_removeFailed": "Det gick inte att ta bort modellen: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 16d0ca20..64caefb0 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3736,7 +3736,7 @@ "backupRestore_backupComplete": "Файл резервної копії створено.", "backupRestore_restoreComplete": "Відновлення завершено. Перепідключіться, якщо ви відновили ідентифікатор радіо.", "backupRestore_missingModelsTitle": "Моделі не завантажено", - "backupRestore_missingModelsMessage": "Відновлені налаштування вибирають моделі, яких немає на цьому пристрої:\n{models}\n\nЗавантажити їх зараз?", + "backupRestore_missingModelsMessage": "Відновлені налаштування вибирають моделі, яких немає на цьому пристрої. Завантажити їх зараз?", "backupRestore_downloadModels": "Завантажити моделі", "backupRestore_downloading": "Завантаження…", "backupRestore_cancelDownload": "Скасувати завантаження", @@ -3756,5 +3756,14 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB або TCP", "connectSheet_stopReconnecting": "Зупинити перепідключення", "connectSheet_reconnectFailed": "Не вдалося зв'язатися з {name}. Переконайтеся, що воно увімкнене й поруч.", - "chat_composerOffline": "Підключіться до радіо, щоб надсилати повідомлення" + "chat_composerOffline": "Підключіться до радіо, щоб надсилати повідомлення", + "modelDownload_notDownloaded": "Не завантажено", + "modelDownload_downloading": "Завантаження", + "modelDownload_active": "Активна", + "modelDownload_failed": "Не вдалося завантажити", + "modelDownload_incomplete": "Неповна", + "modelDownload_verifying": "Перевірка завантаження", + "modelDownload_useModel": "Використовувати цю модель", + "modelDownload_removeFailed": "Не вдалося видалити модель: {error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6b70ddb0..ce91a452 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3813,7 +3813,7 @@ "backupRestore_backupComplete": "备份文件已创建。", "backupRestore_restoreComplete": "恢复完成。如果恢复了无线电身份,请重新连接。", "backupRestore_missingModelsTitle": "模型未下载", - "backupRestore_missingModelsMessage": "恢复的设置所选用的模型在此设备上不可用:\n{models}\n\n现在下载吗?", + "backupRestore_missingModelsMessage": "恢复的设置所选用的模型在此设备上不可用。现在下载吗?", "backupRestore_downloadModels": "下载模型", "backupRestore_downloading": "正在下载…", "backupRestore_cancelDownload": "取消下载", @@ -3833,5 +3833,14 @@ "connectSheet_chooseRadioSubtitle": "蓝牙、USB 或 TCP", "connectSheet_stopReconnecting": "停止重新连接", "connectSheet_reconnectFailed": "无法连接到 {name}。请确保其已开机且在附近。", - "chat_composerOffline": "连接到无线电后才能发送消息" + "chat_composerOffline": "连接到无线电后才能发送消息", + "modelDownload_notDownloaded": "未下载", + "modelDownload_downloading": "正在下载", + "modelDownload_active": "当前使用", + "modelDownload_failed": "下载失败", + "modelDownload_incomplete": "不完整", + "modelDownload_verifying": "正在校验下载", + "modelDownload_useModel": "使用此模型", + "modelDownload_removeFailed": "无法移除模型:{error}", + "modelDownload_progress": "{current} / {total} MB ({percent}%)" } diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 126216cb..f1e822c8 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -5,15 +5,14 @@ import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../models/app_settings.dart'; -import '../models/image_codec_support.dart'; import '../services/app_settings_service.dart'; import '../services/background_service.dart'; import '../services/image_codec_service.dart'; import '../services/map_tile_cache_service.dart'; import '../services/notification_service.dart'; -import '../theme/mesh_theme.dart'; import '../utils/platform_info.dart'; import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/image_codec_models_section.dart'; import '../widgets/cyr2lat_profile_dialog.dart'; import '../widgets/language_picker_sheet.dart'; import '../widgets/mesh_nav_tile.dart'; @@ -739,7 +738,10 @@ class AppSettingsScreen extends StatelessWidget { onChanged: (value) => settingsService.setImageProcessAutomatically(value), ), - _buildImageCodecModels(context), + if (_imageCodecService(context) != null) ...[ + const Divider(height: 1, indent: 16), + const ImageCodecModelsSection(), + ], ], ], ); @@ -764,166 +766,6 @@ class AppSettingsScreen extends StatelessWidget { ); } - /// Model registry for image messages: the download entry point, the - /// downloaded weights, and — when the build simply cannot run the codec — - /// [ImageCodecService.unavailableReason] instead of a dead download button. - Widget _buildImageCodecModels(BuildContext context) { - final ImageCodecService codec; - try { - codec = context.watch(); - } on ProviderNotFoundException { - return const SizedBox.shrink(); - } - final scheme = Theme.of(context).colorScheme; - final textTheme = Theme.of(context).textTheme; - final reason = codec.unavailableReason; - - return Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.imageMessages_modelSectionTitle, - style: textTheme.titleSmall, - ), - const SizedBox(height: 6), - if (reason != null) - Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: scheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(MeshRadii.md), - ), - child: Text( - reason, - style: textTheme.bodyMedium?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ), - for (final spec in imageCodecPresetModels) - _buildImageCodecPreset(context, codec, spec), - for (final model in codec.availableModels) - ListTile( - contentPadding: EdgeInsets.zero, - dense: true, - leading: const Icon(Icons.check_circle_outline, size: 24), - title: Text(model.name.isEmpty ? model.id : model.name), - subtitle: Text(_formatModelBytes(context, model.fileSizeBytes)), - trailing: IconButton( - icon: const Icon(Icons.delete_outline, size: 24), - tooltip: context.l10n.imageMessages_removeModel, - onPressed: codec.isBusy || codec.isDownloading - ? null - : () => codec.removeModel(model), - ), - ), - if (codec.lastError != null) ...[ - const SizedBox(height: 6), - Text( - codec.lastError!, - style: textTheme.bodyMedium?.copyWith(color: scheme.error), - ), - ], - ], - ), - ); - } - - Widget _buildImageCodecPreset( - BuildContext context, - ImageCodecService codec, - ImageCodecModelSpec spec, - ) { - final textTheme = Theme.of(context).textTheme; - final scheme = Theme.of(context).colorScheme; - final alreadyHave = spec.hasCompleteInstalledRecord(codec.availableModels); - // downloadPresetModel throws StateError on a placeholder URL, deliberately, - // so the button must not be offerable until the weights are published. - final blocked = spec.urlsArePlaceholders; - final busy = codec.isDownloading; - - return Padding( - padding: const EdgeInsets.only(top: 4), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ListTile( - contentPadding: EdgeInsets.zero, - dense: true, - leading: const Icon(Icons.download_outlined, size: 24), - title: Text(spec.label), - subtitle: Text( - blocked - ? context.l10n.imageMessages_modelNotPublished - : _formatModelBytes(context, spec.totalSizeBytes), - ), - trailing: alreadyHave - ? Text( - context.l10n.imageMessages_modelReady, - style: textTheme.labelMedium?.copyWith( - color: scheme.onSurfaceVariant, - ), - ) - : busy - ? TextButton( - onPressed: codec.cancelDownload, - child: Text(context.l10n.imageMessages_cancelDownload), - ) - : TextButton( - onPressed: blocked - ? null - : () => _downloadImageCodecModel(context, codec, spec), - child: Text(context.l10n.imageMessages_downloadModel), - ), - ), - if (busy) - Padding( - padding: const EdgeInsets.only(bottom: 8), - child: LinearProgressIndicator(value: codec.downloadProgress), - ), - ], - ), - ); - } - - Future _downloadImageCodecModel( - BuildContext context, - ImageCodecService codec, - ImageCodecModelSpec spec, - ) async { - final messenger = ScaffoldMessenger.of(context); - final l10n = context.l10n; - try { - await codec.downloadPresetModel(spec); - } catch (error) { - messenger.showSnackBar( - SnackBar( - content: Text(l10n.imageMessages_downloadFailedWithError('$error')), - ), - ); - } - } - - String _formatModelBytes(BuildContext context, int bytes) { - final l10n = context.l10n; - if (bytes >= 1024 * 1024 * 1024) { - return l10n.mapCache_sizeGigabytes( - (bytes / (1024 * 1024 * 1024)).toStringAsFixed(2), - ); - } - if (bytes >= 1024 * 1024) { - return l10n.mapCache_sizeMegabytes( - (bytes / (1024 * 1024)).toStringAsFixed(0), - ); - } - if (bytes >= 1024) { - return l10n.mapCache_sizeKilobytes((bytes / 1024).toStringAsFixed(0)); - } - return l10n.mapCache_sizeBytes('$bytes'); - } - Widget _buildBatteryContent( BuildContext context, AppSettingsService settingsService, diff --git a/lib/screens/backup_restore_screen.dart b/lib/screens/backup_restore_screen.dart index 6a39f46a..02989aff 100644 --- a/lib/screens/backup_restore_screen.dart +++ b/lib/screens/backup_restore_screen.dart @@ -22,6 +22,7 @@ import '../utils/platform_info.dart'; import '../utils/share_origin.dart'; import '../widgets/app_bar.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/model_download_list.dart'; import '../widgets/sync_progress_overlay.dart'; class BackupRestoreScreen extends StatefulWidget { @@ -630,12 +631,6 @@ class _BackupRestoreScreenState extends State { required ImageCodecService imageCodecService, }) async { final l10n = context.l10n; - final modelNames = [ - if (translationModel != null) - translationModelFriendlyName(translationModel), - if (imageCodecModel != null) - imageCodecSpec?.label ?? imageCodecModel.name, - ]; var starting = false; var cancelRequested = false; var translationDone = translationModel == null; @@ -658,16 +653,9 @@ class _BackupRestoreScreenState extends State { starting || translationService.isDownloading || imageCodecService.isDownloading; - final currentProgress = currentModel == translationModel?.name - ? translationService.downloadProgress - : currentModel == imageCodecModel?.name - ? imageCodecService.downloadProgress - : null; - final currentFile = currentModel == translationModel?.name - ? translationService.downloadFileName - : currentModel == imageCodecModel?.name - ? imageCodecService.downloadFileName - : null; + final translationCurrent = currentModel == translationModel?.name; + final imageCurrent = currentModel == imageCodecModel?.name; + final failure = downloadError; void requestDownloadCancel() { cancelRequested = true; @@ -682,31 +670,73 @@ class _BackupRestoreScreenState extends State { }, child: AlertDialog( title: Text(l10n.backupRestore_missingModelsTitle), - content: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - l10n.backupRestore_missingModelsMessage( - modelNames.join('\n'), - ), - ), - if (isDownloading) ...[ - const SizedBox(height: 16), - Text(currentFile ?? currentModel ?? ''), - const SizedBox(height: 8), - LinearProgressIndicator(value: currentProgress), - ], - if (downloadError != null) ...[ + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.backupRestore_missingModelsMessage), const SizedBox(height: 12), - Text( - l10n.backupRestore_failed(downloadError!), - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), + ModelDownloadList( + rowPadding: const EdgeInsets.symmetric(vertical: 4), + items: [ + if (translationModel != null) + _missingModelItem( + id: 'translation-${translationModel.id}', + name: translationModelFriendlyName( + translationModel, + ), + sizeBytes: translationModel.fileSizeBytes, + done: translationDone, + current: translationCurrent, + downloading: + translationService.isDownloading || + (starting && translationCurrent), + progress: translationService.downloadProgress, + downloadedBytes: + translationService.downloadedBytes, + totalBytes: translationService.downloadTotalBytes, + detail: + translationService.downloadFileName == + 'Merging chunks...' + ? l10n.translation_mergingChunks + : null, + error: failure == null + ? null + : l10n.backupRestore_failed(failure), + ), + if (imageCodecModel != null) + _missingModelItem( + id: 'image-${imageCodecModel.id}', + name: + imageCodecSpec?.label ?? + imageCodecModelFriendlyName(imageCodecModel), + sizeBytes: + imageCodecSpec?.totalSizeBytes ?? + imageCodecModel.fileSizeBytes, + done: imageCodecDone, + current: imageCurrent, + downloading: + imageCodecService.isDownloading || + (starting && imageCurrent), + progress: imageCodecService.downloadProgress, + downloadedBytes: + imageCodecService.downloadedBytes, + totalBytes: imageCodecService.downloadTotalBytes, + detail: + imageCodecService.downloadFileName + ?.startsWith('Verifying ') == + true + ? l10n.modelDownload_verifying + : null, + error: failure == null + ? null + : l10n.backupRestore_failed(failure), + ), + ], ), ], - ], + ), ), actions: [ TextButton( @@ -830,3 +860,40 @@ class _BackupRestoreScreenState extends State { showDismissibleSnackBar(context, content: Text(message)); } } + +ModelDownloadItem _missingModelItem({ + required String id, + required String name, + required int sizeBytes, + required bool done, + required bool current, + required bool downloading, + required double? progress, + required int downloadedBytes, + required int? totalBytes, + required String? detail, + required String? error, +}) { + final inProgress = downloading && current && !done; + final failed = error != null && current && !inProgress && !done; + return ModelDownloadItem( + id: id, + name: name, + sizeBytes: sizeBytes > 0 ? sizeBytes : null, + status: done + ? ModelDownloadStatus.ready + : failed + ? ModelDownloadStatus.error + : inProgress + ? ModelDownloadStatus.downloading + : ModelDownloadStatus.notDownloaded, + progress: inProgress ? progress : null, + downloadedBytes: inProgress ? downloadedBytes : 0, + totalBytes: inProgress ? totalBytes : null, + detail: failed + ? error + : inProgress + ? detail + : null, + ); +} diff --git a/lib/widgets/image_codec_models_section.dart b/lib/widgets/image_codec_models_section.dart new file mode 100644 index 00000000..66770288 --- /dev/null +++ b/lib/widgets/image_codec_models_section.dart @@ -0,0 +1,297 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/image_codec_support.dart'; +import '../services/image_codec_service.dart'; +import '../theme/mesh_theme.dart'; +import 'model_download_list.dart'; + +/// Image-codec registry: one [ModelDownloadList] row per model. +/// +/// A preset and the files it installed are the same row. The friendly name is +/// the preset label, never the on-disk graph filename. +class ImageCodecModelsSection extends StatefulWidget { + const ImageCodecModelsSection({super.key}); + + @override + State createState() => + _ImageCodecModelsSectionState(); +} + +class _ImageCodecModelsSectionState extends State { + String? _failedId; + String? _failedDetail; + + @override + Widget build(BuildContext context) { + final codec = context.watch(); + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final reason = codec.unavailableReason; + final lastError = codec.lastError; + final showLastError = + lastError != null && + lastError.isNotEmpty && + lastError != 'Download stopped.' && + lastError != _failedDetail; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text( + l10n.imageMessages_modelSectionTitle, + style: theme.textTheme.titleSmall, + ), + ), + if (reason != null) + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(MeshRadii.md), + ), + child: Padding( + padding: const EdgeInsets.all(12), + child: Text( + reason, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ), + ), + ModelDownloadList(items: _items(context, codec)), + if (showLastError) + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Text( + lastError, + style: theme.textTheme.bodyMedium?.copyWith(color: scheme.error), + ), + ) + else + const SizedBox(height: 8), + ], + ); + } + + List _items( + BuildContext context, + ImageCodecService codec, + ) { + final models = codec.availableModels; + final used = {}; + final items = []; + + for (final spec in imageCodecPresetModels) { + final belonging = [ + for (final model in models) + if (_belongsToSpec(model, spec)) model, + ]; + used.addAll(belonging); + final record = _preferredRecord(belonging, spec); + items.add(_presetItem(context, codec, spec, record)); + } + + for (final model in models) { + if (used.contains(model)) continue; + items.add(_customItem(context, codec, model)); + } + return items; + } + + ModelDownloadItem _presetItem( + BuildContext context, + ImageCodecService codec, + ImageCodecModelSpec spec, + ImageCodecModelRecord? record, + ) { + final l10n = context.l10n; + final blocked = spec.urlsArePlaceholders; + final installedId = record?.id; + final complete = + record != null && spec.hasCompleteInstalledRecord([record]); + final downloading = !blocked && _specIsDownloading(codec, spec); + final verifying = downloading && _isVerifying(codec); + final failed = !downloading && !complete && _failedId == spec.id; + final selectedId = codec.selectedModel?.id; + final selected = + complete && (selectedId == spec.id || selectedId == installedId); + final busy = codec.isBusy || codec.isDownloading; + + final ModelDownloadStatus status; + String? statusLabel; + if (downloading) { + status = ModelDownloadStatus.downloading; + } else if (complete) { + status = ModelDownloadStatus.ready; + } else if (failed) { + status = ModelDownloadStatus.error; + } else { + status = ModelDownloadStatus.notDownloaded; + if (record != null && !blocked) { + statusLabel = l10n.modelDownload_incomplete; + } + } + + final size = record != null && record.fileSizeBytes > 0 + ? record.fileSizeBytes + : spec.totalSizeBytes; + + return ModelDownloadItem( + id: spec.id, + name: spec.label, + sizeBytes: size > 0 ? size : null, + status: status, + statusLabel: statusLabel, + selected: selected, + enabled: !blocked, + progress: verifying ? null : codec.downloadProgress, + downloadedBytes: downloading ? codec.downloadedBytes : 0, + totalBytes: downloading ? codec.downloadTotalBytes : null, + detail: blocked + ? l10n.imageMessages_modelNotPublished + : verifying + ? l10n.modelDownload_verifying + : failed + ? _failedDetail + : null, + onDownload: !blocked && !complete && !codec.isDownloading + ? () => _download(spec) + : null, + onCancel: downloading ? codec.cancelDownload : null, + onDelete: record != null && !busy ? () => _delete(record) : null, + onSelect: complete && !selected && !busy + ? () => codec.setSelectedModelId(installedId ?? spec.id) + : null, + ); + } + + ModelDownloadItem _customItem( + BuildContext context, + ImageCodecService codec, + ImageCodecModelRecord model, + ) { + final l10n = context.l10n; + final downloading = _recordIsDownloading(codec, model); + final verifying = downloading && _isVerifying(codec); + final ready = model.localPath.isNotEmpty && !downloading; + final busy = codec.isBusy || codec.isDownloading; + final selected = ready && codec.selectedModel?.id == model.id; + + return ModelDownloadItem( + id: model.id, + name: imageCodecModelFriendlyName(model), + sizeBytes: model.fileSizeBytes > 0 ? model.fileSizeBytes : null, + status: downloading + ? ModelDownloadStatus.downloading + : ready + ? ModelDownloadStatus.ready + : ModelDownloadStatus.notDownloaded, + selected: selected, + progress: verifying ? null : codec.downloadProgress, + downloadedBytes: downloading ? codec.downloadedBytes : 0, + totalBytes: downloading ? codec.downloadTotalBytes : null, + detail: verifying ? l10n.modelDownload_verifying : null, + onCancel: downloading ? codec.cancelDownload : null, + onDelete: !busy ? () => _delete(model) : null, + onSelect: ready && !selected && !busy + ? () => codec.setSelectedModelId(model.id) + : null, + ); + } + + bool _specIsDownloading(ImageCodecService codec, ImageCodecModelSpec spec) { + if (!codec.isDownloading) return false; + final name = _downloadFileName(codec); + if (name == null) return imageCodecPresetModels.length == 1; + return spec.assets.any((asset) => asset.fileName == name); + } + + bool _recordIsDownloading( + ImageCodecService codec, + ImageCodecModelRecord model, + ) { + if (!codec.isDownloading) return false; + final name = _downloadFileName(codec); + if (name == null) return false; + return model.name == name || model.assetFileNames.contains(name); + } + + bool _isVerifying(ImageCodecService codec) => + codec.downloadFileName?.startsWith('Verifying ') ?? false; + + String? _downloadFileName(ImageCodecService codec) { + final raw = codec.downloadFileName; + if (raw == null || raw.isEmpty) return null; + const prefix = 'Verifying '; + return raw.startsWith(prefix) ? raw.substring(prefix.length) : raw; + } + + Future _download(ImageCodecModelSpec spec) async { + setState(() { + _failedId = null; + _failedDetail = null; + }); + final l10n = context.l10n; + try { + await context.read().downloadPresetModel(spec); + } on ImageCodecDownloadCancelled { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.translation_downloadStopped), + ); + } catch (error) { + if (!mounted) return; + final message = l10n.imageMessages_downloadFailedWithError('$error'); + setState(() { + _failedId = spec.id; + _failedDetail = message; + }); + showDismissibleSnackBar(context, content: Text(message)); + } + } + + Future _delete(ImageCodecModelRecord model) async { + final l10n = context.l10n; + try { + await context.read().removeModel(model); + } catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.modelDownload_removeFailed('$error')), + ); + } + } +} + +bool _belongsToSpec(ImageCodecModelRecord model, ImageCodecModelSpec spec) { + if (model.id == spec.id || model.name == spec.fileName) return true; + for (final asset in spec.assets) { + if (asset.fileName == model.name) return true; + } + return false; +} + +ImageCodecModelRecord? _preferredRecord( + List models, + ImageCodecModelSpec spec, +) { + for (final model in models) { + if (spec.hasCompleteInstalledRecord([model])) return model; + } + for (final model in models) { + if (model.id == spec.id) return model; + } + if (models.isEmpty) return null; + return models.first; +} diff --git a/lib/widgets/model_download_list.dart b/lib/widgets/model_download_list.dart new file mode 100644 index 00000000..847c2fd3 --- /dev/null +++ b/lib/widgets/model_download_list.dart @@ -0,0 +1,338 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../l10n/l10n.dart'; +import '../theme/mesh_theme.dart'; +import 'mesh_nav_tile.dart'; + +/// Install state of one on-device model row. +enum ModelDownloadStatus { notDownloaded, downloading, ready, error } + +/// One model in a [ModelDownloadList]. +/// +/// Callers own the download. This only describes what the row should show +/// and which action to offer. +class ModelDownloadItem { + final String id; + final String name; + + /// Bytes on disk, or the expected download size before anything is fetched. + /// Zero and null both mean "size unknown" and are omitted. + final int? sizeBytes; + final ModelDownloadStatus status; + + /// True when this installed model is the one the feature will use. + final bool selected; + + /// False dims the row and drops its actions, same as a disabled settings tile. + final bool enabled; + + /// 0–1 while [status] is [ModelDownloadStatus.downloading]. Null is an + /// indeterminate bar (size unknown, merging, or verifying). + final double? progress; + final int downloadedBytes; + final int? totalBytes; + + /// Extra line under the status: a failure, a "not published" note, or + /// "merging" / "verifying" while a download finishes. + final String? detail; + + /// Replaces the default status word. Used for an install that started but + /// did not finish ("Incomplete"). + final String? statusLabel; + + final VoidCallback? onDownload; + final VoidCallback? onCancel; + final VoidCallback? onDelete; + final VoidCallback? onSelect; + + const ModelDownloadItem({ + required this.id, + required this.name, + required this.status, + this.sizeBytes, + this.selected = false, + this.enabled = true, + this.progress, + this.downloadedBytes = 0, + this.totalBytes, + this.detail, + this.statusLabel, + this.onDownload, + this.onCancel, + this.onDelete, + this.onSelect, + }); + + bool get isActive => selected && status == ModelDownloadStatus.ready; +} + +/// Shared list of on-device models: name, size, status, selection, and one +/// action (download, cancel, or remove). +/// +/// Sits inside an existing card. It does not scroll; the page or dialog does. +class ModelDownloadList extends StatelessWidget { + final List items; + + /// When null, a row with an action keeps the button's own padding on the + /// right, and a row without one uses 16. + final EdgeInsets? rowPadding; + + const ModelDownloadList({super.key, required this.items, this.rowPadding}); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + for (var i = 0; i < items.length; i++) ...[ + if (i > 0) const Divider(height: 1, indent: 16), + _ModelDownloadRow(item: items[i], padding: rowPadding), + ], + ], + ); + } +} + +class _ModelDownloadRow extends StatelessWidget { + final ModelDownloadItem item; + final EdgeInsets? padding; + + const _ModelDownloadRow({required this.item, required this.padding}); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final onTap = _rowTap(); + final actions = _actions(l10n); + final statusWord = _statusWord(l10n); + final sizeLabel = _sizeLabel(l10n); + final caption = _progressCaption(l10n); + + final row = Padding( + padding: + padding ?? + (actions.isEmpty + ? const EdgeInsets.fromLTRB(16, 8, 16, 8) + : const EdgeInsets.fromLTRB(16, 8, 0, 8)), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 2), + child: _leading(scheme), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(item.name, style: meshTileTitleStyle(theme)), + const SizedBox(height: 2), + Text.rich( + TextSpan( + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + children: [ + if (sizeLabel != null) ...[ + TextSpan( + text: sizeLabel, + style: MeshTheme.mono( + fontSize: 14, + color: scheme.onSurfaceVariant, + ), + ), + const TextSpan(text: ' · '), + ], + TextSpan(text: statusWord), + if (item.isActive) ...[ + const TextSpan(text: ' · '), + TextSpan( + text: l10n.modelDownload_active, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurface, + fontWeight: FontWeight.w600, + ), + ), + ], + ], + ), + ), + if (item.detail != null && item.detail!.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + item.detail!, + style: theme.textTheme.bodyMedium?.copyWith( + color: item.status == ModelDownloadStatus.error + ? scheme.error + : scheme.onSurfaceVariant, + ), + ), + ], + if (item.status == ModelDownloadStatus.downloading) ...[ + const SizedBox(height: 8), + LinearProgressIndicator(value: item.progress), + if (caption != null) ...[ + const SizedBox(height: 4), + Text( + caption, + style: MeshTheme.mono( + fontSize: 12, + color: scheme.onSurfaceVariant, + ), + ), + ], + ], + ], + ), + ), + if (actions.isNotEmpty) + Row(mainAxisSize: MainAxisSize.min, children: actions), + ], + ), + ); + + return Opacity( + opacity: item.enabled ? 1 : 0.5, + child: Semantics( + button: onTap != null, + enabled: item.enabled, + selected: item.isActive, + hint: item.status == ModelDownloadStatus.ready && item.onSelect != null + ? l10n.modelDownload_useModel + : null, + child: IgnorePointer( + ignoring: !item.enabled, + child: InkWell( + key: ValueKey('model-row-${item.id}'), + onTap: onTap, + child: row, + ), + ), + ), + ); + } + + VoidCallback? _rowTap() { + if (!item.enabled) return null; + if (item.status == ModelDownloadStatus.ready) return item.onSelect; + if (item.status == ModelDownloadStatus.downloading) return null; + return item.onDownload; + } + + Widget _leading(ColorScheme scheme) { + switch (item.status) { + case ModelDownloadStatus.downloading: + return const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator(strokeWidth: 2), + ); + case ModelDownloadStatus.error: + return Icon(Icons.error_outline, size: 24, color: scheme.error); + case ModelDownloadStatus.ready: + return Icon( + item.isActive ? Icons.check_circle : Icons.check_circle_outline, + size: 24, + color: item.isActive ? scheme.primary : scheme.onSurfaceVariant, + ); + case ModelDownloadStatus.notDownloaded: + return Icon( + Icons.download_outlined, + size: 24, + color: scheme.onSurfaceVariant, + ); + } + } + + List _actions(AppLocalizations l10n) { + if (!item.enabled) return const []; + if (item.status == ModelDownloadStatus.downloading) { + if (item.onCancel == null) return const []; + return [ + IconButton( + key: ValueKey('model-cancel-${item.id}'), + tooltip: l10n.imageMessages_cancelDownload, + onPressed: item.onCancel, + icon: const Icon(Icons.close), + ), + ]; + } + final actions = []; + if (item.status != ModelDownloadStatus.ready && item.onDownload != null) { + actions.add( + IconButton( + key: ValueKey('model-download-${item.id}'), + tooltip: l10n.imageMessages_downloadModel, + onPressed: item.onDownload, + icon: const Icon(Icons.download_outlined), + ), + ); + } + if (item.onDelete != null) { + actions.add( + IconButton( + key: ValueKey('model-remove-${item.id}'), + tooltip: l10n.imageMessages_removeModel, + onPressed: item.onDelete, + icon: const Icon(Icons.delete_outline), + ), + ); + } + return actions; + } + + String _statusWord(AppLocalizations l10n) { + final override = item.statusLabel; + if (override != null && override.isNotEmpty) return override; + switch (item.status) { + case ModelDownloadStatus.notDownloaded: + return l10n.modelDownload_notDownloaded; + case ModelDownloadStatus.downloading: + return l10n.modelDownload_downloading; + case ModelDownloadStatus.ready: + return l10n.imageMessages_modelReady; + case ModelDownloadStatus.error: + return l10n.modelDownload_failed; + } + } + + String? _sizeLabel(AppLocalizations l10n) { + final bytes = item.sizeBytes; + if (bytes == null || bytes <= 0) return null; + if (bytes >= 1024 * 1024 * 1024) { + return l10n.mapCache_sizeGigabytes( + (bytes / (1024 * 1024 * 1024)).toStringAsFixed(2), + ); + } + if (bytes >= 1024 * 1024) { + final mb = bytes / (1024 * 1024); + final digits = mb >= 100 ? 0 : 1; + return l10n.mapCache_sizeMegabytes(mb.toStringAsFixed(digits)); + } + if (bytes >= 1024) { + return l10n.mapCache_sizeKilobytes((bytes / 1024).toStringAsFixed(0)); + } + return l10n.mapCache_sizeBytes('$bytes'); + } + + String? _progressCaption(AppLocalizations l10n) { + if (item.status != ModelDownloadStatus.downloading) return null; + if (item.detail != null && item.detail!.isNotEmpty) return null; + final currentMb = item.downloadedBytes / (1024 * 1024); + final total = item.totalBytes; + if (total == null || total <= 0) { + return l10n.mapCache_sizeMegabytes(currentMb.toStringAsFixed(1)); + } + final totalMb = total / (1024 * 1024); + final fraction = item.progress ?? (item.downloadedBytes / total); + final percent = (fraction * 100).clamp(0, 100).toStringAsFixed(0); + return l10n.modelDownload_progress( + currentMb.toStringAsFixed(1), + totalMb.toStringAsFixed(1), + percent, + ); + } +} diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart index dd8c6ac5..9d68c26f 100644 --- a/lib/widgets/translation_settings_section.dart +++ b/lib/widgets/translation_settings_section.dart @@ -2,12 +2,14 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../helpers/snack_bar_builder.dart'; +import '../l10n/app_localizations.dart'; import '../l10n/l10n.dart'; +import '../models/app_settings.dart'; import '../models/translation_support.dart'; import '../services/app_settings_service.dart'; import '../services/translation_service.dart'; -import '../theme/mesh_theme.dart'; import 'mesh_nav_tile.dart'; +import 'model_download_list.dart'; /// [TranslationService] publishes this as `downloadFileName` while it merges /// downloaded chunks (see translation_service.dart). The service owns the @@ -15,24 +17,21 @@ import 'mesh_nav_tile.dart'; /// place, until the service grows a proper "merging" getter. const String _mergingChunksFileName = 'Merging chunks...'; -/// On-device translation settings: feature toggles, target language, model -/// selection, model downloads and the downloaded-model list. +/// On-device translation settings: feature toggles, target language, and the +/// shared model list. /// -/// Watches only [AppSettingsService] and [TranslationService], so download -/// progress ticks rebuild this card and nothing else on the settings screen. +/// [_TranslationModels] watches [TranslationService], so download progress +/// rebuilds the model rows and not the toggles above them. class TranslationSettingsSection extends StatelessWidget { const TranslationSettingsSection({super.key}); @override Widget build(BuildContext context) { final settingsService = context.watch(); - final translationService = context.watch(); final l10n = context.l10n; final settings = settingsService.settings; final translationEnabled = settings.translationEnabled; final theme = Theme.of(context); - final scheme = theme.colorScheme; - final textTheme = theme.textTheme; final disabledColor = translationEnabled ? null : theme.disabledColor; const tilePadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4); @@ -96,201 +95,11 @@ class TranslationSettingsSection extends StatelessWidget { onTap: () => _showTranslationLanguageDialog(context, settingsService), ), const Divider(height: 1, indent: 16), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: DropdownButtonFormField( - initialValue: settings.translationSelectedModelId, - isExpanded: true, - decoration: InputDecoration( - labelText: l10n.translation_downloadedModelLabel, - border: const OutlineInputBorder(), - ), - items: [ - for (final model in settings.translationDownloadedModels) - DropdownMenuItem( - value: model.id, - child: Text( - translationModelFriendlyName(model), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: settings.translationDownloadedModels.isEmpty - ? null - : (value) { - settingsService.setTranslationSelectedModelId(value); - }, - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: DropdownButtonFormField( - initialValue: null, - isExpanded: true, - decoration: InputDecoration( - labelText: l10n.translation_presetModelLabel, - border: const OutlineInputBorder(), - ), - items: [ - for (final preset in translationPresetModels) - DropdownMenuItem( - value: preset.sourceUrl, - child: Text( - translationModelFriendlyName(preset), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: translationService.isBusy - ? null - : (value) async { - if (value == null) return; - final preset = translationPresetModels.firstWhere( - (entry) => entry.sourceUrl == value, - ); - await _downloadTranslationModel( - context, - translationService, - settingsService, - sourceUrl: preset.sourceUrl, - fileName: preset.name, - id: preset.id, - ); - }, - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _TranslationUrlField( - initialValue: settings.translationModelSourceUrl ?? '', - onChanged: settingsService.setTranslationModelSourceUrl, - onDownload: translationService.isBusy - ? null - : (url) => _downloadTranslationModel( - context, - translationService, - settingsService, - sourceUrl: url, - ), - downloadLabel: translationService.isDownloading - ? l10n.translation_downloading - : translationService.isBusy - ? l10n.translation_working - : l10n.translation_downloadModel, - isDownloading: translationService.isDownloading, - onCancel: translationService.cancelDownload, - labelText: l10n.translation_manualUrlLabel, - stopLabel: l10n.translation_stop, - ), - if (translationService.isDownloading) ...[ - const SizedBox(height: 12), - ClipRRect( - borderRadius: BorderRadius.circular(2), - child: LinearProgressIndicator( - value: _isMerging(translationService) - ? null - : translationService.downloadProgress, - ), - ), - const SizedBox(height: 8), - Align( - alignment: Alignment.centerLeft, - child: Text( - _downloadProgressLabel(context, translationService), - style: MeshTheme.mono( - fontSize: 14, - color: scheme.onSurfaceVariant, - ), - ), - ), - ], - if (settings.translationDownloadedModels.isNotEmpty) ...[ - const SizedBox(height: 16), - Align( - alignment: Alignment.centerLeft, - child: Text( - l10n.translation_downloadedModels, - style: textTheme.titleSmall, - ), - ), - const SizedBox(height: 8), - for (final model in settings.translationDownloadedModels) - Padding( - padding: const EdgeInsets.only(bottom: 8), - child: Row( - children: [ - Icon( - model.id == settings.translationSelectedModelId - ? Icons.check_circle - : Icons.memory_outlined, - size: 24, - color: model.id == settings.translationSelectedModelId - ? scheme.primary - : scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: InkWell( - borderRadius: BorderRadius.circular(MeshRadii.xs), - onTap: () => settingsService - .setTranslationSelectedModelId(model.id), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - translationModelFriendlyName(model), - style: textTheme.bodyLarge?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - Text( - _downloadedModelLabel(context, model), - style: MeshTheme.mono( - fontSize: 12, - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - ), - IconButton( - tooltip: l10n.translation_deleteModel, - onPressed: translationService.isBusy - ? null - : () => _deleteTranslationModel( - context, - translationService, - model, - ), - icon: const Icon(Icons.delete_outline), - ), - ], - ), - ), - ], - if (translationService.lastError != null) ...[ - const SizedBox(height: 8), - Text( - translationService.lastError!, - style: TextStyle(color: scheme.error), - ), - ], - ], - ), - ), + const _TranslationModels(), ], ); } - static bool _isMerging(TranslationService service) => - service.downloadFileName == _mergingChunksFileName; - void _showTranslationLanguageDialog( BuildContext context, AppSettingsService settingsService, @@ -308,50 +117,6 @@ class TranslationSettingsSection extends StatelessWidget { ); } - Future _downloadTranslationModel( - BuildContext context, - TranslationService translationService, - AppSettingsService settingsService, { - required String sourceUrl, - String? fileName, - String? id, - }) async { - if (sourceUrl.isEmpty) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.translation_enterUrlFirst), - ); - return; - } - try { - await translationService.downloadModel( - sourceUrl: sourceUrl, - fileName: fileName, - id: id, - ); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(context.l10n.translation_modelDownloaded), - ); - await settingsService.setTranslationEnabled(true); - } on TranslationDownloadCancelled { - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(context.l10n.translation_downloadStopped), - ); - } catch (error) { - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text( - context.l10n.translation_downloadFailed(error.toString()), - ), - ); - } - } - String _translationLanguageLabel(BuildContext context, String? languageCode) { if (languageCode == null || languageCode.isEmpty) { return context.l10n.translation_useAppLanguage; @@ -363,45 +128,324 @@ class TranslationSettingsSection extends StatelessWidget { } return languageCode.toUpperCase(); } +} - String _downloadProgressLabel( - BuildContext context, - TranslationService translationService, - ) { +class _PendingDownload { + final String id; + final String name; + final String sourceUrl; + final String? fileName; + final String? modelId; + + const _PendingDownload({ + required this.id, + required this.name, + required this.sourceUrl, + this.fileName, + this.modelId, + }); +} + +/// Preset rows, installed models, and the manual URL field. +class _TranslationModels extends StatefulWidget { + const _TranslationModels(); + + @override + State<_TranslationModels> createState() => _TranslationModelsState(); +} + +class _TranslationModelsState extends State<_TranslationModels> { + _PendingDownload? _pending; + String? _failedId; + String? _failedDetail; + + @override + Widget build(BuildContext context) { + final settingsService = context.watch(); + final translationService = context.watch(); final l10n = context.l10n; - if (_isMerging(translationService)) { - return l10n.translation_mergingChunks; - } - final fileName = - translationService.downloadFileName ?? - l10n.translation_defaultModelName; - final currentMb = translationService.downloadedBytes / (1024 * 1024); - final totalBytes = translationService.downloadTotalBytes; - if (totalBytes == null || totalBytes <= 0) { - return l10n.translation_downloadProgressBytes( - fileName, - currentMb.toStringAsFixed(1), - ); - } - final totalMb = totalBytes / (1024 * 1024); - final percent = ((translationService.downloadProgress ?? 0) * 100) - .toStringAsFixed(0); - return l10n.translation_downloadProgressTotal( - fileName, - currentMb.toStringAsFixed(1), - totalMb.toStringAsFixed(1), - percent, + final settings = settingsService.settings; + final scheme = Theme.of(context).colorScheme; + final lastError = translationService.lastError; + final showLastError = + lastError != null && + lastError.isNotEmpty && + lastError != 'Download stopped.' && + lastError != _failedDetail; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ModelDownloadList( + items: _items(l10n, settings, settingsService, translationService), + ), + const Divider(height: 1, indent: 16), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + child: _TranslationUrlField( + initialValue: settings.translationModelSourceUrl ?? '', + onChanged: settingsService.setTranslationModelSourceUrl, + onDownload: translationService.isBusy + ? null + : (url) => _download(sourceUrl: url), + labelText: l10n.translation_manualUrlLabel, + downloadTooltip: l10n.imageMessages_downloadModel, + ), + ), + if (showLastError) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + child: Text( + lastError, + style: Theme.of( + context, + ).textTheme.bodyMedium?.copyWith(color: scheme.error), + ), + ), + ], ); } - Future _deleteTranslationModel( - BuildContext context, + List _items( + AppLocalizations l10n, + AppSettings settings, + AppSettingsService settingsService, + TranslationService service, + ) { + final downloaded = settings.translationDownloadedModels; + final selectedId = settings.translationSelectedModelId; + final pending = _pending; + final used = {}; + final items = []; + var pendingShown = false; + + bool targets(String id, String sourceUrl, String name) { + if (pending == null) return false; + if (pending.id == id || pending.modelId == id) return true; + if (sourceUrl.isNotEmpty && pending.sourceUrl == sourceUrl) return true; + if (name.isNotEmpty && pending.name == name) return true; + return false; + } + + ModelDownloadItem buildItem({ + required String id, + required String name, + required String sourceUrl, + required String? fileName, + required String? modelId, + required TranslationModelRecord? installed, + }) { + if (installed != null) used.add(installed); + final currentFile = service.downloadFileName; + final fileMatches = + currentFile != null && + currentFile != _mergingChunksFileName && + (currentFile == fileName || currentFile == installed?.name); + final downloading = + service.isDownloading && + (targets(id, sourceUrl, name) || fileMatches); + final failed = !downloading && _failedId == id; + if (downloading || failed) pendingShown = true; + final merging = downloading && _isMerging(service); + final busy = service.isBusy; + final installedModel = installed; + + return ModelDownloadItem( + id: id, + name: name, + sizeBytes: installedModel != null && installedModel.fileSizeBytes > 0 + ? installedModel.fileSizeBytes + : null, + status: downloading + ? ModelDownloadStatus.downloading + : failed + ? ModelDownloadStatus.error + : installedModel != null + ? ModelDownloadStatus.ready + : ModelDownloadStatus.notDownloaded, + selected: + installedModel != null && + !downloading && + installedModel.id == selectedId, + detail: merging + ? l10n.translation_mergingChunks + : failed + ? _failedDetail + : null, + progress: downloading && !merging ? service.downloadProgress : null, + downloadedBytes: downloading ? service.downloadedBytes : 0, + totalBytes: downloading ? service.downloadTotalBytes : null, + onDownload: !busy && installedModel == null + ? () => _download( + sourceUrl: sourceUrl, + fileName: fileName, + id: modelId, + ) + : null, + onCancel: downloading ? service.cancelDownload : null, + onDelete: installedModel != null && !busy + ? () => _delete(service, installedModel) + : null, + onSelect: + installedModel != null && + !downloading && + installedModel.id != selectedId && + !busy + ? () => settingsService.setTranslationSelectedModelId( + installedModel.id, + ) + : null, + ); + } + + for (final preset in translationPresetModels) { + TranslationModelRecord? installed; + for (final model in downloaded) { + if (model.id == preset.id || + (preset.sourceUrl.isNotEmpty && + model.sourceUrl == preset.sourceUrl) || + (preset.name.isNotEmpty && model.name == preset.name)) { + installed = model; + break; + } + } + items.add( + buildItem( + id: preset.id, + name: translationModelFriendlyName(preset), + sourceUrl: preset.sourceUrl, + fileName: preset.name, + modelId: preset.id, + installed: installed, + ), + ); + } + + for (final model in downloaded) { + if (used.contains(model)) continue; + items.add( + buildItem( + id: model.id, + name: translationModelFriendlyName(model), + sourceUrl: model.sourceUrl, + fileName: model.name, + modelId: model.id, + installed: model, + ), + ); + } + + if (pending != null && + !pendingShown && + (service.isDownloading || _failedId == pending.id)) { + final downloading = service.isDownloading; + final merging = downloading && _isMerging(service); + items.add( + ModelDownloadItem( + id: pending.id, + name: pending.name, + status: downloading + ? ModelDownloadStatus.downloading + : ModelDownloadStatus.error, + detail: merging + ? l10n.translation_mergingChunks + : downloading + ? null + : _failedDetail, + progress: downloading && !merging ? service.downloadProgress : null, + downloadedBytes: downloading ? service.downloadedBytes : 0, + totalBytes: downloading ? service.downloadTotalBytes : null, + onCancel: downloading ? service.cancelDownload : null, + onDownload: !service.isBusy && !downloading + ? () => _download( + sourceUrl: pending.sourceUrl, + fileName: pending.fileName, + id: pending.modelId, + ) + : null, + ), + ); + } + + return items; + } + + bool _isMerging(TranslationService service) => + service.downloadFileName == _mergingChunksFileName; + + Future _download({ + required String sourceUrl, + String? fileName, + String? id, + }) async { + final trimmed = sourceUrl.trim(); + if (trimmed.isEmpty) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.translation_enterUrlFirst), + ); + return; + } + final pending = _PendingDownload( + id: id ?? trimmed, + name: _displayName(trimmed, fileName, id), + sourceUrl: trimmed, + fileName: fileName, + modelId: id, + ); + setState(() { + _pending = pending; + _failedId = null; + _failedDetail = null; + }); + final settingsService = context.read(); + final translationService = context.read(); + try { + await translationService.downloadModel( + sourceUrl: trimmed, + fileName: fileName, + id: id, + ); + if (!mounted) return; + setState(() { + _pending = null; + _failedId = null; + _failedDetail = null; + }); + showDismissibleSnackBar( + context, + content: Text(context.l10n.translation_modelDownloaded), + ); + await settingsService.setTranslationEnabled(true); + } on TranslationDownloadCancelled { + if (!mounted) return; + setState(() { + _pending = null; + _failedId = null; + _failedDetail = null; + }); + showDismissibleSnackBar( + context, + content: Text(context.l10n.translation_downloadStopped), + ); + } catch (error) { + if (!mounted) return; + final message = context.l10n.translation_downloadFailed('$error'); + setState(() { + _failedId = pending.id; + _failedDetail = message; + }); + showDismissibleSnackBar(context, content: Text(message)); + } + } + + Future _delete( TranslationService translationService, TranslationModelRecord model, ) async { try { await translationService.removeModel(model); - if (!context.mounted) return; + if (!mounted) return; showDismissibleSnackBar( context, content: Text( @@ -411,7 +455,7 @@ class TranslationSettingsSection extends StatelessWidget { ), ); } catch (error) { - if (!context.mounted) return; + if (!mounted) return; showDismissibleSnackBar( context, content: Text( @@ -421,17 +465,36 @@ class TranslationSettingsSection extends StatelessWidget { } } - String _downloadedModelLabel( - BuildContext context, - TranslationModelRecord model, - ) { - final sizeMb = model.fileSizeBytes / (1024 * 1024); - final source = model.sourceUrl.isEmpty ? model.name : model.sourceUrl; - return context.l10n.translation_downloadedModelDetails( - sizeMb.toStringAsFixed(1), - source, + String _displayName(String sourceUrl, String? fileName, String? id) { + for (final preset in translationPresetModels) { + if (preset.id == id || preset.sourceUrl == sourceUrl) { + return translationModelFriendlyName(preset); + } + } + final name = (fileName != null && fileName.isNotEmpty) + ? fileName + : _fileNameFromUrl(sourceUrl); + return translationModelFriendlyName( + TranslationModelRecord( + id: id ?? name, + name: name, + sourceUrl: sourceUrl, + localPath: '', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(0), + fileSizeBytes: 0, + ), ); } + + String _fileNameFromUrl(String sourceUrl) { + final uri = Uri.tryParse(sourceUrl); + if (uri == null || uri.pathSegments.isEmpty) { + return context.l10n.translation_defaultModelName; + } + final last = uri.pathSegments.last.trim(); + if (last.isEmpty) return context.l10n.translation_defaultModelName; + return last; + } } /// Owns the [TextEditingController] for the manual model URL field so it @@ -441,21 +504,15 @@ class _TranslationUrlField extends StatefulWidget { required this.initialValue, required this.onChanged, required this.onDownload, - required this.downloadLabel, - required this.isDownloading, - required this.onCancel, required this.labelText, - required this.stopLabel, + required this.downloadTooltip, }); final String initialValue; final ValueChanged onChanged; final void Function(String url)? onDownload; - final String downloadLabel; - final bool isDownloading; - final VoidCallback onCancel; final String labelText; - final String stopLabel; + final String downloadTooltip; @override State<_TranslationUrlField> createState() => _TranslationUrlFieldState(); @@ -478,39 +535,26 @@ class _TranslationUrlFieldState extends State<_TranslationUrlField> { @override Widget build(BuildContext context) { - return Column( - children: [ - TextField( - controller: _controller, - decoration: InputDecoration( - labelText: widget.labelText, - border: const OutlineInputBorder(), - ), - onChanged: widget.onChanged, + return TextField( + controller: _controller, + keyboardType: TextInputType.url, + autocorrect: false, + enableSuggestions: false, + decoration: InputDecoration( + labelText: widget.labelText, + border: const OutlineInputBorder(), + suffixIcon: IconButton( + tooltip: widget.downloadTooltip, + onPressed: widget.onDownload == null + ? null + : () => widget.onDownload!(_controller.text.trim()), + icon: const Icon(Icons.download_outlined), ), - const SizedBox(height: 8), - Row( - children: [ - Expanded( - child: FilledButton.icon( - onPressed: widget.onDownload == null - ? null - : () => widget.onDownload!(_controller.text.trim()), - icon: const Icon(Icons.download), - label: Text(widget.downloadLabel), - ), - ), - if (widget.isDownloading) ...[ - const SizedBox(width: 8), - OutlinedButton.icon( - onPressed: widget.onCancel, - icon: const Icon(Icons.stop_circle_outlined), - label: Text(widget.stopLabel), - ), - ], - ], - ), - ], + ), + onChanged: widget.onChanged, + onSubmitted: widget.onDownload == null + ? null + : (value) => widget.onDownload!(value.trim()), ); } } diff --git a/test/widgets/model_download_list_test.dart b/test/widgets/model_download_list_test.dart new file mode 100644 index 00000000..def521b1 --- /dev/null +++ b/test/widgets/model_download_list_test.dart @@ -0,0 +1,302 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/models/translation_support.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/image_codec_settings_store.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/image_codec_models_section.dart'; +import 'package:meshcore_open/widgets/model_download_list.dart'; +import 'package:meshcore_open/widgets/translation_settings_section.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + Future pump( + WidgetTester tester, + Widget home, { + List providers = const [], + double textScale = 1, + Size size = const Size(400, 900), + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final app = MaterialApp( + theme: MeshTheme.dark(), + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: Scaffold(body: SingleChildScrollView(child: home)), + ); + await tester.pumpWidget( + providers.isEmpty ? app : MultiProvider(providers: providers, child: app), + ); + } + + testWidgets('rows share name, size, status and one action', (tester) async { + var downloaded = 0; + var cancelled = 0; + var removed = 0; + var selected = 0; + await pump( + tester, + ModelDownloadList( + items: [ + ModelDownloadItem( + id: 'new', + name: 'Preset model', + sizeBytes: 958 * 1024 * 1024, + status: ModelDownloadStatus.notDownloaded, + onDownload: () => downloaded++, + ), + ModelDownloadItem( + id: 'busy', + name: 'Preset model', + sizeBytes: 958 * 1024 * 1024, + status: ModelDownloadStatus.downloading, + progress: 0.4, + downloadedBytes: 400 * 1024 * 1024, + totalBytes: 958 * 1024 * 1024, + onCancel: () => cancelled++, + ), + ModelDownloadItem( + id: 'ready', + name: 'Installed model', + sizeBytes: 1100 * 1024 * 1024, + status: ModelDownloadStatus.ready, + selected: true, + onDelete: () => removed++, + onSelect: () => selected++, + ), + ModelDownloadItem( + id: 'bad', + name: 'Broken model', + status: ModelDownloadStatus.error, + detail: 'HTTP 404', + onDownload: () => downloaded++, + ), + ], + ), + ); + + expect(find.textContaining('958 MB'), findsWidgets); + expect(find.textContaining('Not downloaded'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + expect(find.textContaining('Ready'), findsOneWidget); + expect(find.textContaining('Active'), findsOneWidget); + expect(find.textContaining("Couldn't download"), findsOneWidget); + expect(find.text('HTTP 404'), findsOneWidget); + expect(find.textContaining('400.0 / 958.0 MB (40%)'), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + expect(find.textContaining('http'), findsNothing); + + await tester.tap(find.byKey(const ValueKey('model-download-new'))); + await tester.tap(find.byKey(const ValueKey('model-cancel-busy'))); + await tester.tap(find.byKey(const ValueKey('model-remove-ready'))); + await tester.tap(find.text('Installed model')); + expect(downloaded, 1); + expect(cancelled, 1); + expect(removed, 1); + // The ready row is already selected, so onSelect is still wired here and + // the row tap invokes it. Callers omit onSelect once it is active. + expect(selected, 1); + }); + + testWidgets('a long row wraps at 320dp and text scale 2', (tester) async { + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + if (details.exceptionAsString().contains('overflowed')) { + overflows.add(details.exceptionAsString().split('\n').first); + return; + } + previous?.call(details); + }; + addTearDown(() => FlutterError.onError = previous); + + await pump( + tester, + ModelDownloadList( + items: [ + ModelDownloadItem( + id: 'long', + name: 'Tencent HY-MT 1.5 1.8B Q4_K_M', + sizeBytes: 1140000000, + status: ModelDownloadStatus.downloading, + progress: 0.2, + downloadedBytes: 200 * 1024 * 1024, + totalBytes: 1140000000, + onCancel: () {}, + ), + ], + ), + textScale: 2, + size: const Size(320, 568), + ); + expect(overflows, isEmpty); + expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget); + }); + + testWidgets('translation presets and installs share one list', ( + tester, + ) async { + final settings = AppSettingsService(); + await settings.loadSettings(); + final preset = translationPresetModels.first; + final other = translationPresetModels[1]; + await settings.setTranslationDownloadedModels([ + TranslationModelRecord( + id: preset.id, + name: preset.name, + sourceUrl: preset.sourceUrl, + localPath: '/tmp/model.gguf', + downloadedAt: DateTime.utc(2026, 1, 1), + fileSizeBytes: 1140000000, + ), + TranslationModelRecord( + id: other.id, + name: other.name, + sourceUrl: other.sourceUrl, + localPath: '/tmp/other.gguf', + downloadedAt: DateTime.utc(2026, 1, 2), + fileSizeBytes: 1400 * 1024 * 1024, + ), + ]); + await settings.setTranslationSelectedModelId(preset.id); + final translation = TranslationService(settings); + + await pump( + tester, + const TranslationSettingsSection(), + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: translation), + ], + ); + + expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget); + expect(find.text('Tencent HY-MT 1.5 1.8B Q6_K'), findsOneWidget); + expect(find.textContaining('Ready'), findsNWidgets(2)); + expect(find.textContaining('Active'), findsOneWidget); + expect(find.textContaining('Not downloaded'), findsNothing); + expect(find.text('Downloaded model'), findsNothing); + expect(find.text('Preset Hugging Face model'), findsNothing); + expect(find.text('Manual model URL'), findsOneWidget); + expect(find.textContaining('huggingface.co'), findsNothing); + expect(find.textContaining('.gguf'), findsNothing); + + await tester.tap(find.text('Tencent HY-MT 1.5 1.8B Q6_K')); + await tester.pump(); + expect(settings.settings.translationSelectedModelId, other.id); + + await tester.tap(find.byKey(ValueKey('model-remove-${preset.id}'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + expect( + settings.settings.translationDownloadedModels.map((model) => model.id), + [other.id], + ); + expect(find.textContaining('Not downloaded'), findsOneWidget); + }); + + testWidgets('an installed image bundle is one ready row', (tester) async { + final spec = imageCodecPresetModels.single; + final settings = AppSettingsService(); + final store = InMemoryImageCodecSettingsStore( + ImageCodecPreferences( + enabled: true, + selectedModelId: spec.id, + downloadedModels: [ + ImageCodecModelRecord( + id: spec.id, + name: spec.fileName, + sourceUrl: spec.graph.sourceUrl, + localPath: '/tmp/${spec.fileName}', + downloadedAt: DateTime.utc(2026, 1, 1), + fileSizeBytes: spec.totalSizeBytes, + assetFileNames: [for (final asset in spec.assets) asset.fileName], + assetRoles: { + for (final asset in spec.assets) asset.fileName: asset.role, + }, + bundleVersion: kImageCodecBundleVersion, + ), + ], + ), + ); + final codec = ImageCodecService(settings, settingsStore: store); + + await pump( + tester, + const ImageCodecModelsSection(), + providers: [ + ChangeNotifierProvider.value(value: codec), + ], + ); + + expect(find.text(spec.label), findsOneWidget); + expect(find.textContaining(spec.fileName), findsNothing); + expect(find.textContaining('.onnx'), findsNothing); + expect(find.textContaining('958 MB'), findsOneWidget); + expect(find.textContaining('Ready'), findsOneWidget); + expect(find.textContaining('Active'), findsOneWidget); + expect(find.byTooltip('Remove model'), findsOneWidget); + expect(find.byTooltip('Download'), findsNothing); + }); + + testWidgets('a partial image bundle stays on the preset row', (tester) async { + final spec = imageCodecPresetModels.single; + final settings = AppSettingsService(); + final store = InMemoryImageCodecSettingsStore( + ImageCodecPreferences( + enabled: true, + downloadedModels: [ + ImageCodecModelRecord( + id: spec.id, + name: spec.fileName, + sourceUrl: spec.graph.sourceUrl, + localPath: '/tmp/${spec.fileName}', + downloadedAt: DateTime.utc(2026, 1, 1), + fileSizeBytes: spec.graph.sizeBytes, + assetFileNames: [spec.fileName], + bundleVersion: 0, + ), + ], + ), + ); + final codec = ImageCodecService(settings, settingsStore: store); + + await pump( + tester, + const ImageCodecModelsSection(), + providers: [ + ChangeNotifierProvider.value(value: codec), + ], + ); + + expect(find.text(spec.label), findsOneWidget); + expect(find.textContaining(spec.fileName), findsNothing); + expect(find.textContaining('Incomplete'), findsOneWidget); + expect(find.byTooltip('Download'), findsOneWidget); + expect(find.byTooltip('Remove model'), findsOneWidget); + }); +} diff --git a/untranslated.json b/untranslated.json index 75375aac..bd211125 100644 --- a/untranslated.json +++ b/untranslated.json @@ -12,7 +12,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "cs": [ @@ -28,7 +35,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "de": [ @@ -44,7 +58,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "es": [ @@ -60,7 +81,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "fr": [ @@ -76,7 +104,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "hu": [ @@ -92,7 +127,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "it": [ @@ -108,7 +150,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "ja": [ @@ -124,7 +173,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "ko": [ @@ -140,7 +196,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "nl": [ @@ -156,7 +219,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "pl": [ @@ -172,7 +242,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "pt": [ @@ -188,7 +265,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "pt_PT": [ @@ -204,7 +288,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "ru": [ @@ -220,7 +311,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "sk": [ @@ -236,7 +334,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "sl": [ @@ -252,7 +357,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "sv": [ @@ -268,7 +380,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "uk": [ @@ -284,7 +403,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "zh": [ @@ -300,187 +426,7 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "cs": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "de": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "es": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "fr": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "hu": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "it": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "ja": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "ko": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "nl": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "pl": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "pt": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "pt_PT": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "ru": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "sk": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "sl": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "sv": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "uk": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "zh": [ + "settings_exportBookmarksNoBookmarks", "receivedImage_packetEchoes", "receivedImage_recoveryPacketEchoes", "imageSend_preparingPreview", From 05ebecd977d1c3284fc358a322bc1aed0998bd55 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 00:14:51 +0000 Subject: [PATCH 15/50] Keep a custom model download visible after leaving settings The in-progress URL lived only in the settings page, so reopening App Settings hid the progress and Cancel control while the download continued. The service now keeps the URL and file name, and the list rebuilds that row from it. Co-authored-by: zjs81 --- lib/services/translation_service.dart | 65 ++++++++++++--- lib/widgets/translation_settings_section.dart | 81 +++++++++++++------ test/widgets/model_download_list_test.dart | 55 +++++++++++++ 3 files changed, 163 insertions(+), 38 deletions(-) diff --git a/lib/services/translation_service.dart b/lib/services/translation_service.dart index 909d49fd..1688203b 100644 --- a/lib/services/translation_service.dart +++ b/lib/services/translation_service.dart @@ -61,6 +61,9 @@ class TranslationService extends ChangeNotifier { int _downloadedBytes = 0; int? _downloadTotalBytes; String? _downloadFileName; + String? _downloadTargetFileName; + String? _downloadSourceUrl; + String? _downloadModelId; bool get isBusy => _isBusy; bool get isDownloading => _isDownloading; @@ -68,6 +71,17 @@ class TranslationService extends ChangeNotifier { int get downloadedBytes => _downloadedBytes; int? get downloadTotalBytes => _downloadTotalBytes; String? get downloadFileName => _downloadFileName; + + /// File being fetched. Stays set while chunks are merged, when + /// [downloadFileName] is replaced with the merge status. + String? get downloadTargetFileName => _downloadTargetFileName; + + /// URL of the download in progress. Settings can rebuild the row after + /// the page that started the download has been disposed. + String? get downloadSourceUrl => _downloadSourceUrl; + + /// Preset id when the download was started as a preset, otherwise null. + String? get downloadModelId => _downloadModelId; double? get downloadProgress { final total = _downloadTotalBytes; if (!_isDownloading || total == null || total <= 0) { @@ -195,20 +209,23 @@ class TranslationService extends ChangeNotifier { } return _runExclusive(() async { _setBusy(true); - _setDownloading(true); _lastError = null; + final resolvedFileName = + fileName ?? + _sanitizeFileName( + uri.pathSegments.isNotEmpty + ? uri.pathSegments.last + : 'translation-model.gguf', + ); + _downloadSourceUrl = sourceUrl; + _downloadModelId = id; + _downloadTargetFileName = resolvedFileName; + _downloadFileName = resolvedFileName; + _downloadedBytes = 0; + _downloadTotalBytes = null; + _cancelDownloadRequested = false; + _setDownloading(true); try { - final resolvedFileName = - fileName ?? - _sanitizeFileName( - uri.pathSegments.isNotEmpty - ? uri.pathSegments.last - : 'translation-model.gguf', - ); - _downloadFileName = resolvedFileName; - _downloadedBytes = 0; - _cancelDownloadRequested = false; - // HEAD request to check size and range support. final headClient = http.Client(); int? totalSize; @@ -701,6 +718,27 @@ class TranslationService extends ChangeNotifier { _notify(); } + /// Puts the service in the same state [downloadModel] publishes while a + /// fetch is running, so settings can be rebuilt without a network call. + @visibleForTesting + void debugSetActiveDownload({ + required String sourceUrl, + String? fileName, + String? modelId, + String? displayedFileName, + int downloadedBytes = 0, + int? totalBytes, + }) { + _downloadSourceUrl = sourceUrl; + _downloadModelId = modelId; + _downloadTargetFileName = fileName; + _downloadFileName = displayedFileName ?? fileName; + _downloadedBytes = downloadedBytes; + _downloadTotalBytes = totalBytes; + _isDownloading = true; + _notify(); + } + void _setDownloading(bool value) { _isDownloading = value; if (!value) { @@ -708,6 +746,9 @@ class TranslationService extends ChangeNotifier { _downloadedBytes = 0; _downloadTotalBytes = null; _downloadFileName = null; + _downloadTargetFileName = null; + _downloadSourceUrl = null; + _downloadModelId = null; } _notify(); } diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart index 9d68c26f..fc0ac2cb 100644 --- a/lib/widgets/translation_settings_section.dart +++ b/lib/widgets/translation_settings_section.dart @@ -236,14 +236,10 @@ class _TranslationModelsState extends State<_TranslationModels> { required TranslationModelRecord? installed, }) { if (installed != null) used.add(installed); - final currentFile = service.downloadFileName; - final fileMatches = - currentFile != null && - currentFile != _mergingChunksFileName && - (currentFile == fileName || currentFile == installed?.name); final downloading = service.isDownloading && - (targets(id, sourceUrl, name) || fileMatches); + (targets(id, sourceUrl, name) || + _fileNamesThisDownload(service, fileName, installed?.name)); final failed = !downloading && _failedId == id; if (downloading || failed) pendingShown = true; final merging = downloading && _isMerging(service); @@ -335,34 +331,22 @@ class _TranslationModelsState extends State<_TranslationModels> { ); } - if (pending != null && - !pendingShown && - (service.isDownloading || _failedId == pending.id)) { - final downloading = service.isDownloading; - final merging = downloading && _isMerging(service); + if (!pendingShown && service.isDownloading) { + items.add(_inProgressItem(l10n, service)); + } else if (pending != null && !pendingShown && _failedId == pending.id) { items.add( ModelDownloadItem( id: pending.id, name: pending.name, - status: downloading - ? ModelDownloadStatus.downloading - : ModelDownloadStatus.error, - detail: merging - ? l10n.translation_mergingChunks - : downloading + status: ModelDownloadStatus.error, + detail: _failedDetail, + onDownload: service.isBusy ? null - : _failedDetail, - progress: downloading && !merging ? service.downloadProgress : null, - downloadedBytes: downloading ? service.downloadedBytes : 0, - totalBytes: downloading ? service.downloadTotalBytes : null, - onCancel: downloading ? service.cancelDownload : null, - onDownload: !service.isBusy && !downloading - ? () => _download( + : () => _download( sourceUrl: pending.sourceUrl, fileName: pending.fileName, id: pending.modelId, - ) - : null, + ), ), ); } @@ -370,6 +354,51 @@ class _TranslationModelsState extends State<_TranslationModels> { return items; } + /// True when this row is the file [service] is fetching, including while + /// its displayed filename is the merge status. + bool _fileNamesThisDownload( + TranslationService service, + String? fileName, + String? installedName, + ) { + bool matches(String? candidate) { + if (candidate == null || candidate.isEmpty) return false; + if (candidate == _mergingChunksFileName) return false; + return candidate == fileName || candidate == installedName; + } + + return matches(service.downloadFileName) || + matches(service.downloadTargetFileName); + } + + /// Row for a download whose page state was discarded, or that has no + /// preset or installed row yet. The service keeps the URL and file name. + ModelDownloadItem _inProgressItem( + AppLocalizations l10n, + TranslationService service, + ) { + final sourceUrl = service.downloadSourceUrl ?? ''; + final rawName = service.downloadTargetFileName ?? service.downloadFileName; + final fileName = rawName == _mergingChunksFileName ? null : rawName; + final modelId = service.downloadModelId; + final id = (modelId != null && modelId.isNotEmpty) + ? modelId + : sourceUrl.isNotEmpty + ? sourceUrl + : (fileName ?? 'download'); + final merging = _isMerging(service); + return ModelDownloadItem( + id: id, + name: _displayName(sourceUrl, fileName, modelId), + status: ModelDownloadStatus.downloading, + detail: merging ? l10n.translation_mergingChunks : null, + progress: merging ? null : service.downloadProgress, + downloadedBytes: service.downloadedBytes, + totalBytes: service.downloadTotalBytes, + onCancel: service.cancelDownload, + ); + } + bool _isMerging(TranslationService service) => service.downloadFileName == _mergingChunksFileName; diff --git a/test/widgets/model_download_list_test.dart b/test/widgets/model_download_list_test.dart index def521b1..4734bcad 100644 --- a/test/widgets/model_download_list_test.dart +++ b/test/widgets/model_download_list_test.dart @@ -219,6 +219,61 @@ void main() { expect(find.textContaining('Not downloaded'), findsOneWidget); }); + testWidgets('a custom download stays visible after settings is reopened', ( + tester, + ) async { + final settings = AppSettingsService(); + await settings.loadSettings(); + final translation = TranslationService(settings); + addTearDown(translation.dispose); + // The page that started the download is gone. Only the service still + // knows which file is in flight. + translation.debugSetActiveDownload( + sourceUrl: 'http://127.0.0.1/Tencent-demo.gguf', + fileName: 'Tencent-demo.gguf', + downloadedBytes: 400 * 1024, + totalBytes: 1024 * 1024, + ); + + final providers = [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: translation), + ]; + await pump( + tester, + const TranslationSettingsSection(), + providers: providers, + ); + expect(find.text('Tencent-demo'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + expect(find.textContaining('0.4 / 1.0 MB (39%)'), findsOneWidget); + expect(find.byTooltip('Cancel'), findsOneWidget); + + await pump(tester, const SizedBox.shrink(), providers: providers); + await pump( + tester, + const TranslationSettingsSection(), + providers: providers, + ); + expect(find.text('Tencent-demo'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + expect(find.byTooltip('Cancel'), findsOneWidget); + expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget); + + final preset = translationPresetModels.first; + translation.debugSetActiveDownload( + sourceUrl: preset.sourceUrl, + fileName: preset.name, + modelId: preset.id, + displayedFileName: 'Merging chunks...', + ); + await tester.pump(); + expect(find.text('Tencent-demo'), findsNothing); + expect(find.textContaining('Downloading'), findsOneWidget); + expect(find.textContaining('Merging downloaded chunks'), findsOneWidget); + expect(find.byTooltip('Cancel'), findsOneWidget); + }); + testWidgets('an installed image bundle is one ready row', (tester) async { final spec = imageCodecPresetModels.single; final settings = AppSettingsService(); From 1b804bd1eb2d53a89fcfc7a85a2fb4feed87f864 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 00:50:53 +0000 Subject: [PATCH 16/50] Move send controls into Routing and split retry limits Direct and flood attempts are separate settings, available with auto route rotation off. Saved single retry limits migrate to that split, and reset restores the whole Routing section. Co-authored-by: zjs81 --- documentation/additional-features.md | 15 +- documentation/channels.md | 2 +- documentation/chat-and-messaging.md | 10 +- documentation/design.md | 15 +- documentation/routing-paths.md | 2 +- documentation/settings.md | 16 +- lib/connector/meshcore_connector.dart | 20 +- lib/l10n/app_bg.arb | 20 +- lib/l10n/app_cs.arb | 20 +- lib/l10n/app_de.arb | 20 +- lib/l10n/app_en.arb | 39 +- lib/l10n/app_es.arb | 20 +- lib/l10n/app_fr.arb | 20 +- lib/l10n/app_hu.arb | 20 +- lib/l10n/app_it.arb | 20 +- lib/l10n/app_ja.arb | 20 +- lib/l10n/app_ko.arb | 20 +- lib/l10n/app_localizations.dart | 48 ++- lib/l10n/app_localizations_bg.dart | 39 +- lib/l10n/app_localizations_cs.dart | 39 +- lib/l10n/app_localizations_de.dart | 39 +- lib/l10n/app_localizations_en.dart | 39 +- lib/l10n/app_localizations_es.dart | 39 +- lib/l10n/app_localizations_fr.dart | 39 +- lib/l10n/app_localizations_hu.dart | 39 +- lib/l10n/app_localizations_it.dart | 39 +- lib/l10n/app_localizations_ja.dart | 41 ++- lib/l10n/app_localizations_ko.dart | 39 +- lib/l10n/app_localizations_nl.dart | 39 +- lib/l10n/app_localizations_pl.dart | 39 +- lib/l10n/app_localizations_pt.dart | 78 +++- lib/l10n/app_localizations_ru.dart | 39 +- lib/l10n/app_localizations_sk.dart | 39 +- lib/l10n/app_localizations_sl.dart | 39 +- lib/l10n/app_localizations_sv.dart | 39 +- lib/l10n/app_localizations_uk.dart | 39 +- lib/l10n/app_localizations_zh.dart | 39 +- lib/l10n/app_nl.arb | 20 +- lib/l10n/app_pl.arb | 20 +- lib/l10n/app_pt.arb | 20 +- lib/l10n/app_pt_PT.arb | 20 +- lib/l10n/app_ru.arb | 20 +- lib/l10n/app_sk.arb | 20 +- lib/l10n/app_sl.arb | 20 +- lib/l10n/app_sv.arb | 20 +- lib/l10n/app_uk.arb | 20 +- lib/l10n/app_zh.arb | 20 +- lib/models/app_settings.dart | 44 ++- lib/models/send_attempt_plan.dart | 88 +++++ lib/screens/app_settings_screen.dart | 284 +++++++-------- lib/screens/channels_screen.dart | 8 +- lib/screens/chat_screen.dart | 23 +- lib/screens/filtered_messages_screen.dart | 4 +- lib/screens/scanner_screen.dart | 19 +- lib/screens/settings_screen.dart | 107 +++--- lib/services/app_settings_service.dart | 29 +- lib/services/message_retry_service.dart | 67 +++- lib/services/path_history_service.dart | 13 +- lib/widgets/repeater_login_dialog.dart | 5 +- lib/widgets/room_login_dialog.dart | 5 +- lib/widgets/settings_reveal.dart | 111 ++++++ test/models/model_changes_test.dart | 32 +- test/models/send_attempt_plan_test.dart | 151 ++++++++ .../screens/routing_settings_screen_test.dart | 107 ++++++ .../message_retry_split_limits_test.dart | 168 +++++++++ .../services/message_retry_watchdog_test.dart | 12 +- test/services/path_history_service_test.dart | 31 +- test/services/route_chooser_test.dart | 2 +- untranslated.json | 344 ++++++++---------- 69 files changed, 2199 insertions(+), 784 deletions(-) create mode 100644 lib/models/send_attempt_plan.dart create mode 100644 lib/widgets/settings_reveal.dart create mode 100644 test/models/send_attempt_plan_test.dart create mode 100644 test/screens/routing_settings_screen_test.dart create mode 100644 test/services/message_retry_split_limits_test.dart diff --git a/documentation/additional-features.md b/documentation/additional-features.md index b160577d..86739e68 100644 --- a/documentation/additional-features.md +++ b/documentation/additional-features.md @@ -156,7 +156,7 @@ Maintains an in-memory LRU cache of up to 50 contacts, each with up to 100 route Each route keeps delivery and failure counts that fade over time (half their weight per day, at most 16 recent results). For each send attempt a route is chosen by Thompson sampling over those counts, adjusted slightly for speed and for what the radio currently hears. There are no user-tunable weights. A route is deleted only when it keeps failing and hasn't delivered for a week. Flood deliveries that receive an ACK credit the specific return path. Details: [Auto route selection](routing-paths.md#auto-route-selection). Used internally for: -- **Auto route rotation**: Picks a route for each attempt; retries usually move to a different route, and the last attempt floods +- **Auto route rotation**: Picks a route for each direct attempt; retries usually move to a different route, then the flood attempts run - **Flood statistics**: Tracks flood deliveries and failures --- @@ -167,16 +167,17 @@ Used internally for: Handles reliable delivery of outgoing direct messages: 1. Assigns a UUID and sends immediately. Only one message per contact can be in-flight at a time (avoids overflowing the firmware's 8-entry ACK table); subsequent messages are queued 2. Listens for ACK frames matched via SHA-256 hash of `[timestamp][attempt][text][sender_pubkey]` -3. On timeout, retries with exponential backoff: `1000 × 2^retryCount` ms (1s, 2s, 4s, 8s...) -4. Each retry may use a different path (via path history diversity window) -5. After max retries: marks failed but keeps a **30-second grace window** during which a late ACK can still resolve the message to "delivered". Optionally clears the contact's path +3. On timeout, retries with exponential backoff: `1000 × 2^retryCount` ms (1s, 2s, 4s, 8s...), capped at 32 seconds +4. Each direct retry may use a different path (via path history diversity window) when auto route rotation is on +5. After the configured direct and flood attempts: marks failed but keeps a **30-second grace window** during which a late ACK can still resolve the message to "delivered". Optionally clears the contact's path 6. Reports RTT and path data for quality learning 7. Maintains an ACK hash history (last 50 entries) to handle duplicate ACKs -### Configurable Settings (App Settings → Messaging) -- Max retries (2–10, default 5) +### Configurable Settings (App Settings → Routing) +- Direct attempts (0–15, default 4) and flood attempts (0–10, default 1), set separately from auto route rotation +- Login attempts for a repeater or room server (1–10, default 5). Telemetry requests are not retried - Clear path on max retry (on/off) -- Auto route rotation with weight parameters +- Auto route rotation --- diff --git a/documentation/channels.md b/documentation/channels.md index a8ce6641..4830c666 100644 --- a/documentation/channels.md +++ b/documentation/channels.md @@ -124,7 +124,7 @@ The app bar overflow menu (⋮) has **Filter messages in this channel** (shown w ### Channel Auto-Resend -With **Resend channel messages until they travel far enough** on (App Settings → Messaging), the app waits after each channel send and checks how far the message was heard repeated. If no repeat reached the required hop count, it sends the message again, up to the configured number of times. +With **Resend channel messages until they travel far enough** on (App Settings → Routing), the app waits after each channel send and checks how far the message was heard repeated. If no repeat reached the required hop count, it sends the message again, up to the configured number of times. Where your radio only hears nearby repeaters, turn on **Also count different nearby repeaters**: the message then also counts as sent once the required number of *different* first-hop repeaters have repeated it, across all attempts. Your own radio's echo and zero-hop echoes don't count. diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 53a47331..2a3aaa0c 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -102,11 +102,11 @@ When a direct message is sent: 1. The app computes an expected ACK hash: `SHA256([timestamp][attempt][text][selfPubKey])[0:4]` — matching the firmware's hash calculation. If SMAZ compression is enabled, the compressed text (not the original) is hashed 2. On device acknowledgment (`RESP_CODE_SENT`), the message transitions to "sent" and a timeout timer starts. If that acknowledgment never arrives (for example a dropped BLE notification), a backup timer (the delivery timeout plus 5 seconds) runs the normal retry path instead of leaving the message pending; a late ACK still marks it delivered 3. **Timeout duration**: Preferably from the ML timeout prediction service; otherwise from the device's own `est_timeout` in `RESP_CODE_SENT` (clamped to the physics range); otherwise calculated from LoRa airtime physics: `500 + (airtime × 6 + 250) × (pathLength + 1)` ms for direct paths, `500 + 16 × airtime` ms for flood (airtime is estimated from the radio's current spreading factor, bandwidth, and coding rate). The result is capped at 45 seconds. -4. On timeout, the message is retried with **exponential backoff**: `1000 × 2^retryCount` ms (1s, 2s, 4s, 8s, 16s...) -5. **Max retries**: Configurable (default 5, range 2–10) -6. After max retries, the message is marked "failed" — but a **30-second grace window** remains during which a late ACK can still resolve the message to "delivered" -7. If **Clear Path on Max Retry** is enabled (App Settings), the contact's stored routing path is automatically cleared when max retries are exhausted -8. **Auto route rotation**: When enabled (and no manual path override is set), the retry service uses a diversity window to avoid re-using recently tried paths, cycling through known routes on each attempt +4. On timeout, the message is retried with **exponential backoff**: `1000 × 2^retryCount` ms (1s, 2s, 4s, 8s, 16s...), capped at 32 seconds +5. **Direct and flood attempts**: Set separately in App Settings → Routing (defaults 4 direct and 1 flood; up to 15 direct and 10 flood). With auto route rotation on, the direct attempts use known routes and the flood attempts follow. With it off, every attempt stays on the contact's current path and only that path's limit applies. Zero on both still sends once +6. After those attempts, the message is marked "failed" — but a **30-second grace window** remains during which a late ACK can still resolve the message to "delivered" +7. If **Clear Path on Max Retry** is enabled (App Settings → Routing), the contact's stored routing path is automatically cleared when the attempts are exhausted +8. **Auto route rotation**: When enabled (and no manual path override is set), the retry service uses a diversity window to avoid re-using recently tried paths, cycling through known routes on each direct attempt. Flood attempts come after those ### Manual Retry diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..7047e0c6 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -2,7 +2,7 @@ How MeshCore Open's interface is built today, and the rules to follow when adding or changing UI. Every value below comes from the code it cites. If you change one of those sources, or settle on a new pattern, update this page in the same change. -The source of truth is `lib/theme/mesh_theme.dart` (theme), `lib/widgets/mesh_ui.dart` (shared widgets) and `lib/widgets/mesh_nav_tile.dart` (settings rows). Where the code disagrees with this page, fix one of them; do not copy the inconsistency. +The source of truth is `lib/theme/mesh_theme.dart` (theme), `lib/widgets/mesh_ui.dart` (shared widgets), `lib/widgets/settings_reveal.dart` (reveal-on-enable and settings sliders) and `lib/widgets/mesh_nav_tile.dart` (settings rows). Where the code disagrees with this page, fix one of them; do not copy the inconsistency. ## 1. Principles @@ -117,6 +117,8 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Label above a group | `SectionHeader(label, trailing:)` | Upper-cases for you; pass the normal-case l10n string | | Settings navigation row | `MeshNavTile` | `onTap: null` dims it to 50 % and reports it as disabled; use `subtitle` to say why | | Settings switch | `SwitchListTile` inside `MeshSettingsTileTheme` | Wrap the settings screen body once in `MeshSettingsTileTheme` | +| Switch that reveals more controls | `SettingsReveal` | 200ms height ease, `surfaceContainerHighest`, 16px start indent. See [Reveal on enable](#reveal-on-enable) | +| Settings slider | `SettingsValueSlider` | The title includes the selected number, so it stays visible. The drag bubble repeats it | | Radio-style choice in a sheet | `MeshSheetOption` | Used by the language picker and map time filter | | Choosing between images | Selectable thumbnail tiles in a centred `Wrap` | Image send versions (`_versionTile` in `image_send_preview_sheet.dart`). `InkWell` with `MeshRadii.sm`; selected tile gets a 3px `primary` border **and** a `primary` check badge (never colour alone); caption under the tile in `bodySmall`, w600 when selected; figures such as packet counts in `MeshTheme.mono` 12; wrap the tile in `Semantics(button: true, selected:, label:)` | | Popup menu row | **always** `PopupMenuItem(child: MeshMenuItemRow(icon:, label:))` | Label wraps to 2 lines then ellipsizes; `leading:` for `ThemedIcon`; no icon keeps the 20px slot | @@ -147,6 +149,16 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act **IconButton.** Always set `tooltip:` with a localized string. It is the accessible name. +### Reveal on enable + +A switch that uncovers more controls uses `SettingsReveal` (`lib/widgets/settings_reveal.dart`). The block's height eases over 200ms (`RevealOnEnable.duration`, `Curves.easeInOut`, aligned to the top). While the switch is off the extra controls are not in the tree, so they are not announced. The panel uses `surfaceContainerHighest` and a 16px start indent. + +The same animation without the tint is `RevealOnEnable`. Use it when the revealed control is not a settings sub-panel: the Cyrillic-to-Latin profile picker, the Bluetooth-off banner on the scanner, and the device-info rows on the Settings screen. + +Do not add a second duration, and do not reveal the controls with a plain `if` that pops them in. A block that swaps between two bodies, such as the filtered-message preview, keeps `AnimatedSize` but uses `RevealOnEnable.duration` and `RevealOnEnable.curve`. + +Sliders that belong to a setting use `SettingsValueSlider`. Put the selected number in the title (a localized string with the count). The slider's drag label repeats that number; it is not the only place the value appears. + ## 6. Sheets, dialogs and pages What the code does: @@ -216,6 +228,7 @@ Follow the same pattern for any new remote-value screen. - [ ] Colours from `colorScheme` or theme extensions; no raw `Colors.*` or `MeshPalette.ink/bg/line` in chrome. - [ ] Text styles from `textTheme` or `MeshTheme.mono`; nothing below 12. - [ ] Settings rows use `MeshNavTile` / `SwitchListTile` inside `MeshSettingsTileTheme`; cards are `MeshCard` with a `SectionHeader`. +- [ ] A switch that reveals more controls uses `SettingsReveal`. A settings slider uses `SettingsValueSlider` so the selected value stays in the title. - [ ] Popup menu rows use `MeshMenuItemRow`; segmented buttons use `MeshSegmentLabel`; destructive menu items last, in `scheme.error`. - [ ] Every `IconButton` and FAB has a localized `tooltip`. - [ ] Tap targets at least 48×48. diff --git a/documentation/routing-paths.md b/documentation/routing-paths.md index 74548258..131b5b1c 100644 --- a/documentation/routing-paths.md +++ b/documentation/routing-paths.md @@ -55,7 +55,7 @@ Contacts/messages persist hop count, path bytes, and width. Legacy contact recor - **Faded stats:** each route keeps delivery and failure counts that lose half their weight every 24 hours (`routeStatsHalfLife`), so recent behaviour outweighs old. - **Thompson sampling:** for each attempt, a plausible delivery rate is drawn for every route from its faded counts and the best draw wins. Proven routes win most of the time; untested or recovering routes are still tried occasionally. Speed adjusts the score slightly. - **Context:** `MeshCoreConnector.routeContextFor` reports what the radio heard in the last two hours (advertisers heard directly and the last hop of relayed adverts). Routes whose first hop was heard — or the direct route, when the contact itself was heard directly — score higher; routes that don't fit score lower. Not hearing a repeater is weak evidence, so nothing is excluded. With nothing heard, context has no effect. -- **Retries** halve the score of routes already tried for the same message, so they usually try something different without wasting an attempt on a much weaker route. The final attempt always floods. +- **Retries** halve the score of routes already tried for the same message, so they usually try something different without wasting an attempt on a much weaker route. Direct attempts use a known route. Once those are used up, the remaining attempts flood (`SendAttemptPlan.floodFromAttempt`). With flood attempts set to 0, a send never switches to flood. - **Offline contacts:** `MessageRetryService` holds a message's route failures until its fate is known. If any attempt is acknowledged, the routes that timed out are blamed; if nothing gets through, the contact was probably unreachable and no route is blamed. - **Forgetting:** a failing route is deleted only after it hasn't delivered for a week, so a repeater that is down for a day is still known when it returns. - Route picks and their results are written to the app debug log under the `Routing` tag. diff --git a/documentation/settings.md b/documentation/settings.md index 3f101f07..2efb4be9 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -119,18 +119,26 @@ A dedicated sub-screen for app-level preferences (nothing here is sent to the de Individual channels can be muted from the channel chat bell icon, the channel list, or the channel notification. Replying from notifications, watches, and Android Auto is described in [Notifications](notifications.md). ### Messaging -- **Clear Path on Max Retry**: Erases the stored routing path after all retries fail - **Jump to Oldest Unread**: When opening a chat, scrolls to the oldest unread message instead of the newest - **Auto-fetch Repeater Settings** (off by default): Requests every setting when a repeater's settings screen opens. Each setting is a separate request over LoRa, so this is slow and uses airtime; when off, use Refresh All or the per-setting refresh buttons. See [Repeater Settings](repeater-management.md#repeater-settings) -- **Auto Route Rotation**: Lets the app choose each message's route from the routes that have worked for that contact (see [Auto route selection](routing-paths.md#auto-route-selection)). When enabled, it expands (hidden when off) to show: - - Max Message Retries (2–10, default 5) - - **Reset Routing Algorithm to Default**: Restores the routing settings to their factory defaults - **Enable Message Tracing**: Shows path trace overlays and extra metadata on messages - **Region next to hop count** (default off): Shows a channel message's region chip on the same line as its hop count instead of below it + +### Routing +What happens when a message is sent. Each slider shows its selected number in the title. Turning a switch on reveals its extra controls with the same animation. + +- **Clear Path on Max Retry**: Erases the stored routing path after every send attempt fails +- **Direct attempts** (0–15, default 4): How many times to try a known route. Available whether or not auto route rotation is on +- **Flood attempts** (0–10, default 1): How many times to flood. Floods use more airtime. With rotation on, these run after the direct attempts. With it off, they apply only when the contact's path is already Flood +- **Login attempts** (1–10, default 5): How many times to try logging in to a repeater or room server. Telemetry fetches are sent once and have no retry setting +- **Auto Route Rotation**: Lets the app choose each direct attempt's route from the routes that have worked for that contact (see [Auto route selection](routing-paths.md#auto-route-selection)). Off keeps the contact's current path for every attempt - **Resend channel messages until they travel far enough** (default off): If your channel message isn't heard coming back through enough repeaters, it's sent again. Uses more airtime. When on, it shows: - Required hops (1–8, default 2) - Resend up to (1–5 times, default 1) - **Also count different nearby repeaters** (default off): Treats the message as sent once that many *different* first-hop repeaters have repeated it, even if you can't hear it travel further. Useful where only nearby repeaters are audible. See [Channels](channels.md#channel-auto-resend) +- **Reset routing settings to defaults**: Restores every control in this section (the toggles, the attempt limits, and the stored route-weight constants) to the factory defaults + +If both direct and flood attempts are 0, the message is still sent once on the current path. A saved `max_message_retries` value from an older version becomes that many attempts minus one direct, plus one flood, which keeps the old "last attempt floods" behaviour for the previous default of 5 (4 direct + 1 flood). ### Battery - **Battery Chemistry**: NMC / LiFePO4 / LiPo (per device, used to calibrate percentage from voltage) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index ad9fa57e..9d59570e 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -18,6 +18,7 @@ import '../models/contact.dart'; import '../models/message_filter.dart'; import '../models/message.dart'; import '../models/path_selection.dart'; +import '../models/send_attempt_plan.dart'; import '../models/translation_support.dart'; import '../helpers/reaction_helper.dart'; import '../helpers/channel_resend_coverage.dart'; @@ -2405,11 +2406,11 @@ class MeshCoreConnector extends ChangeNotifier { debugLogService: _appDebugLogService, recordPathResult: _recordPathResult, selectRetryPath: - (contactKey, attemptIndex, maxRetries, recentSelections) => + (contactKey, attemptIndex, directRetries, recentSelections) => _selectAutoPathForAttempt( contactKey, attemptIndex: attemptIndex, - maxRetries: maxRetries, + directRetries: directRetries, recentSelections: recentSelections, ), onDeliveryObserved: (contactKey, pathLength, messageBytes, tripTimeMs) { @@ -2422,8 +2423,6 @@ class MeshCoreConnector extends ChangeNotifier { }, ), ); - final maxRetries = _appSettingsService?.settings.maxMessageRetries ?? 5; - _retryService?.setMaxRetries(maxRetries); } Future loadContactCache() async { @@ -2866,7 +2865,7 @@ class MeshCoreConnector extends ChangeNotifier { PathSelection? _selectAutoPathForAttempt( String contactPubKeyHex, { required int attemptIndex, - required int maxRetries, + required int directRetries, List recentSelections = const [], }) { final hasKnownPaths = @@ -2881,7 +2880,7 @@ class MeshCoreConnector extends ChangeNotifier { final selection = _pathHistoryService?.selectPathForAttempt( contactPubKeyHex, attemptIndex: attemptIndex, - maxRetries: maxRetries, + directRetries: directRetries, recentSelections: recentSelections, context: routeContext, ); @@ -2891,7 +2890,8 @@ class MeshCoreConnector extends ChangeNotifier { // app debug log on a live mesh. _appDebugLogService?.info( 'Route pick for ${contact?.name ?? contactPubKeyHex.substring(0, 8)}: ' - 'attempt ${attemptIndex + 1}/$maxRetries → ${_describeRoute(selection)} ' + 'attempt ${attemptIndex + 1} ' + '→ ${_describeRoute(selection)} ' '(heard nearby: ${routeContext.hasNeighbourInfo}, ' 'contact heard direct: ${routeContext.contactHeardDirectly})', tag: 'Routing', @@ -5442,11 +5442,13 @@ class MeshCoreConnector extends ChangeNotifier { final autoRotationEnabled = _appSettingsService?.settings.autoRouteRotationEnabled == true; if (autoRotationEnabled && contact.pathOverride == null) { - final maxRetries = _appSettingsService?.settings.maxMessageRetries ?? 5; + final directRetries = + _appSettingsService?.settings.directRetries ?? + SendAttemptPlan.defaultDirectRetries; autoSelection = _selectAutoPathForAttempt( contact.publicKeyHex, attemptIndex: 0, - maxRetries: maxRetries, + directRetries: directRetries, ); } diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 913a0815..47ddb12f 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Покажи известие, когато бъдат открити нови възли.", "appSettings_messaging": "Съобщения", "appSettings_clearPathOnMaxRetry": "Изчисти пътя при максимален брой опити", - "appSettings_clearPathOnMaxRetrySubtitle": "Възстанови пътя към контакта след 5 неуспешни опита за изпращане", - "appSettings_pathsWillBeCleared": "Пътищата ще бъдат почистени след 5 неуспешни опита.", + "appSettings_clearPathOnMaxRetrySubtitle": "Нулиране на записания път към контакта, когато всички опити за изпращане се провалят", + "appSettings_pathsWillBeCleared": "Пътищата се изчистват, когато всички опити за изпращане се провалят", "appSettings_pathsWillNotBeCleared": "Пътищата няма да бъдат автоматично изчистени.", "appSettings_autoRouteRotation": "Автоматична ротация на маршрутите", - "appSettings_autoRouteRotationSubtitle": "Превключвайте между най-добрите пътища и режим Flood", + "appSettings_autoRouteRotationSubtitle": "При всеки директен опит се пробва друг известен маршрут. Следващите опити са Flood. Изключено запазва текущия път на контакта.", "appSettings_autoRouteRotationEnabled": "Автоматичната ротация на маршрутите е включена", "appSettings_autoRouteRotationDisabled": "Автоматичната ротация на маршрутите е изключена", "appSettings_battery": "Батерия", @@ -3353,9 +3353,9 @@ "settings_regionFetchNoneResponded": "Нито един близък ретранслатор не отговори. Приближете се до ретранслатор и опитайте отново.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Маршрутизиране", - "appSettings_resetRoutingToDefault": "Нулиране на алгоритъма за маршрутизация до стойност по подразбиране", - "appSettings_resetRoutingToDefaultSubtitle": "Възстановяване на настройките на алгоритъма за маршрутизация до заводските стойности по подразбиране", - "appSettings_routingResetToDefault": "Настройките на алгоритъма за маршрутизация са нулирани до стойност по подразбиране", + "appSettings_resetRoutingToDefault": "Нулиране на настройките за маршрутизация до стойностите по подразбиране", + "appSettings_resetRoutingToDefaultSubtitle": "Възстановяване на настройките за маршрутизация в този раздел до стойностите по подразбиране", + "appSettings_routingResetToDefault": "Настройките за маршрутизация са нулирани до стойностите по подразбиране", "appSettings_imageMessagesSection": "Съобщения с изображения", "appSettings_showApiKey": "Показване на API ключа", "appSettings_hideApiKey": "Скриване на API ключа", @@ -3776,5 +3776,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB или TCP", "connectSheet_stopReconnecting": "Спри повторното свързване", "connectSheet_reconnectFailed": "Няма връзка с {name}. Уверете се, че е включено и наблизо.", - "chat_composerOffline": "Свържете се с радио, за да изпращате съобщения" + "chat_composerOffline": "Свържете се с радио, за да изпращате съобщения", + "appSettings_directRetries": "Директни опити: {count}", + "appSettings_directRetriesSubtitle": "Колко пъти да се пробва известен маршрут. Достъпно и когато автоматичната ротация е изключена.", + "appSettings_floodRetries": "Опити Flood: {count}", + "appSettings_floodRetriesSubtitle": "Колко пъти да се използва Flood. Flood заема повече ефирно време. При включена ротация идват след директните опити.", + "appSettings_loginAttempts": "Опити за вход: {count}", + "appSettings_loginAttemptsSubtitle": "Колко пъти да се опитва вход към ретранслатор или room сървър, преди да се откаже." } diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index f72e9821..1d9843eb 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -549,11 +549,11 @@ "appSettings_advertisementNotificationsSubtitle": "Zobrazit oznámení při objevení nových uzlů", "appSettings_messaging": "Zprávy", "appSettings_clearPathOnMaxRetry": "Vymazat cestu po maximu pokusů", - "appSettings_clearPathOnMaxRetrySubtitle": "Resetovat cestu kontaktu po 5 neúspěšných pokusech o odeslání", - "appSettings_pathsWillBeCleared": "Cesty budou vymazány po 5 neúspěšných pokusech", + "appSettings_clearPathOnMaxRetrySubtitle": "Resetovat uloženou cestu kontaktu, když selžou všechny pokusy o odeslání", + "appSettings_pathsWillBeCleared": "Cesty se vymažou, když selžou všechny pokusy o odeslání", "appSettings_pathsWillNotBeCleared": "Cesty nebudou automaticky mazány", "appSettings_autoRouteRotation": "Automatické střídání tras", - "appSettings_autoRouteRotationSubtitle": "Střídat nejlepší cesty a režim flood", + "appSettings_autoRouteRotationSubtitle": "Při každém přímém pokusu zkusit jinou známou trasu. Pozdější pokusy jsou Flood. Vypnuto ponechá aktuální cestu kontaktu.", "appSettings_autoRouteRotationEnabled": "Automatické střídání tras zapnuto", "appSettings_autoRouteRotationDisabled": "Automatické střídání tras vypnuto", "appSettings_maxMessageRetries": "Maximum opakování zprávy", @@ -3890,9 +3890,9 @@ } }, "appSettings_routingSection": "Směrování", - "appSettings_resetRoutingToDefault": "Obnovit výchozí směrovací algoritmus", - "appSettings_resetRoutingToDefaultSubtitle": "Obnovit nastavení směrovacího algoritmu na tovární hodnoty", - "appSettings_routingResetToDefault": "Nastavení směrovacího algoritmu obnoveno na výchozí", + "appSettings_resetRoutingToDefault": "Obnovit výchozí nastavení směrování", + "appSettings_resetRoutingToDefaultSubtitle": "Obnovit nastavení směrování v této části na výchozí hodnoty", + "appSettings_routingResetToDefault": "Nastavení směrování obnoveno na výchozí", "appSettings_imageMessagesSection": "Obrázkové zprávy", "appSettings_showApiKey": "Zobrazit klíč API", "appSettings_hideApiKey": "Skrýt klíč API", @@ -4389,5 +4389,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB nebo TCP", "connectSheet_stopReconnecting": "Zastavit připojování", "connectSheet_reconnectFailed": "Nelze se spojit s {name}. Ujistěte se, že je zapnuté a nablízku.", - "chat_composerOffline": "Pro odesílání zpráv se připojte k rádiu" + "chat_composerOffline": "Pro odesílání zpráv se připojte k rádiu", + "appSettings_directRetries": "Přímé pokusy: {count}", + "appSettings_directRetriesSubtitle": "Kolikrát se zkusí známá trasa. Dostupné i když je automatické střídání tras vypnuté.", + "appSettings_floodRetries": "Pokusy Flood: {count}", + "appSettings_floodRetriesSubtitle": "Kolikrát se použije Flood. Flood zabere víc vysílacího času. Při zapnutém střídání následují po přímých pokusech.", + "appSettings_loginAttempts": "Pokusy o přihlášení: {count}", + "appSettings_loginAttemptsSubtitle": "Kolikrát se zkusí přihlášení k opakovači nebo room serveru, než se to vzdá." } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 40d00f84..e996a4d4 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Benachrichtigung anzeigen, wenn neue Knoten entdeckt werden", "appSettings_messaging": "Nachrichten", "appSettings_clearPathOnMaxRetry": "Pfad bei maximalen Wiederholungsversuchen löschen", - "appSettings_clearPathOnMaxRetrySubtitle": "Kontaktpfade nach 5 fehlgeschlagenen Sendeversuchen zurücksetzen", - "appSettings_pathsWillBeCleared": "Pfade werden nach 5 fehlgeschlagenen Wiederholungen gelöscht.", + "appSettings_clearPathOnMaxRetrySubtitle": "Gespeicherten Kontaktpfad zurücksetzen, wenn alle Sendeversuche fehlschlagen", + "appSettings_pathsWillBeCleared": "Pfade werden gelöscht, wenn alle Sendeversuche fehlschlagen", "appSettings_pathsWillNotBeCleared": "Pfade werden nicht automatisch gelöscht.", "appSettings_autoRouteRotation": "Automatische Routenrotation", - "appSettings_autoRouteRotationSubtitle": "Zwischen den besten Pfaden und dem Flood-Modus wechseln", + "appSettings_autoRouteRotationSubtitle": "Bei jedem direkten Versuch eine andere bekannte Route nutzen. Die späteren Versuche sind Flood. Aus behält den aktuellen Pfad des Kontakts.", "appSettings_autoRouteRotationEnabled": "Automatische Routenrotation aktiviert", "appSettings_autoRouteRotationDisabled": "Automatische Routenrotation deaktiviert", "appSettings_battery": "Akku", @@ -3488,9 +3488,9 @@ "settings_regionFetchNoneResponded": "Kein Repeater in der Nähe hat geantwortet. Gehe näher an einen Repeater heran und versuche es erneut.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Routing", - "appSettings_resetRoutingToDefault": "Routing-Algorithmus auf Standard zurücksetzen", - "appSettings_resetRoutingToDefaultSubtitle": "Routing-Algorithmus-Einstellungen auf Werkseinstellungen zurücksetzen", - "appSettings_routingResetToDefault": "Routing-Algorithmus-Einstellungen auf Standard zurückgesetzt", + "appSettings_resetRoutingToDefault": "Routing-Einstellungen auf Standard zurücksetzen", + "appSettings_resetRoutingToDefaultSubtitle": "Die Routing-Einstellungen in diesem Abschnitt auf die Standardwerte zurücksetzen", + "appSettings_routingResetToDefault": "Routing-Einstellungen auf Standard zurückgesetzt", "appSettings_imageMessagesSection": "Bildnachrichten", "appSettings_showApiKey": "API-Schlüssel anzeigen", "appSettings_hideApiKey": "API-Schlüssel verbergen", @@ -3911,5 +3911,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB oder TCP", "connectSheet_stopReconnecting": "Wiederverbindung abbrechen", "connectSheet_reconnectFailed": "{name} ist nicht erreichbar. Stellen Sie sicher, dass es eingeschaltet und in der Nähe ist.", - "chat_composerOffline": "Mit einem Funkgerät verbinden, um Nachrichten zu senden" + "chat_composerOffline": "Mit einem Funkgerät verbinden, um Nachrichten zu senden", + "appSettings_directRetries": "Direkte Versuche: {count}", + "appSettings_directRetriesSubtitle": "Wie oft eine bekannte Route versucht wird. Auch verfügbar, wenn die automatische Routenrotation aus ist.", + "appSettings_floodRetries": "Flood-Versuche: {count}", + "appSettings_floodRetriesSubtitle": "Wie oft geflutet wird. Flood verbraucht mehr Sendezeit. Bei eingeschalteter Rotation folgen diese auf die direkten Versuche.", + "appSettings_loginAttempts": "Anmeldeversuche: {count}", + "appSettings_loginAttemptsSubtitle": "Wie oft die Anmeldung an einem Repeater oder Room-Server versucht wird, bevor abgebrochen wird." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..52461453 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -617,15 +617,42 @@ "appSettings_advertisementNotificationsSubtitle": "Show notification when new nodes are discovered", "appSettings_messaging": "Messaging", "appSettings_clearPathOnMaxRetry": "Clear Path on Max Retry", - "appSettings_clearPathOnMaxRetrySubtitle": "Reset contact path after 5 failed send attempts", - "appSettings_pathsWillBeCleared": "Paths will be cleared after 5 failed retries", + "appSettings_clearPathOnMaxRetrySubtitle": "Reset the contact's saved path after every send attempt fails", + "appSettings_pathsWillBeCleared": "Paths will be cleared after all send attempts fail", "appSettings_pathsWillNotBeCleared": "Paths will not be auto-cleared", "appSettings_autoRouteRotation": "Auto Route Rotation", - "appSettings_autoRouteRotationSubtitle": "Cycle between best paths and flood mode", + "appSettings_autoRouteRotationSubtitle": "On each direct attempt, try a different known route. Later attempts flood. Off keeps the contact's current path.", "appSettings_autoRouteRotationEnabled": "Auto route rotation enabled", "appSettings_autoRouteRotationDisabled": "Auto route rotation disabled", "appSettings_maxMessageRetries": "Max Message Retries", "appSettings_maxMessageRetriesSubtitle": "Number of retry attempts before marking a message as failed", + "appSettings_directRetries": "Direct attempts: {count}", + "@appSettings_directRetries": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "appSettings_directRetriesSubtitle": "How many times to try a known route. This stays available when auto route rotation is off.", + "appSettings_floodRetries": "Flood attempts: {count}", + "@appSettings_floodRetries": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "appSettings_floodRetriesSubtitle": "How many times to flood. Floods use more airtime. With rotation on, these follow the direct attempts.", + "appSettings_loginAttempts": "Login attempts: {count}", + "@appSettings_loginAttempts": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "appSettings_loginAttemptsSubtitle": "How many times to try logging in to a repeater or room server before giving up.", "appSettings_ipfsImageLinks": "IPFS provider configuration", "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", "appSettings_loadLinkImages": "Load images from links", @@ -3905,9 +3932,9 @@ "appSettings_sourceSummary": "{label} - {description}", "@appSettings_sourceSummary": {"placeholders": {"label": {"type": "String"}, "description": {"type": "String"}}}, "appSettings_routingSection": "Routing", - "appSettings_resetRoutingToDefault": "Reset Routing Algorithm to Default", - "appSettings_resetRoutingToDefaultSubtitle": "Restore routing algorithm settings to factory defaults", - "appSettings_routingResetToDefault": "Routing algorithm settings reset to default", + "appSettings_resetRoutingToDefault": "Reset routing settings to defaults", + "appSettings_resetRoutingToDefaultSubtitle": "Restore the routing settings in this section to their defaults", + "appSettings_routingResetToDefault": "Routing settings reset to defaults", "appSettings_imageMessagesSection": "Image messages", "appSettings_showApiKey": "Show API key", "appSettings_hideApiKey": "Hide API key", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 1b0ddb11..95c9fb04 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Mostrar notificación cuando se descubren nuevos nodos", "appSettings_messaging": "Mensajería", "appSettings_clearPathOnMaxRetry": "Borrar ruta al máximo de reintentos", - "appSettings_clearPathOnMaxRetrySubtitle": "Restablecer la ruta de contacto después de 5 intentos de envío fallidos", - "appSettings_pathsWillBeCleared": "Las rutas se borrarán después de 5 intentos fallidos.", + "appSettings_clearPathOnMaxRetrySubtitle": "Restablecer la ruta guardada del contacto cuando fallen todos los intentos de envío", + "appSettings_pathsWillBeCleared": "Las rutas se borrarán cuando fallen todos los intentos de envío", "appSettings_pathsWillNotBeCleared": "Las rutas no se eliminarán automáticamente.", "appSettings_autoRouteRotation": "Rotación automática de rutas", - "appSettings_autoRouteRotationSubtitle": "Alternar entre las mejores rutas y el modo Flood", + "appSettings_autoRouteRotationSubtitle": "En cada intento directo, probar otra ruta conocida. Los intentos siguientes son Flood. Desactivado mantiene la ruta actual del contacto.", "appSettings_autoRouteRotationEnabled": "Rotación de ruta automática habilitada", "appSettings_autoRouteRotationDisabled": "Rotación de ruta automática desactivada", "appSettings_battery": "Batería", @@ -3373,9 +3373,9 @@ "settings_regionFetchNoneResponded": "Ningún repetidor cercano respondió. Acércate a un repetidor e inténtalo de nuevo.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Enrutamiento", - "appSettings_resetRoutingToDefault": "Restablecer algoritmo de enrutamiento a predeterminado", - "appSettings_resetRoutingToDefaultSubtitle": "Restaurar la configuración del algoritmo de enrutamiento a los valores predeterminados de fábrica", - "appSettings_routingResetToDefault": "Configuración del algoritmo de enrutamiento restablecida a predeterminado", + "appSettings_resetRoutingToDefault": "Restablecer la configuración de enrutamiento", + "appSettings_resetRoutingToDefaultSubtitle": "Restaurar los ajustes de enrutamiento de esta sección a sus valores predeterminados", + "appSettings_routingResetToDefault": "Configuración de enrutamiento restablecida", "appSettings_imageMessagesSection": "Mensajes con imágenes", "appSettings_showApiKey": "Mostrar clave de API", "appSettings_hideApiKey": "Ocultar clave de API", @@ -3962,5 +3962,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB o TCP", "connectSheet_stopReconnecting": "Dejar de reconectar", "connectSheet_reconnectFailed": "No se pudo conectar con {name}. Comprueba que esté encendida y cerca.", - "chat_composerOffline": "Conéctate a una radio para enviar mensajes" + "chat_composerOffline": "Conéctate a una radio para enviar mensajes", + "appSettings_directRetries": "Intentos directos: {count}", + "appSettings_directRetriesSubtitle": "Cuántas veces probar una ruta conocida. Sigue disponible aunque la rotación automática esté desactivada.", + "appSettings_floodRetries": "Intentos Flood: {count}", + "appSettings_floodRetriesSubtitle": "Cuántas veces usar Flood. Flood usa más tiempo de aire. Con la rotación activada, van después de los intentos directos.", + "appSettings_loginAttempts": "Intentos de inicio de sesión: {count}", + "appSettings_loginAttemptsSubtitle": "Cuántas veces intentar iniciar sesión en un repetidor o servidor de sala antes de rendirse." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index de3c1be3..7328109b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Afficher une notification lors de la découverte de nouveaux nœuds", "appSettings_messaging": "Messagerie", "appSettings_clearPathOnMaxRetry": "Effacer le chemin après le nombre maximal de tentatives", - "appSettings_clearPathOnMaxRetrySubtitle": "Réinitialiser le chemin de contact après 5 tentatives d'envoi infructueuses", - "appSettings_pathsWillBeCleared": "Les chemins seront effacés après 5 échecs.", + "appSettings_clearPathOnMaxRetrySubtitle": "Réinitialiser le chemin enregistré du contact lorsque toutes les tentatives d'envoi échouent", + "appSettings_pathsWillBeCleared": "Les chemins seront effacés si toutes les tentatives d'envoi échouent", "appSettings_pathsWillNotBeCleared": "Les chemins ne seront pas effacés automatiquement.", "appSettings_autoRouteRotation": "Rotation automatique du routage", - "appSettings_autoRouteRotationSubtitle": "Alterner entre les meilleurs chemins et le mode flood", + "appSettings_autoRouteRotationSubtitle": "À chaque tentative directe, essayer une autre route connue. Les tentatives suivantes sont en Flood. Désactivé : le chemin actuel du contact est conservé.", "appSettings_autoRouteRotationEnabled": "Rotation automatique du routage activée", "appSettings_autoRouteRotationDisabled": "Rotation automatique du routage désactivée", "appSettings_battery": "Batterie", @@ -3373,9 +3373,9 @@ "settings_regionFetchNoneResponded": "Aucun répéteur à proximité n'a répondu. Rapprochez-vous d'un répéteur et réessayez.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Routage", - "appSettings_resetRoutingToDefault": "Réinitialiser l'algorithme de routage", - "appSettings_resetRoutingToDefaultSubtitle": "Restaurer les paramètres de l'algorithme de routage aux valeurs par défaut", - "appSettings_routingResetToDefault": "Paramètres de l'algorithme de routage réinitialisés", + "appSettings_resetRoutingToDefault": "Réinitialiser les paramètres de routage", + "appSettings_resetRoutingToDefaultSubtitle": "Rétablir les paramètres de routage de cette section à leurs valeurs par défaut", + "appSettings_routingResetToDefault": "Paramètres de routage réinitialisés", "appSettings_imageMessagesSection": "Messages image", "appSettings_showApiKey": "Afficher la clé API", "appSettings_hideApiKey": "Masquer la clé API", @@ -3910,5 +3910,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ou TCP", "connectSheet_stopReconnecting": "Arrêter la reconnexion", "connectSheet_reconnectFailed": "Impossible de joindre {name}. Vérifiez qu'elle est allumée et à proximité.", - "chat_composerOffline": "Connectez-vous à une radio pour envoyer des messages" + "chat_composerOffline": "Connectez-vous à une radio pour envoyer des messages", + "appSettings_directRetries": "Tentatives directes : {count}", + "appSettings_directRetriesSubtitle": "Nombre d'essais sur une route connue. Disponible même si la rotation automatique des routes est désactivée.", + "appSettings_floodRetries": "Tentatives Flood : {count}", + "appSettings_floodRetriesSubtitle": "Nombre de Flood. Un Flood utilise plus de temps d'antenne. Avec la rotation activée, ils suivent les tentatives directes.", + "appSettings_loginAttempts": "Tentatives de connexion : {count}", + "appSettings_loginAttemptsSubtitle": "Nombre d'essais de connexion à un répéteur ou à un serveur de salon avant d'abandonner." } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index ba73a0d6..243963b5 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -269,11 +269,11 @@ "appSettings_advertisementNotificationsSubtitle": "Értesítés megjelenítése új csomópontok felfedezésekor", "appSettings_messaging": "Üzenetküldés", "appSettings_clearPathOnMaxRetry": "Útvonal törlése a Max. újrapróbálkozásnál", - "appSettings_clearPathOnMaxRetrySubtitle": "Állítsa vissza a kapcsolati elérési utat 5 sikertelen küldési kísérlet után", - "appSettings_pathsWillBeCleared": "Az elérési utak 5 sikertelen újrapróbálkozás után törlődnek", + "appSettings_clearPathOnMaxRetrySubtitle": "A kapcsolat mentett útvonalának visszaállítása, ha minden küldési próbálkozás sikertelen", + "appSettings_pathsWillBeCleared": "Az útvonalak törlődnek, ha minden küldési próbálkozás sikertelen", "appSettings_pathsWillNotBeCleared": "Az útvonalak nem törlődnek automatikusan", "appSettings_autoRouteRotation": "Automatikus útvonalváltás", - "appSettings_autoRouteRotationSubtitle": "Váltson a legjobb útvonalak és a flood mód között", + "appSettings_autoRouteRotationSubtitle": "Minden közvetlen próbálkozásnál másik ismert útvonalat próbál. A későbbiek Flood. Kikapcsolva a kapcsolat jelenlegi útvonalát használja.", "appSettings_autoRouteRotationEnabled": "Az automatikus útvonalforgatás engedélyezve", "appSettings_autoRouteRotationDisabled": "Az automatikus útvonalforgatás letiltva", "appSettings_maxMessageRetries": "Üzenet újrapróbálkozások maximális száma", @@ -3392,9 +3392,9 @@ "settings_regionFetchNoneResponded": "Egyik közeli átjátszó sem válaszolt. Menjen közelebb egy átjátszóhoz, és próbálja újra.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Útválasztás", - "appSettings_resetRoutingToDefault": "Útvonaltervezési algoritmus visszaállítása alapértelmezettre", - "appSettings_resetRoutingToDefaultSubtitle": "Útvonaltervezési algoritmus beállításainak visszaállítása gyári alapértelmezett értékekre", - "appSettings_routingResetToDefault": "Útvonaltervezési algoritmus beállításai visszaállítva alapértelmezettre", + "appSettings_resetRoutingToDefault": "Útválasztási beállítások visszaállítása alapértelmezettre", + "appSettings_resetRoutingToDefaultSubtitle": "A szakasz útvonalbeállításainak visszaállítása az alapértelmezett értékekre", + "appSettings_routingResetToDefault": "Útválasztási beállítások visszaállítva alapértelmezettre", "appSettings_imageMessagesSection": "Képüzenetek", "appSettings_showApiKey": "API-kulcs megjelenítése", "appSettings_hideApiKey": "API-kulcs elrejtése", @@ -3867,5 +3867,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB vagy TCP", "connectSheet_stopReconnecting": "Újracsatlakozás leállítása", "connectSheet_reconnectFailed": "Nem érhető el: {name}. Ellenőrizze, hogy be van-e kapcsolva és a közelben van-e.", - "chat_composerOffline": "Üzenetküldéshez csatlakozzon rádióhoz" + "chat_composerOffline": "Üzenetküldéshez csatlakozzon rádióhoz", + "appSettings_directRetries": "Közvetlen próbálkozások: {count}", + "appSettings_directRetriesSubtitle": "Hányszor próbáljon ismert útvonalat. Akkor is beállítható, ha az automatikus útvonalváltás ki van kapcsolva.", + "appSettings_floodRetries": "Flood próbálkozások: {count}", + "appSettings_floodRetriesSubtitle": "Hányszor használjon Floodot. A Flood több adásidőt használ. Bekapcsolt váltásnál a közvetlen próbálkozások után jönnek.", + "appSettings_loginAttempts": "Bejelentkezési próbálkozások: {count}", + "appSettings_loginAttemptsSubtitle": "Hányszor próbáljon bejelentkezni egy átjátszóra vagy room szerverre, mielőtt feladja." } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 8d6bd2ec..9ef267fc 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -197,11 +197,11 @@ "appSettings_advertisementNotificationsSubtitle": "Mostra notifica quando vengono scoperti nuovi nodi", "appSettings_messaging": "Messaggi", "appSettings_clearPathOnMaxRetry": "Cancella percorso al massimo dei tentativi", - "appSettings_clearPathOnMaxRetrySubtitle": "Reimposta il percorso di contatto dopo 5 tentativi di invio falliti", - "appSettings_pathsWillBeCleared": "I percorsi verranno cancellati dopo 5 tentativi falliti.", + "appSettings_clearPathOnMaxRetrySubtitle": "Reimposta il percorso salvato del contatto quando tutti i tentativi di invio falliscono", + "appSettings_pathsWillBeCleared": "I percorsi verranno cancellati quando tutti i tentativi di invio falliscono", "appSettings_pathsWillNotBeCleared": "I percorsi non verranno cancellati automaticamente.", "appSettings_autoRouteRotation": "Rotazione Percorso Automatico", - "appSettings_autoRouteRotationSubtitle": "Alterna tra i percorsi migliori e la modalità flood", + "appSettings_autoRouteRotationSubtitle": "A ogni tentativo diretto, prova un altro percorso noto. I tentativi successivi sono Flood. Disattivato mantiene il percorso attuale del contatto.", "appSettings_autoRouteRotationEnabled": "Rotazione percorso automatico abilitata", "appSettings_autoRouteRotationDisabled": "Rotazione del percorso automatico disabilitata", "appSettings_battery": "Batteria", @@ -3373,9 +3373,9 @@ "settings_regionFetchNoneResponded": "Nessun ripetitore vicino ha risposto. Avvicinati a un ripetitore e riprova.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Instradamento", - "appSettings_resetRoutingToDefault": "Reimposta algoritmo di instradamento sui valori predefiniti", - "appSettings_resetRoutingToDefaultSubtitle": "Ripristina le impostazioni dell'algoritmo di instradamento ai valori predefiniti di fabbrica", - "appSettings_routingResetToDefault": "Impostazioni algoritmo di instradamento reimpostate sui valori predefiniti", + "appSettings_resetRoutingToDefault": "Reimposta le impostazioni di instradamento sui valori predefiniti", + "appSettings_resetRoutingToDefaultSubtitle": "Ripristina le impostazioni di instradamento di questa sezione ai valori predefiniti", + "appSettings_routingResetToDefault": "Impostazioni di instradamento reimpostate sui valori predefiniti", "appSettings_imageMessagesSection": "Messaggi immagine", "appSettings_showApiKey": "Mostra chiave API", "appSettings_hideApiKey": "Nascondi chiave API", @@ -3910,5 +3910,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB o TCP", "connectSheet_stopReconnecting": "Interrompi la riconnessione", "connectSheet_reconnectFailed": "Impossibile raggiungere {name}. Assicurati che sia acceso e nelle vicinanze.", - "chat_composerOffline": "Connettiti a una radio per inviare messaggi" + "chat_composerOffline": "Connettiti a una radio per inviare messaggi", + "appSettings_directRetries": "Tentativi diretti: {count}", + "appSettings_directRetriesSubtitle": "Quante volte provare un percorso noto. Resta disponibile anche con la rotazione automatica disattivata.", + "appSettings_floodRetries": "Tentativi Flood: {count}", + "appSettings_floodRetriesSubtitle": "Quante volte usare Flood. Flood usa più tempo in aria. Con la rotazione attiva, seguono i tentativi diretti.", + "appSettings_loginAttempts": "Tentativi di accesso: {count}", + "appSettings_loginAttemptsSubtitle": "Quante volte provare l'accesso a un ripetitore o a un server room prima di rinunciare." } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 0a3b8931..10a5b039 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -275,11 +275,11 @@ "appSettings_advertisementNotificationsSubtitle": "新しいノードが発見された場合に通知を表示する", "appSettings_messaging": "メッセージング", "appSettings_clearPathOnMaxRetry": "最大再試行時に経路を消去", - "appSettings_clearPathOnMaxRetrySubtitle": "5 回送信に失敗したら連絡先の経路をリセットします", - "appSettings_pathsWillBeCleared": "5 回失敗すると経路を消去します", + "appSettings_clearPathOnMaxRetrySubtitle": "すべての送信が失敗したら、連絡先の保存済み経路をリセットします", + "appSettings_pathsWillBeCleared": "すべての送信が失敗すると経路を消去します", "appSettings_pathsWillNotBeCleared": "経路は自動では消去されません", "appSettings_autoRouteRotation": "自動経路切り替え", - "appSettings_autoRouteRotationSubtitle": "最適な経路とフラッドモードを切り替えます", + "appSettings_autoRouteRotationSubtitle": "直接の試行ごとに別の既知の経路を試します。その後の試行は Flood です。オフのときは連絡先の現在の経路を使います。", "appSettings_autoRouteRotationEnabled": "自動経路切り替えが有効です", "appSettings_autoRouteRotationDisabled": "自動経路切り替えは無効です", "appSettings_maxMessageRetries": "最大メッセージ再試行回数", @@ -3373,9 +3373,9 @@ "settings_regionFetchNoneResponded": "近くのリピータから応答がありませんでした。リピータに近づいてもう一度お試しください。", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "ルーティング", - "appSettings_resetRoutingToDefault": "ルーティングアルゴリズムをデフォルトにリセット", - "appSettings_resetRoutingToDefaultSubtitle": "ルーティングアルゴリズムの設定を工場出荷時のデフォルトに戻す", - "appSettings_routingResetToDefault": "ルーティングアルゴリズムの設定がデフォルトにリセットされました", + "appSettings_resetRoutingToDefault": "ルーティング設定をデフォルトにリセット", + "appSettings_resetRoutingToDefaultSubtitle": "このセクションの経路設定を初期値に戻します", + "appSettings_routingResetToDefault": "ルーティング設定がデフォルトにリセットされました", "appSettings_imageMessagesSection": "画像メッセージ", "appSettings_showApiKey": "APIキーを表示", "appSettings_hideApiKey": "APIキーを非表示", @@ -4116,5 +4116,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth、USB、またはTCP", "connectSheet_stopReconnecting": "再接続を停止", "connectSheet_reconnectFailed": "{name} に接続できませんでした。電源が入っていて近くにあることを確認してください。", - "chat_composerOffline": "メッセージを送信するには無線機に接続してください" + "chat_composerOffline": "メッセージを送信するには無線機に接続してください", + "appSettings_directRetries": "直接の試行: {count}", + "appSettings_directRetriesSubtitle": "既知の経路を試す回数です。自動経路切り替えがオフでも設定できます。", + "appSettings_floodRetries": "Flood の試行: {count}", + "appSettings_floodRetriesSubtitle": "Flood する回数です。Flood は通信時間を多く使います。切り替えがオンのとき、直接の試行の後に行います。", + "appSettings_loginAttempts": "ログイン試行: {count}", + "appSettings_loginAttemptsSubtitle": "リピータまたはルームサーバーへのログインをあきらめるまでの回数です。" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index dcaf27a3..39f55216 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -269,11 +269,11 @@ "appSettings_advertisementNotificationsSubtitle": "새 노드가 발견되었을 때 알림 표시", "appSettings_messaging": "메시징", "appSettings_clearPathOnMaxRetry": "최대 재시도 시 경로 지우기", - "appSettings_clearPathOnMaxRetrySubtitle": "전송 시도가 5번 실패하면 연락 경로를 재설정합니다.", - "appSettings_pathsWillBeCleared": "5번 실패하면 해당 경로를 지웁니다.", + "appSettings_clearPathOnMaxRetrySubtitle": "모든 전송 시도가 실패하면 연락처의 저장된 경로를 재설정합니다", + "appSettings_pathsWillBeCleared": "모든 전송 시도가 실패하면 경로를 지웁니다", "appSettings_pathsWillNotBeCleared": "경로를 자동으로 지우지 않습니다.", "appSettings_autoRouteRotation": "자동 경로 순환", - "appSettings_autoRouteRotationSubtitle": "최적 경로와 플러딩 모드 사이를 전환합니다.", + "appSettings_autoRouteRotationSubtitle": "직접 시도마다 다른 알려진 경로를 사용합니다. 이후 시도는 Flood입니다. 끄면 연락처의 현재 경로를 유지합니다.", "appSettings_autoRouteRotationEnabled": "자동 경로 순환 기능 활성화", "appSettings_autoRouteRotationDisabled": "자동 경로 순환 기능 비활성화", "appSettings_maxMessageRetries": "최대 메시지 재시도 횟수", @@ -3373,9 +3373,9 @@ "settings_regionFetchNoneResponded": "응답한 주변 리피터가 없습니다. 리피터에 더 가까이 이동한 후 다시 시도하세요.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "라우팅", - "appSettings_resetRoutingToDefault": "라우팅 알고리즘 기본값으로 재설정", - "appSettings_resetRoutingToDefaultSubtitle": "라우팅 알고리즘 설정을 공장 기본값으로 복원", - "appSettings_routingResetToDefault": "라우팅 알고리즘 설정이 기본값으로 재설정되었습니다", + "appSettings_resetRoutingToDefault": "라우팅 설정을 기본값으로 재설정", + "appSettings_resetRoutingToDefaultSubtitle": "이 섹션의 라우팅 설정을 기본값으로 되돌립니다", + "appSettings_routingResetToDefault": "라우팅 설정이 기본값으로 재설정되었습니다", "appSettings_imageMessagesSection": "이미지 메시지", "appSettings_showApiKey": "API 키 표시", "appSettings_hideApiKey": "API 키 숨기기", @@ -4116,5 +4116,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB 또는 TCP", "connectSheet_stopReconnecting": "재연결 중지", "connectSheet_reconnectFailed": "{name}에 연결할 수 없습니다. 전원이 켜져 있고 가까이 있는지 확인하세요.", - "chat_composerOffline": "메시지를 보내려면 무전기에 연결하세요" + "chat_composerOffline": "메시지를 보내려면 무전기에 연결하세요", + "appSettings_directRetries": "직접 시도: {count}", + "appSettings_directRetriesSubtitle": "알려진 경로를 시도하는 횟수입니다. 자동 경로 순환을 꺼도 설정할 수 있습니다.", + "appSettings_floodRetries": "Flood 시도: {count}", + "appSettings_floodRetriesSubtitle": "Flood를 사용하는 횟수입니다. Flood는 전파 시간을 더 씁니다. 순환이 켜져 있으면 직접 시도 다음에 실행됩니다.", + "appSettings_loginAttempts": "로그인 시도: {count}", + "appSettings_loginAttemptsSubtitle": "중계기나 룸 서버 로그인을 포기하기 전까지의 시도 횟수입니다." } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..48f7031a 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2632,13 +2632,13 @@ abstract class AppLocalizations { /// No description provided for @appSettings_clearPathOnMaxRetrySubtitle. /// /// In en, this message translates to: - /// **'Reset contact path after 5 failed send attempts'** + /// **'Reset the contact\'s saved path after every send attempt fails'** String get appSettings_clearPathOnMaxRetrySubtitle; /// No description provided for @appSettings_pathsWillBeCleared. /// /// In en, this message translates to: - /// **'Paths will be cleared after 5 failed retries'** + /// **'Paths will be cleared after all send attempts fail'** String get appSettings_pathsWillBeCleared; /// No description provided for @appSettings_pathsWillNotBeCleared. @@ -2656,7 +2656,7 @@ abstract class AppLocalizations { /// No description provided for @appSettings_autoRouteRotationSubtitle. /// /// In en, this message translates to: - /// **'Cycle between best paths and flood mode'** + /// **'On each direct attempt, try a different known route. Later attempts flood. Off keeps the contact\'s current path.'** String get appSettings_autoRouteRotationSubtitle; /// No description provided for @appSettings_autoRouteRotationEnabled. @@ -2683,6 +2683,42 @@ abstract class AppLocalizations { /// **'Number of retry attempts before marking a message as failed'** String get appSettings_maxMessageRetriesSubtitle; + /// No description provided for @appSettings_directRetries. + /// + /// In en, this message translates to: + /// **'Direct attempts: {count}'** + String appSettings_directRetries(int count); + + /// No description provided for @appSettings_directRetriesSubtitle. + /// + /// In en, this message translates to: + /// **'How many times to try a known route. This stays available when auto route rotation is off.'** + String get appSettings_directRetriesSubtitle; + + /// No description provided for @appSettings_floodRetries. + /// + /// In en, this message translates to: + /// **'Flood attempts: {count}'** + String appSettings_floodRetries(int count); + + /// No description provided for @appSettings_floodRetriesSubtitle. + /// + /// In en, this message translates to: + /// **'How many times to flood. Floods use more airtime. With rotation on, these follow the direct attempts.'** + String get appSettings_floodRetriesSubtitle; + + /// No description provided for @appSettings_loginAttempts. + /// + /// In en, this message translates to: + /// **'Login attempts: {count}'** + String appSettings_loginAttempts(int count); + + /// No description provided for @appSettings_loginAttemptsSubtitle. + /// + /// In en, this message translates to: + /// **'How many times to try logging in to a repeater or room server before giving up.'** + String get appSettings_loginAttemptsSubtitle; + /// No description provided for @appSettings_ipfsImageLinks. /// /// In en, this message translates to: @@ -11744,19 +11780,19 @@ abstract class AppLocalizations { /// No description provided for @appSettings_resetRoutingToDefault. /// /// In en, this message translates to: - /// **'Reset Routing Algorithm to Default'** + /// **'Reset routing settings to defaults'** String get appSettings_resetRoutingToDefault; /// No description provided for @appSettings_resetRoutingToDefaultSubtitle. /// /// In en, this message translates to: - /// **'Restore routing algorithm settings to factory defaults'** + /// **'Restore the routing settings in this section to their defaults'** String get appSettings_resetRoutingToDefaultSubtitle; /// No description provided for @appSettings_routingResetToDefault. /// /// In en, this message translates to: - /// **'Routing algorithm settings reset to default'** + /// **'Routing settings reset to defaults'** String get appSettings_routingResetToDefault; /// No description provided for @appSettings_imageMessagesSection. diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..ca492bc5 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1443,11 +1443,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Възстанови пътя към контакта след 5 неуспешни опита за изпращане'; + 'Нулиране на записания път към контакта, когато всички опити за изпращане се провалят'; @override String get appSettings_pathsWillBeCleared => - 'Пътищата ще бъдат почистени след 5 неуспешни опита.'; + 'Пътищата се изчистват, когато всички опити за изпращане се провалят'; @override String get appSettings_pathsWillNotBeCleared => @@ -1459,7 +1459,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Превключвайте между най-добрите пътища и режим Flood'; + 'При всеки директен опит се пробва друг известен маршрут. Следващите опити са Flood. Изключено запазва текущия път на контакта.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1477,6 +1477,33 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Брой опити за повторно изпращане, преди съобщението да бъде маркирано като неуспешно.'; + @override + String appSettings_directRetries(int count) { + return 'Директни опити: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Колко пъти да се пробва известен маршрут. Достъпно и когато автоматичната ротация е изключена.'; + + @override + String appSettings_floodRetries(int count) { + return 'Опити Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Колко пъти да се използва Flood. Flood заема повече ефирно време. При включена ротация идват след директните опити.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Опити за вход: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Колко пъти да се опитва вход към ретранслатор или room сървър, преди да се откаже.'; + @override String get appSettings_ipfsImageLinks => 'Конфигурация на IPFS доставчик'; @@ -7037,15 +7064,15 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Нулиране на алгоритъма за маршрутизация до стойност по подразбиране'; + 'Нулиране на настройките за маршрутизация до стойностите по подразбиране'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Възстановяване на настройките на алгоритъма за маршрутизация до заводските стойности по подразбиране'; + 'Възстановяване на настройките за маршрутизация в този раздел до стойностите по подразбиране'; @override String get appSettings_routingResetToDefault => - 'Настройките на алгоритъма за маршрутизация са нулирани до стойност по подразбиране'; + 'Настройките за маршрутизация са нулирани до стойностите по подразбиране'; @override String get appSettings_imageMessagesSection => 'Съобщения с изображения'; diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..81ff8f3f 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -1434,11 +1434,11 @@ class AppLocalizationsCs extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Resetovat cestu kontaktu po 5 neúspěšných pokusech o odeslání'; + 'Resetovat uloženou cestu kontaktu, když selžou všechny pokusy o odeslání'; @override String get appSettings_pathsWillBeCleared => - 'Cesty budou vymazány po 5 neúspěšných pokusech'; + 'Cesty se vymažou, když selžou všechny pokusy o odeslání'; @override String get appSettings_pathsWillNotBeCleared => @@ -1449,7 +1449,7 @@ class AppLocalizationsCs extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Střídat nejlepší cesty a režim flood'; + 'Při každém přímém pokusu zkusit jinou známou trasu. Pozdější pokusy jsou Flood. Vypnuto ponechá aktuální cestu kontaktu.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1466,6 +1466,33 @@ class AppLocalizationsCs extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Počet opakovaných pokusů, než se zpráva označí jako neodeslaná'; + @override + String appSettings_directRetries(int count) { + return 'Přímé pokusy: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Kolikrát se zkusí známá trasa. Dostupné i když je automatické střídání tras vypnuté.'; + + @override + String appSettings_floodRetries(int count) { + return 'Pokusy Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Kolikrát se použije Flood. Flood zabere víc vysílacího času. Při zapnutém střídání následují po přímých pokusech.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Pokusy o přihlášení: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Kolikrát se zkusí přihlášení k opakovači nebo room serveru, než se to vzdá.'; + @override String get appSettings_ipfsImageLinks => 'Konfigurace poskytovatele IPFS'; @@ -7017,15 +7044,15 @@ class AppLocalizationsCs extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Obnovit výchozí směrovací algoritmus'; + 'Obnovit výchozí nastavení směrování'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Obnovit nastavení směrovacího algoritmu na tovární hodnoty'; + 'Obnovit nastavení směrování v této části na výchozí hodnoty'; @override String get appSettings_routingResetToDefault => - 'Nastavení směrovacího algoritmu obnoveno na výchozí'; + 'Nastavení směrování obnoveno na výchozí'; @override String get appSettings_imageMessagesSection => 'Obrázkové zprávy'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..d43bf080 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1445,11 +1445,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Kontaktpfade nach 5 fehlgeschlagenen Sendeversuchen zurücksetzen'; + 'Gespeicherten Kontaktpfad zurücksetzen, wenn alle Sendeversuche fehlschlagen'; @override String get appSettings_pathsWillBeCleared => - 'Pfade werden nach 5 fehlgeschlagenen Wiederholungen gelöscht.'; + 'Pfade werden gelöscht, wenn alle Sendeversuche fehlschlagen'; @override String get appSettings_pathsWillNotBeCleared => @@ -1460,7 +1460,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Zwischen den besten Pfaden und dem Flood-Modus wechseln'; + 'Bei jedem direkten Versuch eine andere bekannte Route nutzen. Die späteren Versuche sind Flood. Aus behält den aktuellen Pfad des Kontakts.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1478,6 +1478,33 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Anzahl der Versuche, eine Nachricht erneut zu senden, bevor sie als fehlgeschlagen markiert wird.'; + @override + String appSettings_directRetries(int count) { + return 'Direkte Versuche: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Wie oft eine bekannte Route versucht wird. Auch verfügbar, wenn die automatische Routenrotation aus ist.'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood-Versuche: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Wie oft geflutet wird. Flood verbraucht mehr Sendezeit. Bei eingeschalteter Rotation folgen diese auf die direkten Versuche.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Anmeldeversuche: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Wie oft die Anmeldung an einem Repeater oder Room-Server versucht wird, bevor abgebrochen wird.'; + @override String get appSettings_ipfsImageLinks => 'IPFS-Anbieter-Konfiguration'; @@ -7052,15 +7079,15 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Routing-Algorithmus auf Standard zurücksetzen'; + 'Routing-Einstellungen auf Standard zurücksetzen'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Routing-Algorithmus-Einstellungen auf Werkseinstellungen zurücksetzen'; + 'Die Routing-Einstellungen in diesem Abschnitt auf die Standardwerte zurücksetzen'; @override String get appSettings_routingResetToDefault => - 'Routing-Algorithmus-Einstellungen auf Standard zurückgesetzt'; + 'Routing-Einstellungen auf Standard zurückgesetzt'; @override String get appSettings_imageMessagesSection => 'Bildnachrichten'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..6b8136a3 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1417,11 +1417,11 @@ class AppLocalizationsEn extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Reset contact path after 5 failed send attempts'; + 'Reset the contact\'s saved path after every send attempt fails'; @override String get appSettings_pathsWillBeCleared => - 'Paths will be cleared after 5 failed retries'; + 'Paths will be cleared after all send attempts fail'; @override String get appSettings_pathsWillNotBeCleared => @@ -1432,7 +1432,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Cycle between best paths and flood mode'; + 'On each direct attempt, try a different known route. Later attempts flood. Off keeps the contact\'s current path.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1449,6 +1449,33 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Number of retry attempts before marking a message as failed'; + @override + String appSettings_directRetries(int count) { + return 'Direct attempts: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'How many times to try a known route. This stays available when auto route rotation is off.'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood attempts: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'How many times to flood. Floods use more airtime. With rotation on, these follow the direct attempts.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Login attempts: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'How many times to try logging in to a repeater or room server before giving up.'; + @override String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; @@ -6938,15 +6965,15 @@ class AppLocalizationsEn extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Reset Routing Algorithm to Default'; + 'Reset routing settings to defaults'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Restore routing algorithm settings to factory defaults'; + 'Restore the routing settings in this section to their defaults'; @override String get appSettings_routingResetToDefault => - 'Routing algorithm settings reset to default'; + 'Routing settings reset to defaults'; @override String get appSettings_imageMessagesSection => 'Image messages'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..2acf9ddc 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1436,11 +1436,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Restablecer la ruta de contacto después de 5 intentos de envío fallidos'; + 'Restablecer la ruta guardada del contacto cuando fallen todos los intentos de envío'; @override String get appSettings_pathsWillBeCleared => - 'Las rutas se borrarán después de 5 intentos fallidos.'; + 'Las rutas se borrarán cuando fallen todos los intentos de envío'; @override String get appSettings_pathsWillNotBeCleared => @@ -1451,7 +1451,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Alternar entre las mejores rutas y el modo Flood'; + 'En cada intento directo, probar otra ruta conocida. Los intentos siguientes son Flood. Desactivado mantiene la ruta actual del contacto.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1469,6 +1469,33 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Número de intentos de reintento antes de marcar un mensaje como fallido.'; + @override + String appSettings_directRetries(int count) { + return 'Intentos directos: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Cuántas veces probar una ruta conocida. Sigue disponible aunque la rotación automática esté desactivada.'; + + @override + String appSettings_floodRetries(int count) { + return 'Intentos Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Cuántas veces usar Flood. Flood usa más tiempo de aire. Con la rotación activada, van después de los intentos directos.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Intentos de inicio de sesión: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Cuántas veces intentar iniciar sesión en un repetidor o servidor de sala antes de rendirse.'; + @override String get appSettings_ipfsImageLinks => 'Configuración del proveedor IPFS'; @@ -7033,15 +7060,15 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Restablecer algoritmo de enrutamiento a predeterminado'; + 'Restablecer la configuración de enrutamiento'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Restaurar la configuración del algoritmo de enrutamiento a los valores predeterminados de fábrica'; + 'Restaurar los ajustes de enrutamiento de esta sección a sus valores predeterminados'; @override String get appSettings_routingResetToDefault => - 'Configuración del algoritmo de enrutamiento restablecida a predeterminado'; + 'Configuración de enrutamiento restablecida'; @override String get appSettings_imageMessagesSection => 'Mensajes con imágenes'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..c24ec931 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1442,11 +1442,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Réinitialiser le chemin de contact après 5 tentatives d\'envoi infructueuses'; + 'Réinitialiser le chemin enregistré du contact lorsque toutes les tentatives d\'envoi échouent'; @override String get appSettings_pathsWillBeCleared => - 'Les chemins seront effacés après 5 échecs.'; + 'Les chemins seront effacés si toutes les tentatives d\'envoi échouent'; @override String get appSettings_pathsWillNotBeCleared => @@ -1457,7 +1457,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Alterner entre les meilleurs chemins et le mode flood'; + 'À chaque tentative directe, essayer une autre route connue. Les tentatives suivantes sont en Flood. Désactivé : le chemin actuel du contact est conservé.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1475,6 +1475,33 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Nombre de tentatives avant de marquer un message comme ayant échoué.'; + @override + String appSettings_directRetries(int count) { + return 'Tentatives directes : $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Nombre d\'essais sur une route connue. Disponible même si la rotation automatique des routes est désactivée.'; + + @override + String appSettings_floodRetries(int count) { + return 'Tentatives Flood : $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Nombre de Flood. Un Flood utilise plus de temps d\'antenne. Avec la rotation activée, ils suivent les tentatives directes.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Tentatives de connexion : $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Nombre d\'essais de connexion à un répéteur ou à un serveur de salon avant d\'abandonner.'; + @override String get appSettings_ipfsImageLinks => 'Configuration du fournisseur IPFS'; @@ -7058,15 +7085,15 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Réinitialiser l\'algorithme de routage'; + 'Réinitialiser les paramètres de routage'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Restaurer les paramètres de l\'algorithme de routage aux valeurs par défaut'; + 'Rétablir les paramètres de routage de cette section à leurs valeurs par défaut'; @override String get appSettings_routingResetToDefault => - 'Paramètres de l\'algorithme de routage réinitialisés'; + 'Paramètres de routage réinitialisés'; @override String get appSettings_imageMessagesSection => 'Messages image'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..c6954bba 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1434,11 +1434,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Állítsa vissza a kapcsolati elérési utat 5 sikertelen küldési kísérlet után'; + 'A kapcsolat mentett útvonalának visszaállítása, ha minden küldési próbálkozás sikertelen'; @override String get appSettings_pathsWillBeCleared => - 'Az elérési utak 5 sikertelen újrapróbálkozás után törlődnek'; + 'Az útvonalak törlődnek, ha minden küldési próbálkozás sikertelen'; @override String get appSettings_pathsWillNotBeCleared => @@ -1449,7 +1449,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Váltson a legjobb útvonalak és a flood mód között'; + 'Minden közvetlen próbálkozásnál másik ismert útvonalat próbál. A későbbiek Flood. Kikapcsolva a kapcsolat jelenlegi útvonalát használja.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1467,6 +1467,33 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Az üzenet sikertelenként való megjelölése előtti újrapróbálkozások száma'; + @override + String appSettings_directRetries(int count) { + return 'Közvetlen próbálkozások: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Hányszor próbáljon ismert útvonalat. Akkor is beállítható, ha az automatikus útvonalváltás ki van kapcsolva.'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood próbálkozások: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Hányszor használjon Floodot. A Flood több adásidőt használ. Bekapcsolt váltásnál a közvetlen próbálkozások után jönnek.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Bejelentkezési próbálkozások: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Hányszor próbáljon bejelentkezni egy átjátszóra vagy room szerverre, mielőtt feladja.'; + @override String get appSettings_ipfsImageLinks => 'IPFS-szolgáltató beállítása'; @@ -7028,15 +7055,15 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Útvonaltervezési algoritmus visszaállítása alapértelmezettre'; + 'Útválasztási beállítások visszaállítása alapértelmezettre'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Útvonaltervezési algoritmus beállításainak visszaállítása gyári alapértelmezett értékekre'; + 'A szakasz útvonalbeállításainak visszaállítása az alapértelmezett értékekre'; @override String get appSettings_routingResetToDefault => - 'Útvonaltervezési algoritmus beállításai visszaállítva alapértelmezettre'; + 'Útválasztási beállítások visszaállítva alapértelmezettre'; @override String get appSettings_imageMessagesSection => 'Képüzenetek'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..e3e38cca 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1440,11 +1440,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Reimposta il percorso di contatto dopo 5 tentativi di invio falliti'; + 'Reimposta il percorso salvato del contatto quando tutti i tentativi di invio falliscono'; @override String get appSettings_pathsWillBeCleared => - 'I percorsi verranno cancellati dopo 5 tentativi falliti.'; + 'I percorsi verranno cancellati quando tutti i tentativi di invio falliscono'; @override String get appSettings_pathsWillNotBeCleared => @@ -1455,7 +1455,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Alterna tra i percorsi migliori e la modalità flood'; + 'A ogni tentativo diretto, prova un altro percorso noto. I tentativi successivi sono Flood. Disattivato mantiene il percorso attuale del contatto.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1473,6 +1473,33 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Numero di tentativi di riprova prima di considerare un messaggio come fallito.'; + @override + String appSettings_directRetries(int count) { + return 'Tentativi diretti: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Quante volte provare un percorso noto. Resta disponibile anche con la rotazione automatica disattivata.'; + + @override + String appSettings_floodRetries(int count) { + return 'Tentativi Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Quante volte usare Flood. Flood usa più tempo in aria. Con la rotazione attiva, seguono i tentativi diretti.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Tentativi di accesso: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Quante volte provare l\'accesso a un ripetitore o a un server room prima di rinunciare.'; + @override String get appSettings_ipfsImageLinks => 'Configurazione del provider IPFS'; @@ -7041,15 +7068,15 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Reimposta algoritmo di instradamento sui valori predefiniti'; + 'Reimposta le impostazioni di instradamento sui valori predefiniti'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Ripristina le impostazioni dell\'algoritmo di instradamento ai valori predefiniti di fabbrica'; + 'Ripristina le impostazioni di instradamento di questa sezione ai valori predefiniti'; @override String get appSettings_routingResetToDefault => - 'Impostazioni algoritmo di instradamento reimpostate sui valori predefiniti'; + 'Impostazioni di instradamento reimpostate sui valori predefiniti'; @override String get appSettings_imageMessagesSection => 'Messaggi immagine'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..f9c76c8b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1370,10 +1370,10 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - '5 回送信に失敗したら連絡先の経路をリセットします'; + 'すべての送信が失敗したら、連絡先の保存済み経路をリセットします'; @override - String get appSettings_pathsWillBeCleared => '5 回失敗すると経路を消去します'; + String get appSettings_pathsWillBeCleared => 'すべての送信が失敗すると経路を消去します'; @override String get appSettings_pathsWillNotBeCleared => '経路は自動では消去されません'; @@ -1382,7 +1382,8 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_autoRouteRotation => '自動経路切り替え'; @override - String get appSettings_autoRouteRotationSubtitle => '最適な経路とフラッドモードを切り替えます'; + String get appSettings_autoRouteRotationSubtitle => + '直接の試行ごとに別の既知の経路を試します。その後の試行は Flood です。オフのときは連絡先の現在の経路を使います。'; @override String get appSettings_autoRouteRotationEnabled => '自動経路切り替えが有効です'; @@ -1396,6 +1397,33 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => 'メッセージを失敗として扱うまでの再試行回数'; + @override + String appSettings_directRetries(int count) { + return '直接の試行: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + '既知の経路を試す回数です。自動経路切り替えがオフでも設定できます。'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood の試行: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Flood する回数です。Flood は通信時間を多く使います。切り替えがオンのとき、直接の試行の後に行います。'; + + @override + String appSettings_loginAttempts(int count) { + return 'ログイン試行: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'リピータまたはルームサーバーへのログインをあきらめるまでの回数です。'; + @override String get appSettings_ipfsImageLinks => 'IPFSプロバイダー設定'; @@ -6708,15 +6736,14 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_routingSection => 'ルーティング'; @override - String get appSettings_resetRoutingToDefault => 'ルーティングアルゴリズムをデフォルトにリセット'; + String get appSettings_resetRoutingToDefault => 'ルーティング設定をデフォルトにリセット'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'ルーティングアルゴリズムの設定を工場出荷時のデフォルトに戻す'; + 'このセクションの経路設定を初期値に戻します'; @override - String get appSettings_routingResetToDefault => - 'ルーティングアルゴリズムの設定がデフォルトにリセットされました'; + String get appSettings_routingResetToDefault => 'ルーティング設定がデフォルトにリセットされました'; @override String get appSettings_imageMessagesSection => '画像メッセージ'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..9a6c10bc 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1373,10 +1373,10 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - '전송 시도가 5번 실패하면 연락 경로를 재설정합니다.'; + '모든 전송 시도가 실패하면 연락처의 저장된 경로를 재설정합니다'; @override - String get appSettings_pathsWillBeCleared => '5번 실패하면 해당 경로를 지웁니다.'; + String get appSettings_pathsWillBeCleared => '모든 전송 시도가 실패하면 경로를 지웁니다'; @override String get appSettings_pathsWillNotBeCleared => '경로를 자동으로 지우지 않습니다.'; @@ -1386,7 +1386,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - '최적 경로와 플러딩 모드 사이를 전환합니다.'; + '직접 시도마다 다른 알려진 경로를 사용합니다. 이후 시도는 Flood입니다. 끄면 연락처의 현재 경로를 유지합니다.'; @override String get appSettings_autoRouteRotationEnabled => '자동 경로 순환 기능 활성화'; @@ -1400,6 +1400,33 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => '메시지를 실패로 처리하기 전 시도 횟수'; + @override + String appSettings_directRetries(int count) { + return '직접 시도: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + '알려진 경로를 시도하는 횟수입니다. 자동 경로 순환을 꺼도 설정할 수 있습니다.'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood 시도: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Flood를 사용하는 횟수입니다. Flood는 전파 시간을 더 씁니다. 순환이 켜져 있으면 직접 시도 다음에 실행됩니다.'; + + @override + String appSettings_loginAttempts(int count) { + return '로그인 시도: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + '중계기나 룸 서버 로그인을 포기하기 전까지의 시도 횟수입니다.'; + @override String get appSettings_ipfsImageLinks => 'IPFS 제공자 설정'; @@ -6724,14 +6751,14 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_routingSection => '라우팅'; @override - String get appSettings_resetRoutingToDefault => '라우팅 알고리즘 기본값으로 재설정'; + String get appSettings_resetRoutingToDefault => '라우팅 설정을 기본값으로 재설정'; @override String get appSettings_resetRoutingToDefaultSubtitle => - '라우팅 알고리즘 설정을 공장 기본값으로 복원'; + '이 섹션의 라우팅 설정을 기본값으로 되돌립니다'; @override - String get appSettings_routingResetToDefault => '라우팅 알고리즘 설정이 기본값으로 재설정되었습니다'; + String get appSettings_routingResetToDefault => '라우팅 설정이 기본값으로 재설정되었습니다'; @override String get appSettings_imageMessagesSection => '이미지 메시지'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..d1c1ace3 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1433,11 +1433,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Reset contactpad na 5 mislukte verzendpogingen'; + 'Het opgeslagen pad van het contact resetten als alle verzendpogingen mislukken'; @override String get appSettings_pathsWillBeCleared => - 'Paden worden gewist na 5 mislukte pogingen'; + 'Paden worden gewist als alle verzendpogingen mislukken'; @override String get appSettings_pathsWillNotBeCleared => @@ -1448,7 +1448,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Wissel tussen beste paden en floodmodus'; + 'Bij elke directe poging een andere bekende route proberen. Latere pogingen zijn Flood. Uit houdt het huidige pad van het contact.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1465,6 +1465,33 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Aantal pogingen om een bericht opnieuw te versturen voordat het als mislukt wordt gemarkeerd'; + @override + String appSettings_directRetries(int count) { + return 'Directe pogingen: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Hoe vaak een bekende route wordt geprobeerd. Blijft beschikbaar als automatische routerotatie uit staat.'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood-pogingen: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Hoe vaak Flood wordt gebruikt. Flood kost meer zendtijd. Met rotatie aan volgen ze op de directe pogingen.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Inlogpogingen: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Hoe vaak wordt geprobeerd in te loggen op een repeater of roomserver voordat het stopt.'; + @override String get appSettings_ipfsImageLinks => 'IPFS-providerconfiguratie'; @@ -7001,15 +7028,15 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Routeringsalgoritme resetten naar standaard'; + 'Routeringsinstellingen resetten naar standaard'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Routeringsalgoritme-instellingen herstellen naar fabrieksstandaardwaarden'; + 'De routeringsinstellingen in dit gedeelte terugzetten naar de standaardwaarden'; @override String get appSettings_routingResetToDefault => - 'Routeringsalgoritme-instellingen gereset naar standaard'; + 'Routeringsinstellingen gereset naar standaard'; @override String get appSettings_imageMessagesSection => 'Afbeeldingsberichten'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..51954827 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1447,11 +1447,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Resetuj ścieżkę kontaktu po 5 nieudanych próbach wysłania'; + 'Resetuj zapisaną ścieżkę kontaktu, gdy wszystkie próby wysłania się nie powiodą'; @override String get appSettings_pathsWillBeCleared => - 'Ścieżka zostanie wyczyszczona po 5 nieudanych próbach.'; + 'Ścieżki zostaną wyczyszczone, gdy wszystkie próby wysłania się nie powiodą'; @override String get appSettings_pathsWillNotBeCleared => @@ -1462,7 +1462,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Przełączaj się między najlepszymi ścieżkami a trybem flood.'; + 'Przy każdej próbie bezpośredniej wypróbuj inną znaną trasę. Późniejsze próby to Flood. Wyłączone zostawia bieżącą ścieżkę kontaktu.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1480,6 +1480,33 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Liczba prób ponownego wysłania wiadomości przed oznaczaniem jej jako nieudanej'; + @override + String appSettings_directRetries(int count) { + return 'Próby bezpośrednie: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Ile razy próbować znanej trasy. Dostępne także przy wyłączonej automatycznej rotacji trasy.'; + + @override + String appSettings_floodRetries(int count) { + return 'Próby Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Ile razy użyć Flood. Flood zużywa więcej czasu antenowego. Przy włączonej rotacji następują po próbach bezpośrednich.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Próby logowania: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Ile razy próbować logowania do przemiennika lub serwera room, zanim aplikacja zrezygnuje.'; + @override String get appSettings_ipfsImageLinks => 'Konfiguracja dostawcy IPFS'; @@ -7075,15 +7102,15 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Resetuj algorytm trasowania do domyślnych'; + 'Resetuj ustawienia trasowania do domyślnych'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Przywróć ustawienia algorytmu trasowania do fabrycznych ustawień domyślnych'; + 'Przywróć ustawienia trasowania w tej sekcji do wartości domyślnych'; @override String get appSettings_routingResetToDefault => - 'Ustawienia algorytmu trasowania zresetowane do domyślnych'; + 'Ustawienia trasowania zresetowane do domyślnych'; @override String get appSettings_imageMessagesSection => 'Wiadomości z obrazami'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..1b367341 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1439,11 +1439,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Redefinir o caminho de contato após 5 tentativas de envio falhas'; + 'Redefinir o caminho salvo do contato quando todas as tentativas de envio falharem'; @override String get appSettings_pathsWillBeCleared => - 'Os caminhos serão limpos após 5 tentativas falhas.'; + 'Os caminhos serão limpos quando todas as tentativas de envio falharem'; @override String get appSettings_pathsWillNotBeCleared => @@ -1454,7 +1454,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Alternar entre os melhores caminhos e o modo Flood'; + 'Em cada tentativa direta, experimentar outra rota conhecida. As tentativas seguintes são Flood. Desligado mantém o caminho atual do contato.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1472,6 +1472,33 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Número de tentativas de reenvio antes de classificar uma mensagem como falha.'; + @override + String appSettings_directRetries(int count) { + return 'Tentativas diretas: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Quantas vezes tentar uma rota conhecida. Continua disponível com a rotação automática de rotas desligada.'; + + @override + String appSettings_floodRetries(int count) { + return 'Tentativas Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Quantas vezes usar Flood. Flood usa mais tempo de ar. Com a rotação ligada, vêm depois das tentativas diretas.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Tentativas de login: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Quantas vezes tentar entrar em um repetidor ou servidor de sala antes de desistir.'; + @override String get appSettings_ipfsImageLinks => 'Configuração do provedor IPFS'; @@ -7026,15 +7053,15 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Redefinir algoritmo de roteamento para o padrão'; + 'Redefinir configurações de roteamento para o padrão'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Restaurar as configurações do algoritmo de roteamento para os valores padrão de fábrica'; + 'Restaurar as configurações de roteamento desta seção para os padrões'; @override String get appSettings_routingResetToDefault => - 'Configurações do algoritmo de roteamento redefinidas para o padrão'; + 'Configurações de roteamento redefinidas para o padrão'; @override String get appSettings_imageMessagesSection => 'Mensagens de imagem'; @@ -8993,11 +9020,11 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Repor o caminho do contacto após 5 tentativas de envio falhadas'; + 'Repor o caminho guardado do contacto quando todas as tentativas de envio falharem'; @override String get appSettings_pathsWillBeCleared => - 'Os caminhos serão limpos após 5 tentativas falhadas'; + 'Os caminhos serão limpos quando todas as tentativas de envio falharem'; @override String get appSettings_pathsWillNotBeCleared => @@ -9008,7 +9035,7 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get appSettings_autoRouteRotationSubtitle => - 'Alterna entre os melhores caminhos e o modo flood'; + 'Em cada tentativa direta, experimentar outro caminho conhecido. As tentativas seguintes são Flood. Desligado mantém o caminho atual do contacto.'; @override String get appSettings_autoRouteRotationEnabled => @@ -9025,6 +9052,33 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { String get appSettings_maxMessageRetriesSubtitle => 'Número de tentativas antes de marcar uma mensagem como falhada'; + @override + String appSettings_directRetries(int count) { + return 'Tentativas diretas: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Quantas vezes tentar um caminho conhecido. Continua disponível com a rotação automática de caminhos desligada.'; + + @override + String appSettings_floodRetries(int count) { + return 'Tentativas Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Quantas vezes usar Flood. Flood usa mais tempo de ar. Com a rotação ligada, vêm a seguir às tentativas diretas.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Tentativas de início de sessão: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Quantas vezes tentar iniciar sessão num repetidor ou servidor de sala antes de desistir.'; + @override String get appSettings_ipfsImageLinks => 'Configuração do fornecedor IPFS'; @@ -14477,15 +14531,15 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get appSettings_resetRoutingToDefault => - 'Repor algoritmo de encaminhamento'; + 'Repor definições de encaminhamento'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Repõe as definições do algoritmo de encaminhamento para os valores de fábrica'; + 'Repor as definições de encaminhamento desta secção para os valores predefinidos'; @override String get appSettings_routingResetToDefault => - 'Definições do algoritmo de encaminhamento repostas'; + 'Definições de encaminhamento repostas'; @override String get appSettings_imageMessagesSection => 'Mensagens de imagem'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..3d4111b2 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1438,11 +1438,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Сбросить маршрут контакта после 5 неудачных попыток отправки'; + 'Сбросить сохранённый маршрут контакта, когда все попытки отправки не удались'; @override String get appSettings_pathsWillBeCleared => - 'Маршруты будут сброшены после 5 неудачных попыток'; + 'Маршруты будут сброшены, когда все попытки отправки не удались'; @override String get appSettings_pathsWillNotBeCleared => @@ -1454,7 +1454,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Циклически переключаться между лучшими маршрутами и режимом Flood'; + 'При каждой прямой попытке пробовать другой известный маршрут. Следующие попытки — Flood. Выключено оставляет текущий маршрут контакта.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1472,6 +1472,33 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Количество попыток повторной отправки сообщения перед тем, как пометить его как неудачное.'; + @override + String appSettings_directRetries(int count) { + return 'Прямые попытки: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Сколько раз пробовать известный маршрут. Доступно и когда автоматическая ротация выключена.'; + + @override + String appSettings_floodRetries(int count) { + return 'Попытки Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Сколько раз использовать Flood. Flood занимает больше эфирного времени. При включённой ротации они идут после прямых попыток.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Попытки входа: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Сколько раз пытаться войти на ретранслятор или room-сервер, прежде чем сдаться.'; + @override String get appSettings_ipfsImageLinks => 'Настройка провайдера IPFS'; @@ -7052,15 +7079,15 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Сбросить алгоритм маршрутизации к значению по умолчанию'; + 'Сбросить настройки маршрутизации к значениям по умолчанию'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Восстановить настройки алгоритма маршрутизации к заводским значениям по умолчанию'; + 'Вернуть настройки маршрутизации в этом разделе к значениям по умолчанию'; @override String get appSettings_routingResetToDefault => - 'Настройки алгоритма маршрутизации сброшены к значению по умолчанию'; + 'Настройки маршрутизации сброшены к значениям по умолчанию'; @override String get appSettings_imageMessagesSection => 'Сообщения-изображения'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..932b79d4 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1433,11 +1433,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Resetovať cestu kontaktu po 5 neúspešných pokusoch o odoslanie'; + 'Resetovať uloženú cestu kontaktu, keď zlyhajú všetky pokusy o odoslanie'; @override String get appSettings_pathsWillBeCleared => - 'Cesty budú vymazané po 5 neúspešných pokusoch.'; + 'Cesty sa vymažú, keď zlyhajú všetky pokusy o odoslanie'; @override String get appSettings_pathsWillNotBeCleared => @@ -1448,7 +1448,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Striedajte sa medzi najlepšími trasami a flood režimom.'; + 'Pri každom priamom pokuse skúsiť inú známu trasu. Neskoršie pokusy sú Flood. Vypnuté ponechá aktuálnu cestu kontaktu.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1466,6 +1466,33 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Počet opakovaných pokusov pred označením správy ako neúspešnej'; + @override + String appSettings_directRetries(int count) { + return 'Priame pokusy: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Koľkokrát sa skúsi známa trasa. Dostupné aj keď je automatické striedanie trás vypnuté.'; + + @override + String appSettings_floodRetries(int count) { + return 'Pokusy Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Koľkokrát sa použije Flood. Flood zaberie viac vysielacieho času. Pri zapnutom striedaní nasledujú po priamych pokusoch.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Pokusy o prihlásenie: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Koľkokrát sa skúsi prihlásenie k opakovaču alebo room serveru, kým sa to vzdá.'; + @override String get appSettings_ipfsImageLinks => 'Konfigurácia poskytovateľa IPFS'; @@ -7025,15 +7052,15 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Obnoviť algoritmus smerovania na predvolené'; + 'Obnoviť nastavenia smerovania na predvolené'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Obnoviť nastavenia algoritmu smerovania na továrne predvolené hodnoty'; + 'Obnoviť nastavenia smerovania v tejto časti na predvolené hodnoty'; @override String get appSettings_routingResetToDefault => - 'Nastavenia algoritmu smerovania obnovené na predvolené'; + 'Nastavenia smerovania obnovené na predvolené'; @override String get appSettings_imageMessagesSection => 'Obrazové správy'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..40527806 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1431,11 +1431,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Ponastavi pot stika po 5 neuspelih poskusih pošiljanja'; + 'Ponastavi shranjeno pot stika, ko spodletijo vsi poskusi pošiljanja'; @override String get appSettings_pathsWillBeCleared => - 'Poti bodo počiščene po 5 neuspelih poskusih.'; + 'Poti se počistijo, ko spodletijo vsi poskusi pošiljanja'; @override String get appSettings_pathsWillNotBeCleared => @@ -1446,7 +1446,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Izmenjuj najboljše poti in flood način'; + 'Ob vsakem neposrednem poskusu preizkusi drugo znano pot. Kasnejši poskusi so Flood. Izklopljeno ohrani trenutno pot stika.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1464,6 +1464,33 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Število poskusov ponovnega poslanja, preden se sporočilo označuje kot neuspešno'; + @override + String appSettings_directRetries(int count) { + return 'Neposredni poskusi: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Kolikokrat se preizkusi znana pot. Na voljo tudi, ko je samodejno kroženje poti izklopljeno.'; + + @override + String appSettings_floodRetries(int count) { + return 'Poskusi Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Kolikokrat se uporabi Flood. Flood porabi več oddajnega časa. Ob vklopljenem kroženju sledijo neposrednim poskusom.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Poskusi prijave: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Kolikokrat se poskusi prijava v ponavljalnik ali room strežnik, preden obupa.'; + @override String get appSettings_ipfsImageLinks => 'Konfiguracija ponudnika IPFS'; @@ -7013,15 +7040,15 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Ponastavite algoritem usmerjanja na privzeto'; + 'Ponastavi nastavitve usmerjanja na privzete'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Obnovite nastavitve algoritma usmerjanja na tovarniške privzetke'; + 'Obnovi nastavitve usmerjanja v tem razdelku na privzete vrednosti'; @override String get appSettings_routingResetToDefault => - 'Nastavitve algoritma usmerjanja so ponastavljene na privzeto'; + 'Nastavitve usmerjanja so ponastavljene na privzete'; @override String get appSettings_imageMessagesSection => 'Sporočila s slikami'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..fae3713e 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1421,11 +1421,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Återställ kontaktens rutt efter 5 misslyckade sändningsförsök'; + 'Återställ kontaktens sparade rutt när alla sändningsförsök misslyckas'; @override String get appSettings_pathsWillBeCleared => - 'Rutter rensas efter 5 misslyckade försök'; + 'Rutter rensas när alla sändningsförsök misslyckas'; @override String get appSettings_pathsWillNotBeCleared => @@ -1436,7 +1436,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Växla mellan de bästa rutterna och flood-läge'; + 'Vid varje direkt försök, prova en annan känd rutt. Senare försök är Flood. Av behåller kontaktens aktuella rutt.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1453,6 +1453,33 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Antal försök att skicka om ett meddelande innan det markeras som misslyckat.'; + @override + String appSettings_directRetries(int count) { + return 'Direkta försök: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Hur många gånger en känd rutt provas. Finns kvar även när automatisk ruttrotation är av.'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood-försök: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Hur många gånger Flood används. Flood tar mer sändningstid. Med rotation på kommer de efter de direkta försöken.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Inloggningsförsök: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Hur många gånger inloggning till en repeater eller room-server provas innan den ger upp.'; + @override String get appSettings_ipfsImageLinks => 'Konfiguration av IPFS-leverantör'; @@ -6980,15 +7007,15 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Återställ rutningsalgoritm till standard'; + 'Återställ rutningsinställningar till standard'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Återställ rutningsalgoritmins inställningar till fabriksstandard'; + 'Återställ routningsinställningarna i det här avsnittet till standardvärden'; @override String get appSettings_routingResetToDefault => - 'Rutningsalgoritmins inställningar återställda till standard'; + 'Rutningsinställningar återställda till standard'; @override String get appSettings_imageMessagesSection => 'Bildmeddelanden'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..32159140 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1433,11 +1433,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Скидати шлях до контакту після 5 невдалих спроб надсилання'; + 'Скинути збережений шлях контакту, коли всі спроби надсилання не вдаються'; @override String get appSettings_pathsWillBeCleared => - 'Шляхи будуть очищені після 5 невдалих спроб.'; + 'Шляхи буде очищено, коли всі спроби надсилання не вдадуться'; @override String get appSettings_pathsWillNotBeCleared => @@ -1448,7 +1448,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Чергувати найкращі шляхи та режим Flood'; + 'На кожній прямій спробі пробувати інший відомий маршрут. Наступні спроби — Flood. Вимкнено залишає поточний шлях контакту.'; @override String get appSettings_autoRouteRotationEnabled => @@ -1466,6 +1466,33 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Кількість спроб повторного відправлення повідомлення перед тим, як позначити його як невдале'; + @override + String appSettings_directRetries(int count) { + return 'Прямі спроби: $count'; + } + + @override + String get appSettings_directRetriesSubtitle => + 'Скільки разів пробувати відомий маршрут. Доступно і коли авторотацію вимкнено.'; + + @override + String appSettings_floodRetries(int count) { + return 'Спроби Flood: $count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + 'Скільки разів використовувати Flood. Flood займає більше ефірного часу. Якщо ротацію ввімкнено, вони йдуть після прямих спроб.'; + + @override + String appSettings_loginAttempts(int count) { + return 'Спроби входу: $count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => + 'Скільки разів пробувати вхід до ретранслятора або room-сервера, перш ніж здатися.'; + @override String get appSettings_ipfsImageLinks => 'Налаштування IPFS-провайдера'; @@ -7060,15 +7087,15 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_resetRoutingToDefault => - 'Скинути алгоритм маршрутизації до типового'; + 'Скинути налаштування маршрутизації до типових'; @override String get appSettings_resetRoutingToDefaultSubtitle => - 'Відновити налаштування алгоритму маршрутизації до заводських значень за замовчуванням'; + 'Відновити налаштування маршрутизації в цьому розділі до значень за замовчуванням'; @override String get appSettings_routingResetToDefault => - 'Налаштування алгоритму маршрутизації скинуто до типових'; + 'Налаштування маршрутизації скинуто до типових'; @override String get appSettings_imageMessagesSection => 'Повідомлення із зображеннями'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..a1d5c7f1 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1347,10 +1347,11 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_clearPathOnMaxRetry => '达到最大重试次数时清除路径'; @override - String get appSettings_clearPathOnMaxRetrySubtitle => '在5次发送失败后重置联系路径。'; + String get appSettings_clearPathOnMaxRetrySubtitle => + '所有发送尝试都失败后,重置联系人已保存的路径'; @override - String get appSettings_pathsWillBeCleared => '5次失败后将重新路由'; + String get appSettings_pathsWillBeCleared => '所有发送尝试失败后将清除路径'; @override String get appSettings_pathsWillNotBeCleared => '路径不会自动清除'; @@ -1359,7 +1360,8 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_autoRouteRotation => '自动路径轮换'; @override - String get appSettings_autoRouteRotationSubtitle => '在最佳路径和泛洪模式之间切换'; + String get appSettings_autoRouteRotationSubtitle => + '每次直接尝试换一条已知路由。之后的尝试使用 Flood。关闭后保持联系人的当前路径。'; @override String get appSettings_autoRouteRotationEnabled => '自动路径轮换已启用'; @@ -1373,6 +1375,31 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => '在将消息标记为失败之前,允许尝试的次数'; + @override + String appSettings_directRetries(int count) { + return '直接尝试:$count'; + } + + @override + String get appSettings_directRetriesSubtitle => '尝试已知路由的次数。关闭自动路径轮换后仍然可以设置。'; + + @override + String appSettings_floodRetries(int count) { + return 'Flood 尝试:$count'; + } + + @override + String get appSettings_floodRetriesSubtitle => + '使用 Flood 的次数。Flood 占用更多空中时间。开启轮换时,这些尝试排在直接尝试之后。'; + + @override + String appSettings_loginAttempts(int count) { + return '登录尝试:$count'; + } + + @override + String get appSettings_loginAttemptsSubtitle => '登录中继或房间服务器时,放弃前的尝试次数。'; + @override String get appSettings_ipfsImageLinks => 'IPFS 提供商配置'; @@ -6561,13 +6588,13 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_routingSection => '路由'; @override - String get appSettings_resetRoutingToDefault => '将路由算法重置为默认值'; + String get appSettings_resetRoutingToDefault => '将路由设置重置为默认值'; @override - String get appSettings_resetRoutingToDefaultSubtitle => '将路由算法设置恢复为出厂默认值'; + String get appSettings_resetRoutingToDefaultSubtitle => '将本部分的路由设置恢复为默认值'; @override - String get appSettings_routingResetToDefault => '路由算法设置已重置为默认值'; + String get appSettings_routingResetToDefault => '路由设置已重置为默认值'; @override String get appSettings_imageMessagesSection => '图片消息'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 2f192869..5a7dbd73 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -203,11 +203,11 @@ "appSettings_advertisementNotificationsSubtitle": "Toon notificatie wanneer nieuwe nodes worden ontdekt", "appSettings_messaging": "Berichten", "appSettings_clearPathOnMaxRetry": "Pad wissen na max. pogingen", - "appSettings_clearPathOnMaxRetrySubtitle": "Reset contactpad na 5 mislukte verzendpogingen", - "appSettings_pathsWillBeCleared": "Paden worden gewist na 5 mislukte pogingen", + "appSettings_clearPathOnMaxRetrySubtitle": "Het opgeslagen pad van het contact resetten als alle verzendpogingen mislukken", + "appSettings_pathsWillBeCleared": "Paden worden gewist als alle verzendpogingen mislukken", "appSettings_pathsWillNotBeCleared": "Paden worden niet automatisch gewist", "appSettings_autoRouteRotation": "Route Automatisch Roteren", - "appSettings_autoRouteRotationSubtitle": "Wissel tussen beste paden en floodmodus", + "appSettings_autoRouteRotationSubtitle": "Bij elke directe poging een andere bekende route proberen. Latere pogingen zijn Flood. Uit houdt het huidige pad van het contact.", "appSettings_autoRouteRotationEnabled": "Automatische route rotatie ingeschakeld", "appSettings_autoRouteRotationDisabled": "Automatische route rotatie is uitgeschakeld", "appSettings_battery": "Batterij", @@ -3254,9 +3254,9 @@ "settings_regionFetchNoneResponded": "Geen repeaters in de buurt hebben geantwoord. Ga dichter bij een repeater staan en probeer het opnieuw.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Routering", - "appSettings_resetRoutingToDefault": "Routeringsalgoritme resetten naar standaard", - "appSettings_resetRoutingToDefaultSubtitle": "Routeringsalgoritme-instellingen herstellen naar fabrieksstandaardwaarden", - "appSettings_routingResetToDefault": "Routeringsalgoritme-instellingen gereset naar standaard", + "appSettings_resetRoutingToDefault": "Routeringsinstellingen resetten naar standaard", + "appSettings_resetRoutingToDefaultSubtitle": "De routeringsinstellingen in dit gedeelte terugzetten naar de standaardwaarden", + "appSettings_routingResetToDefault": "Routeringsinstellingen gereset naar standaard", "appSettings_imageMessagesSection": "Afbeeldingsberichten", "appSettings_showApiKey": "API-sleutel tonen", "appSettings_hideApiKey": "API-sleutel verbergen", @@ -3677,5 +3677,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB of TCP", "connectSheet_stopReconnecting": "Opnieuw verbinden stoppen", "connectSheet_reconnectFailed": "Kan {name} niet bereiken. Controleer of het aan staat en in de buurt is.", - "chat_composerOffline": "Verbind met een radio om berichten te versturen" + "chat_composerOffline": "Verbind met een radio om berichten te versturen", + "appSettings_directRetries": "Directe pogingen: {count}", + "appSettings_directRetriesSubtitle": "Hoe vaak een bekende route wordt geprobeerd. Blijft beschikbaar als automatische routerotatie uit staat.", + "appSettings_floodRetries": "Flood-pogingen: {count}", + "appSettings_floodRetriesSubtitle": "Hoe vaak Flood wordt gebruikt. Flood kost meer zendtijd. Met rotatie aan volgen ze op de directe pogingen.", + "appSettings_loginAttempts": "Inlogpogingen: {count}", + "appSettings_loginAttemptsSubtitle": "Hoe vaak wordt geprobeerd in te loggen op een repeater of roomserver voordat het stopt." } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index af3783a1..f0abd6ed 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Wyświetl powiadomienie, gdy zostaną wykryte nowe węzły.", "appSettings_messaging": "Wiadomości", "appSettings_clearPathOnMaxRetry": "Wyczyść ścieżkę po maks. liczbie prób", - "appSettings_clearPathOnMaxRetrySubtitle": "Resetuj ścieżkę kontaktu po 5 nieudanych próbach wysłania", - "appSettings_pathsWillBeCleared": "Ścieżka zostanie wyczyszczona po 5 nieudanych próbach.", + "appSettings_clearPathOnMaxRetrySubtitle": "Resetuj zapisaną ścieżkę kontaktu, gdy wszystkie próby wysłania się nie powiodą", + "appSettings_pathsWillBeCleared": "Ścieżki zostaną wyczyszczone, gdy wszystkie próby wysłania się nie powiodą", "appSettings_pathsWillNotBeCleared": "Ścieżka nie zostanie automatycznie wyczyszczona.", "appSettings_autoRouteRotation": "Automatyczna rotacja trasy", - "appSettings_autoRouteRotationSubtitle": "Przełączaj się między najlepszymi ścieżkami a trybem flood.", + "appSettings_autoRouteRotationSubtitle": "Przy każdej próbie bezpośredniej wypróbuj inną znaną trasę. Późniejsze próby to Flood. Wyłączone zostawia bieżącą ścieżkę kontaktu.", "appSettings_autoRouteRotationEnabled": "Automatyczne obracanie tras włączone", "appSettings_autoRouteRotationDisabled": "Automatyczne obracanie tras wyłączone", "appSettings_battery": "Bateria", @@ -3386,9 +3386,9 @@ "settings_regionFetchNoneResponded": "Żaden pobliski przekaźnik nie odpowiedział. Zbliż się do przekaźnika i spróbuj ponownie.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Routing", - "appSettings_resetRoutingToDefault": "Resetuj algorytm trasowania do domyślnych", - "appSettings_resetRoutingToDefaultSubtitle": "Przywróć ustawienia algorytmu trasowania do fabrycznych ustawień domyślnych", - "appSettings_routingResetToDefault": "Ustawienia algorytmu trasowania zresetowane do domyślnych", + "appSettings_resetRoutingToDefault": "Resetuj ustawienia trasowania do domyślnych", + "appSettings_resetRoutingToDefaultSubtitle": "Przywróć ustawienia trasowania w tej sekcji do wartości domyślnych", + "appSettings_routingResetToDefault": "Ustawienia trasowania zresetowane do domyślnych", "appSettings_imageMessagesSection": "Wiadomości z obrazami", "appSettings_showApiKey": "Pokaż klucz API", "appSettings_hideApiKey": "Ukryj klucz API", @@ -4015,5 +4015,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB lub TCP", "connectSheet_stopReconnecting": "Zatrzymaj ponowne łączenie", "connectSheet_reconnectFailed": "Nie można połączyć z {name}. Upewnij się, że jest włączone i w pobliżu.", - "chat_composerOffline": "Połącz się z radiem, aby wysyłać wiadomości" + "chat_composerOffline": "Połącz się z radiem, aby wysyłać wiadomości", + "appSettings_directRetries": "Próby bezpośrednie: {count}", + "appSettings_directRetriesSubtitle": "Ile razy próbować znanej trasy. Dostępne także przy wyłączonej automatycznej rotacji trasy.", + "appSettings_floodRetries": "Próby Flood: {count}", + "appSettings_floodRetriesSubtitle": "Ile razy użyć Flood. Flood zużywa więcej czasu antenowego. Przy włączonej rotacji następują po próbach bezpośrednich.", + "appSettings_loginAttempts": "Próby logowania: {count}", + "appSettings_loginAttemptsSubtitle": "Ile razy próbować logowania do przemiennika lub serwera room, zanim aplikacja zrezygnuje." } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index ad24e07a..9b7c454a 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Mostrar notificação quando novos nós forem descobertos", "appSettings_messaging": "Mensagens", "appSettings_clearPathOnMaxRetry": "Limpar Caminho em Tentativas Máximas", - "appSettings_clearPathOnMaxRetrySubtitle": "Redefinir o caminho de contato após 5 tentativas de envio falhas", - "appSettings_pathsWillBeCleared": "Os caminhos serão limpos após 5 tentativas falhas.", + "appSettings_clearPathOnMaxRetrySubtitle": "Redefinir o caminho salvo do contato quando todas as tentativas de envio falharem", + "appSettings_pathsWillBeCleared": "Os caminhos serão limpos quando todas as tentativas de envio falharem", "appSettings_pathsWillNotBeCleared": "Os caminhos não serão limpos automaticamente.", "appSettings_autoRouteRotation": "Rotação de Rota Automática", - "appSettings_autoRouteRotationSubtitle": "Alternar entre os melhores caminhos e o modo Flood", + "appSettings_autoRouteRotationSubtitle": "Em cada tentativa direta, experimentar outra rota conhecida. As tentativas seguintes são Flood. Desligado mantém o caminho atual do contato.", "appSettings_autoRouteRotationEnabled": "Rotação de roteamento automático habilitada", "appSettings_autoRouteRotationDisabled": "Rotação de roteamento automático desativada", "appSettings_battery": "Bateria", @@ -3239,9 +3239,9 @@ "settings_regionFetchNoneResponded": "Nenhum repetidor próximo respondeu. Aproxime-se de um repetidor e tente novamente.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Roteamento", - "appSettings_resetRoutingToDefault": "Redefinir algoritmo de roteamento para o padrão", - "appSettings_resetRoutingToDefaultSubtitle": "Restaurar as configurações do algoritmo de roteamento para os valores padrão de fábrica", - "appSettings_routingResetToDefault": "Configurações do algoritmo de roteamento redefinidas para o padrão", + "appSettings_resetRoutingToDefault": "Redefinir configurações de roteamento para o padrão", + "appSettings_resetRoutingToDefaultSubtitle": "Restaurar as configurações de roteamento desta seção para os padrões", + "appSettings_routingResetToDefault": "Configurações de roteamento redefinidas para o padrão", "appSettings_imageMessagesSection": "Mensagens de imagem", "appSettings_showApiKey": "Mostrar chave de API", "appSettings_hideApiKey": "Ocultar chave de API", @@ -3828,5 +3828,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ou TCP", "connectSheet_stopReconnecting": "Parar de reconectar", "connectSheet_reconnectFailed": "Não foi possível alcançar {name}. Verifique se está ligado e por perto.", - "chat_composerOffline": "Conecte-se a um rádio para enviar mensagens" + "chat_composerOffline": "Conecte-se a um rádio para enviar mensagens", + "appSettings_directRetries": "Tentativas diretas: {count}", + "appSettings_directRetriesSubtitle": "Quantas vezes tentar uma rota conhecida. Continua disponível com a rotação automática de rotas desligada.", + "appSettings_floodRetries": "Tentativas Flood: {count}", + "appSettings_floodRetriesSubtitle": "Quantas vezes usar Flood. Flood usa mais tempo de ar. Com a rotação ligada, vêm depois das tentativas diretas.", + "appSettings_loginAttempts": "Tentativas de login: {count}", + "appSettings_loginAttemptsSubtitle": "Quantas vezes tentar entrar em um repetidor ou servidor de sala antes de desistir." } diff --git a/lib/l10n/app_pt_PT.arb b/lib/l10n/app_pt_PT.arb index 80218599..5b326773 100644 --- a/lib/l10n/app_pt_PT.arb +++ b/lib/l10n/app_pt_PT.arb @@ -415,11 +415,11 @@ "appSettings_advertisementNotificationsSubtitle": "Mostrar notificação quando são descobertos novos nós", "appSettings_messaging": "Mensagens", "appSettings_clearPathOnMaxRetry": "Limpar caminho no máx. de tentativas", - "appSettings_clearPathOnMaxRetrySubtitle": "Repor o caminho do contacto após 5 tentativas de envio falhadas", - "appSettings_pathsWillBeCleared": "Os caminhos serão limpos após 5 tentativas falhadas", + "appSettings_clearPathOnMaxRetrySubtitle": "Repor o caminho guardado do contacto quando todas as tentativas de envio falharem", + "appSettings_pathsWillBeCleared": "Os caminhos serão limpos quando todas as tentativas de envio falharem", "appSettings_pathsWillNotBeCleared": "Os caminhos não serão limpos automaticamente", "appSettings_autoRouteRotation": "Rotação automática de rotas", - "appSettings_autoRouteRotationSubtitle": "Alterna entre os melhores caminhos e o modo flood", + "appSettings_autoRouteRotationSubtitle": "Em cada tentativa direta, experimentar outro caminho conhecido. As tentativas seguintes são Flood. Desligado mantém o caminho atual do contacto.", "appSettings_autoRouteRotationEnabled": "Rotação automática de rotas ativada", "appSettings_autoRouteRotationDisabled": "Rotação automática de rotas desativada", "appSettings_maxMessageRetries": "Máx. de tentativas por mensagem", @@ -1907,9 +1907,9 @@ "settings_regionFetchNoneResponded": "Nenhum repetidor próximo respondeu. Aproxime-se de um repetidor e tente novamente.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Encaminhamento", - "appSettings_resetRoutingToDefault": "Repor algoritmo de encaminhamento", - "appSettings_resetRoutingToDefaultSubtitle": "Repõe as definições do algoritmo de encaminhamento para os valores de fábrica", - "appSettings_routingResetToDefault": "Definições do algoritmo de encaminhamento repostas", + "appSettings_resetRoutingToDefault": "Repor definições de encaminhamento", + "appSettings_resetRoutingToDefaultSubtitle": "Repor as definições de encaminhamento desta secção para os valores predefinidos", + "appSettings_routingResetToDefault": "Definições de encaminhamento repostas", "appSettings_imageMessagesSection": "Mensagens de imagem", "appSettings_showApiKey": "Mostrar chave API", "appSettings_hideApiKey": "Ocultar chave API", @@ -2055,5 +2055,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ou TCP", "connectSheet_stopReconnecting": "Parar de religar", "connectSheet_reconnectFailed": "Não foi possível contactar {name}. Verifique se está ligado e por perto.", - "chat_composerOffline": "Ligue-se a um rádio para enviar mensagens" + "chat_composerOffline": "Ligue-se a um rádio para enviar mensagens", + "appSettings_directRetries": "Tentativas diretas: {count}", + "appSettings_directRetriesSubtitle": "Quantas vezes tentar um caminho conhecido. Continua disponível com a rotação automática de caminhos desligada.", + "appSettings_floodRetries": "Tentativas Flood: {count}", + "appSettings_floodRetriesSubtitle": "Quantas vezes usar Flood. Flood usa mais tempo de ar. Com a rotação ligada, vêm a seguir às tentativas diretas.", + "appSettings_loginAttempts": "Tentativas de início de sessão: {count}", + "appSettings_loginAttemptsSubtitle": "Quantas vezes tentar iniciar sessão num repetidor ou servidor de sala antes de desistir." } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index f5ff336c..2bf49032 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -162,11 +162,11 @@ "appSettings_advertisementNotificationsSubtitle": "Показывать уведомление при обнаружении новых нод", "appSettings_messaging": "Обмен сообщениями", "appSettings_clearPathOnMaxRetry": "Сбросить маршрут после максимального числа попыток", - "appSettings_clearPathOnMaxRetrySubtitle": "Сбросить маршрут контакта после 5 неудачных попыток отправки", - "appSettings_pathsWillBeCleared": "Маршруты будут сброшены после 5 неудачных попыток", + "appSettings_clearPathOnMaxRetrySubtitle": "Сбросить сохранённый маршрут контакта, когда все попытки отправки не удались", + "appSettings_pathsWillBeCleared": "Маршруты будут сброшены, когда все попытки отправки не удались", "appSettings_pathsWillNotBeCleared": "Маршруты не будут автоматически сбрасываться", "appSettings_autoRouteRotation": "Автоматическое переключение маршрутов", - "appSettings_autoRouteRotationSubtitle": "Циклически переключаться между лучшими маршрутами и режимом Flood", + "appSettings_autoRouteRotationSubtitle": "При каждой прямой попытке пробовать другой известный маршрут. Следующие попытки — Flood. Выключено оставляет текущий маршрут контакта.", "appSettings_autoRouteRotationEnabled": "Автоматическое переключение маршрутов включено", "appSettings_autoRouteRotationDisabled": "Автоматическое переключение маршрутов отключено", "appSettings_battery": "Батарея", @@ -2650,9 +2650,9 @@ "settings_regionFetchNoneResponded": "Ближайшие репитеры не ответили. Подойдите ближе к репитеру и повторите попытку.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Маршрутизация", - "appSettings_resetRoutingToDefault": "Сбросить алгоритм маршрутизации к значению по умолчанию", - "appSettings_resetRoutingToDefaultSubtitle": "Восстановить настройки алгоритма маршрутизации к заводским значениям по умолчанию", - "appSettings_routingResetToDefault": "Настройки алгоритма маршрутизации сброшены к значению по умолчанию", + "appSettings_resetRoutingToDefault": "Сбросить настройки маршрутизации к значениям по умолчанию", + "appSettings_resetRoutingToDefaultSubtitle": "Вернуть настройки маршрутизации в этом разделе к значениям по умолчанию", + "appSettings_routingResetToDefault": "Настройки маршрутизации сброшены к значениям по умолчанию", "appSettings_imageMessagesSection": "Сообщения-изображения", "appSettings_showApiKey": "Показать API-ключ", "appSettings_hideApiKey": "Скрыть API-ключ", @@ -3073,5 +3073,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB или TCP", "connectSheet_stopReconnecting": "Остановить переподключение", "connectSheet_reconnectFailed": "Не удалось связаться с {name}. Убедитесь, что оно включено и находится рядом.", - "chat_composerOffline": "Подключитесь к радио, чтобы отправлять сообщения" + "chat_composerOffline": "Подключитесь к радио, чтобы отправлять сообщения", + "appSettings_directRetries": "Прямые попытки: {count}", + "appSettings_directRetriesSubtitle": "Сколько раз пробовать известный маршрут. Доступно и когда автоматическая ротация выключена.", + "appSettings_floodRetries": "Попытки Flood: {count}", + "appSettings_floodRetriesSubtitle": "Сколько раз использовать Flood. Flood занимает больше эфирного времени. При включённой ротации они идут после прямых попыток.", + "appSettings_loginAttempts": "Попытки входа: {count}", + "appSettings_loginAttemptsSubtitle": "Сколько раз пытаться войти на ретранслятор или room-сервер, прежде чем сдаться." } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index c582c8f4..c4c5e618 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Zobraziť upozornenie, keď sa objavia nové uzly.", "appSettings_messaging": "Správy", "appSettings_clearPathOnMaxRetry": "Vymazať cestu pri maximálnom počte pokusov", - "appSettings_clearPathOnMaxRetrySubtitle": "Resetovať cestu kontaktu po 5 neúspešných pokusoch o odoslanie", - "appSettings_pathsWillBeCleared": "Cesty budú vymazané po 5 neúspešných pokusoch.", + "appSettings_clearPathOnMaxRetrySubtitle": "Resetovať uloženú cestu kontaktu, keď zlyhajú všetky pokusy o odoslanie", + "appSettings_pathsWillBeCleared": "Cesty sa vymažú, keď zlyhajú všetky pokusy o odoslanie", "appSettings_pathsWillNotBeCleared": "Cesty sa automaticky nevymazávajú.", "appSettings_autoRouteRotation": "Automatické striedanie trás", - "appSettings_autoRouteRotationSubtitle": "Striedajte sa medzi najlepšími trasami a flood režimom.", + "appSettings_autoRouteRotationSubtitle": "Pri každom priamom pokuse skúsiť inú známu trasu. Neskoršie pokusy sú Flood. Vypnuté ponechá aktuálnu cestu kontaktu.", "appSettings_autoRouteRotationEnabled": "Automatické striedanie trás je zapnuté", "appSettings_autoRouteRotationDisabled": "Automatické striedanie trás je vypnuté", "appSettings_battery": "Batéria", @@ -3354,9 +3354,9 @@ "settings_regionFetchNoneResponded": "Blízke opakovače neodpovedali. Priblížte sa k opakovaču a skúste to znova.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Smerovanie", - "appSettings_resetRoutingToDefault": "Obnoviť algoritmus smerovania na predvolené", - "appSettings_resetRoutingToDefaultSubtitle": "Obnoviť nastavenia algoritmu smerovania na továrne predvolené hodnoty", - "appSettings_routingResetToDefault": "Nastavenia algoritmu smerovania obnovené na predvolené", + "appSettings_resetRoutingToDefault": "Obnoviť nastavenia smerovania na predvolené", + "appSettings_resetRoutingToDefaultSubtitle": "Obnoviť nastavenia smerovania v tejto časti na predvolené hodnoty", + "appSettings_routingResetToDefault": "Nastavenia smerovania obnovené na predvolené", "appSettings_imageMessagesSection": "Obrazové správy", "appSettings_showApiKey": "Zobraziť API kľúč", "appSettings_hideApiKey": "Skryť API kľúč", @@ -3829,5 +3829,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB alebo TCP", "connectSheet_stopReconnecting": "Zastaviť pripájanie", "connectSheet_reconnectFailed": "Nedá sa spojiť s {name}. Uistite sa, že je zapnuté a nablízku.", - "chat_composerOffline": "Na odosielanie správ sa pripojte k rádiu" + "chat_composerOffline": "Na odosielanie správ sa pripojte k rádiu", + "appSettings_directRetries": "Priame pokusy: {count}", + "appSettings_directRetriesSubtitle": "Koľkokrát sa skúsi známa trasa. Dostupné aj keď je automatické striedanie trás vypnuté.", + "appSettings_floodRetries": "Pokusy Flood: {count}", + "appSettings_floodRetriesSubtitle": "Koľkokrát sa použije Flood. Flood zaberie viac vysielacieho času. Pri zapnutom striedaní nasledujú po priamych pokusoch.", + "appSettings_loginAttempts": "Pokusy o prihlásenie: {count}", + "appSettings_loginAttemptsSubtitle": "Koľkokrát sa skúsi prihlásenie k opakovaču alebo room serveru, kým sa to vzdá." } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 3dcbeb94..53088560 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Pokaži obvestilo, ko so najdene nove naprave.", "appSettings_messaging": "Komuniciranje", "appSettings_clearPathOnMaxRetry": "Počisti pot ob največ poskusih", - "appSettings_clearPathOnMaxRetrySubtitle": "Ponastavi pot stika po 5 neuspelih poskusih pošiljanja", - "appSettings_pathsWillBeCleared": "Poti bodo počiščene po 5 neuspelih poskusih.", + "appSettings_clearPathOnMaxRetrySubtitle": "Ponastavi shranjeno pot stika, ko spodletijo vsi poskusi pošiljanja", + "appSettings_pathsWillBeCleared": "Poti se počistijo, ko spodletijo vsi poskusi pošiljanja", "appSettings_pathsWillNotBeCleared": "Poti ne bodo samodejno počiščene.", "appSettings_autoRouteRotation": "Samodejno kroženje poti", - "appSettings_autoRouteRotationSubtitle": "Izmenjuj najboljše poti in flood način", + "appSettings_autoRouteRotationSubtitle": "Ob vsakem neposrednem poskusu preizkusi drugo znano pot. Kasnejši poskusi so Flood. Izklopljeno ohrani trenutno pot stika.", "appSettings_autoRouteRotationEnabled": "Samodejno kroženje poti omogočeno", "appSettings_autoRouteRotationDisabled": "Samodejno kroženje poti onemogočeno", "appSettings_battery": "Baterija", @@ -3240,9 +3240,9 @@ "settings_regionFetchNoneResponded": "Noben bližnji ponovitelj ni odgovoril. Približajte se ponovitelju in poskusite znova.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Usmerjanje", - "appSettings_resetRoutingToDefault": "Ponastavite algoritem usmerjanja na privzeto", - "appSettings_resetRoutingToDefaultSubtitle": "Obnovite nastavitve algoritma usmerjanja na tovarniške privzetke", - "appSettings_routingResetToDefault": "Nastavitve algoritma usmerjanja so ponastavljene na privzeto", + "appSettings_resetRoutingToDefault": "Ponastavi nastavitve usmerjanja na privzete", + "appSettings_resetRoutingToDefaultSubtitle": "Obnovi nastavitve usmerjanja v tem razdelku na privzete vrednosti", + "appSettings_routingResetToDefault": "Nastavitve usmerjanja so ponastavljene na privzete", "appSettings_imageMessagesSection": "Sporočila s slikami", "appSettings_showApiKey": "Pokaži API ključ", "appSettings_hideApiKey": "Skrij API ključ", @@ -3983,5 +3983,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB ali TCP", "connectSheet_stopReconnecting": "Ustavi ponovno povezovanje", "connectSheet_reconnectFailed": "Ni mogoče doseči {name}. Preverite, ali je vklopljen in v bližini.", - "chat_composerOffline": "Za pošiljanje sporočil se povežite z radiem" + "chat_composerOffline": "Za pošiljanje sporočil se povežite z radiem", + "appSettings_directRetries": "Neposredni poskusi: {count}", + "appSettings_directRetriesSubtitle": "Kolikokrat se preizkusi znana pot. Na voljo tudi, ko je samodejno kroženje poti izklopljeno.", + "appSettings_floodRetries": "Poskusi Flood: {count}", + "appSettings_floodRetriesSubtitle": "Kolikokrat se uporabi Flood. Flood porabi več oddajnega časa. Ob vklopljenem kroženju sledijo neposrednim poskusom.", + "appSettings_loginAttempts": "Poskusi prijave: {count}", + "appSettings_loginAttemptsSubtitle": "Kolikokrat se poskusi prijava v ponavljalnik ali room strežnik, preden obupa." } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 7ec4e120..64039433 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -198,11 +198,11 @@ "appSettings_advertisementNotificationsSubtitle": "Visa en notifiering när nya noder upptäcks", "appSettings_messaging": "Meddelanden", "appSettings_clearPathOnMaxRetry": "Rensa rutt efter maximalt antal försök", - "appSettings_clearPathOnMaxRetrySubtitle": "Återställ kontaktens rutt efter 5 misslyckade sändningsförsök", - "appSettings_pathsWillBeCleared": "Rutter rensas efter 5 misslyckade försök", + "appSettings_clearPathOnMaxRetrySubtitle": "Återställ kontaktens sparade rutt när alla sändningsförsök misslyckas", + "appSettings_pathsWillBeCleared": "Rutter rensas när alla sändningsförsök misslyckas", "appSettings_pathsWillNotBeCleared": "Rutter rensas inte automatiskt", "appSettings_autoRouteRotation": "Automatisk ruttrotation", - "appSettings_autoRouteRotationSubtitle": "Växla mellan de bästa rutterna och flood-läge", + "appSettings_autoRouteRotationSubtitle": "Vid varje direkt försök, prova en annan känd rutt. Senare försök är Flood. Av behåller kontaktens aktuella rutt.", "appSettings_autoRouteRotationEnabled": "Automatisk ruttrotation är aktiverad", "appSettings_autoRouteRotationDisabled": "Automatisk ruttrotation är avstängd", "appSettings_battery": "Batteri", @@ -3234,9 +3234,9 @@ "settings_regionFetchNoneResponded": "Ingen repeater i närheten svarade. Flytta dig närmare en repeater och försök igen.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Routing", - "appSettings_resetRoutingToDefault": "Återställ rutningsalgoritm till standard", - "appSettings_resetRoutingToDefaultSubtitle": "Återställ rutningsalgoritmins inställningar till fabriksstandard", - "appSettings_routingResetToDefault": "Rutningsalgoritmins inställningar återställda till standard", + "appSettings_resetRoutingToDefault": "Återställ rutningsinställningar till standard", + "appSettings_resetRoutingToDefaultSubtitle": "Återställ routningsinställningarna i det här avsnittet till standardvärden", + "appSettings_routingResetToDefault": "Rutningsinställningar återställda till standard", "appSettings_imageMessagesSection": "Bildmeddelanden", "appSettings_showApiKey": "Visa API-nyckel", "appSettings_hideApiKey": "Dölj API-nyckel", @@ -3823,5 +3823,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB eller TCP", "connectSheet_stopReconnecting": "Sluta återansluta", "connectSheet_reconnectFailed": "Kunde inte nå {name}. Kontrollera att den är påslagen och i närheten.", - "chat_composerOffline": "Anslut till en radio för att skicka meddelanden" + "chat_composerOffline": "Anslut till en radio för att skicka meddelanden", + "appSettings_directRetries": "Direkta försök: {count}", + "appSettings_directRetriesSubtitle": "Hur många gånger en känd rutt provas. Finns kvar även när automatisk ruttrotation är av.", + "appSettings_floodRetries": "Flood-försök: {count}", + "appSettings_floodRetriesSubtitle": "Hur många gånger Flood används. Flood tar mer sändningstid. Med rotation på kommer de efter de direkta försöken.", + "appSettings_loginAttempts": "Inloggningsförsök: {count}", + "appSettings_loginAttemptsSubtitle": "Hur många gånger inloggning till en repeater eller room-server provas innan den ger upp." } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 16d0ca20..8b3847e9 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -200,11 +200,11 @@ "appSettings_advertisementNotificationsSubtitle": "Показувати сповіщення при виявленні нових вузлів", "appSettings_messaging": "Обмін повідомленнями", "appSettings_clearPathOnMaxRetry": "Очищати шлях після макс. спроб", - "appSettings_clearPathOnMaxRetrySubtitle": "Скидати шлях до контакту після 5 невдалих спроб надсилання", - "appSettings_pathsWillBeCleared": "Шляхи будуть очищені після 5 невдалих спроб.", + "appSettings_clearPathOnMaxRetrySubtitle": "Скинути збережений шлях контакту, коли всі спроби надсилання не вдаються", + "appSettings_pathsWillBeCleared": "Шляхи буде очищено, коли всі спроби надсилання не вдадуться", "appSettings_pathsWillNotBeCleared": "Шляхи не будуть очищатись автоматично.", "appSettings_autoRouteRotation": "Авторотація маршруту", - "appSettings_autoRouteRotationSubtitle": "Чергувати найкращі шляхи та режим Flood", + "appSettings_autoRouteRotationSubtitle": "На кожній прямій спробі пробувати інший відомий маршрут. Наступні спроби — Flood. Вимкнено залишає поточний шлях контакту.", "appSettings_autoRouteRotationEnabled": "Авторотація маршрутизації увімкнена", "appSettings_autoRouteRotationDisabled": "Авторотація маршрутизації вимкнена", "appSettings_battery": "Батарея", @@ -3333,9 +3333,9 @@ "settings_regionFetchNoneResponded": "Ближні ретранслятори не відповіли. Підійдіть ближче до ретранслятора й спробуйте ще раз.", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "Маршрутизація", - "appSettings_resetRoutingToDefault": "Скинути алгоритм маршрутизації до типового", - "appSettings_resetRoutingToDefaultSubtitle": "Відновити налаштування алгоритму маршрутизації до заводських значень за замовчуванням", - "appSettings_routingResetToDefault": "Налаштування алгоритму маршрутизації скинуто до типових", + "appSettings_resetRoutingToDefault": "Скинути налаштування маршрутизації до типових", + "appSettings_resetRoutingToDefaultSubtitle": "Відновити налаштування маршрутизації в цьому розділі до значень за замовчуванням", + "appSettings_routingResetToDefault": "Налаштування маршрутизації скинуто до типових", "appSettings_imageMessagesSection": "Повідомлення із зображеннями", "appSettings_showApiKey": "Показати API-ключ", "appSettings_hideApiKey": "Приховати API-ключ", @@ -3756,5 +3756,11 @@ "connectSheet_chooseRadioSubtitle": "Bluetooth, USB або TCP", "connectSheet_stopReconnecting": "Зупинити перепідключення", "connectSheet_reconnectFailed": "Не вдалося зв'язатися з {name}. Переконайтеся, що воно увімкнене й поруч.", - "chat_composerOffline": "Підключіться до радіо, щоб надсилати повідомлення" + "chat_composerOffline": "Підключіться до радіо, щоб надсилати повідомлення", + "appSettings_directRetries": "Прямі спроби: {count}", + "appSettings_directRetriesSubtitle": "Скільки разів пробувати відомий маршрут. Доступно і коли авторотацію вимкнено.", + "appSettings_floodRetries": "Спроби Flood: {count}", + "appSettings_floodRetriesSubtitle": "Скільки разів використовувати Flood. Flood займає більше ефірного часу. Якщо ротацію ввімкнено, вони йдуть після прямих спроб.", + "appSettings_loginAttempts": "Спроби входу: {count}", + "appSettings_loginAttemptsSubtitle": "Скільки разів пробувати вхід до ретранслятора або room-сервера, перш ніж здатися." } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6b70ddb0..05e27bb4 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -212,11 +212,11 @@ "appSettings_advertisementNotificationsSubtitle": "发现新节点时显示通知", "appSettings_messaging": "消息", "appSettings_clearPathOnMaxRetry": "达到最大重试次数时清除路径", - "appSettings_clearPathOnMaxRetrySubtitle": "在5次发送失败后重置联系路径。", - "appSettings_pathsWillBeCleared": "5次失败后将重新路由", + "appSettings_clearPathOnMaxRetrySubtitle": "所有发送尝试都失败后,重置联系人已保存的路径", + "appSettings_pathsWillBeCleared": "所有发送尝试失败后将清除路径", "appSettings_pathsWillNotBeCleared": "路径不会自动清除", "appSettings_autoRouteRotation": "自动路径轮换", - "appSettings_autoRouteRotationSubtitle": "在最佳路径和泛洪模式之间切换", + "appSettings_autoRouteRotationSubtitle": "每次直接尝试换一条已知路由。之后的尝试使用 Flood。关闭后保持联系人的当前路径。", "appSettings_autoRouteRotationEnabled": "自动路径轮换已启用", "appSettings_autoRouteRotationDisabled": "自动路径轮换已禁用", "appSettings_battery": "电池", @@ -3244,9 +3244,9 @@ "settings_regionFetchNoneResponded": "附近没有中继器响应。请靠近中继器后重试。", "appSettings_sourceSummary": "{label} - {description}", "appSettings_routingSection": "路由", - "appSettings_resetRoutingToDefault": "将路由算法重置为默认值", - "appSettings_resetRoutingToDefaultSubtitle": "将路由算法设置恢复为出厂默认值", - "appSettings_routingResetToDefault": "路由算法设置已重置为默认值", + "appSettings_resetRoutingToDefault": "将路由设置重置为默认值", + "appSettings_resetRoutingToDefaultSubtitle": "将本部分的路由设置恢复为默认值", + "appSettings_routingResetToDefault": "路由设置已重置为默认值", "appSettings_imageMessagesSection": "图片消息", "appSettings_showApiKey": "显示 API 密钥", "appSettings_hideApiKey": "隐藏 API 密钥", @@ -3833,5 +3833,11 @@ "connectSheet_chooseRadioSubtitle": "蓝牙、USB 或 TCP", "connectSheet_stopReconnecting": "停止重新连接", "connectSheet_reconnectFailed": "无法连接到 {name}。请确保其已开机且在附近。", - "chat_composerOffline": "连接到无线电后才能发送消息" + "chat_composerOffline": "连接到无线电后才能发送消息", + "appSettings_directRetries": "直接尝试:{count}", + "appSettings_directRetriesSubtitle": "尝试已知路由的次数。关闭自动路径轮换后仍然可以设置。", + "appSettings_floodRetries": "Flood 尝试:{count}", + "appSettings_floodRetriesSubtitle": "使用 Flood 的次数。Flood 占用更多空中时间。开启轮换时,这些尝试排在直接尝试之后。", + "appSettings_loginAttempts": "登录尝试:{count}", + "appSettings_loginAttemptsSubtitle": "登录中继或房间服务器时,放弃前的尝试次数。" } diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 9b2b80b6..20c8ab63 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -1,5 +1,6 @@ import 'custom_theme.dart'; import 'image_codec_support.dart'; +import 'send_attempt_plan.dart'; import 'translation_support.dart'; enum UnitSystem { metric, imperial } @@ -103,7 +104,9 @@ class AppSettings { static const double defaultInitialRouteWeight = 3.0; static const double defaultRouteWeightSuccessIncrement = 0.5; static const double defaultRouteWeightFailureDecrement = 0.2; - static const int defaultMaxMessageRetries = 5; + static const int defaultDirectRetries = SendAttemptPlan.defaultDirectRetries; + static const int defaultFloodRetries = SendAttemptPlan.defaultFloodRetries; + static const int defaultLoginAttempts = SendAttemptPlan.defaultLoginAttempts; final bool clearPathOnMaxRetry; final bool mapShowRepeaters; @@ -137,7 +140,11 @@ class AppSettings { final double initialRouteWeight; final double routeWeightSuccessIncrement; final double routeWeightFailureDecrement; - final int maxMessageRetries; + final int directRetries; + final int floodRetries; + + /// How many times a repeater or room-server login is sent before giving up. + final int loginAttempts; final bool channelMinHopsEnabled; final int channelMinHops; final int channelMinHopsRetries; @@ -236,6 +243,16 @@ class AppSettings { downloadedModels: imageCodecDownloadedModels, ); + /// Attempts for one direct message. [rotating] is auto route rotation with + /// no manual path. [floodPath] is the contact's fixed path. + int sendAttemptLimit({required bool rotating, required bool floodPath}) { + return SendAttemptPlan( + directRetries: directRetries, + floodRetries: floodRetries, + rotateRoutes: rotating, + ).attemptLimit(floodPath: floodPath); + } + String get effectiveMapTileApiKey { final apiKey = mapTileApiKey?.trim(); if (apiKey == null || apiKey.isEmpty) { @@ -291,7 +308,9 @@ class AppSettings { this.initialRouteWeight = defaultInitialRouteWeight, this.routeWeightSuccessIncrement = defaultRouteWeightSuccessIncrement, this.routeWeightFailureDecrement = defaultRouteWeightFailureDecrement, - this.maxMessageRetries = defaultMaxMessageRetries, + this.directRetries = defaultDirectRetries, + this.floodRetries = defaultFloodRetries, + this.loginAttempts = defaultLoginAttempts, this.channelMinHopsEnabled = false, this.channelMinHops = 2, this.channelMinHopsRetries = 1, @@ -389,7 +408,9 @@ class AppSettings { 'initial_route_weight': initialRouteWeight, 'route_weight_success_increment': routeWeightSuccessIncrement, 'route_weight_failure_decrement': routeWeightFailureDecrement, - 'max_message_retries': maxMessageRetries, + 'max_direct_retries': directRetries, + 'max_flood_retries': floodRetries, + 'login_attempts': loginAttempts, 'channel_min_hops_enabled': channelMinHopsEnabled, 'channel_min_hops': channelMinHops, 'channel_min_hops_retries': channelMinHopsRetries, @@ -539,8 +560,11 @@ class AppSettings { routeWeightFailureDecrement: (json['route_weight_failure_decrement'] as num?)?.toDouble() ?? defaultRouteWeightFailureDecrement, - maxMessageRetries: - json['max_message_retries'] as int? ?? defaultMaxMessageRetries, + directRetries: SendAttemptPlan.retriesFromJson(json).direct, + floodRetries: SendAttemptPlan.retriesFromJson(json).flood, + loginAttempts: SendAttemptPlan.clampLogin( + (json['login_attempts'] as num?)?.toInt() ?? defaultLoginAttempts, + ), channelMinHopsEnabled: json['channel_min_hops_enabled'] as bool? ?? false, channelMinHops: json['channel_min_hops'] as int? ?? 2, channelMinHopsRetries: json['channel_min_hops_retries'] as int? ?? 1, @@ -698,7 +722,9 @@ class AppSettings { double? initialRouteWeight, double? routeWeightSuccessIncrement, double? routeWeightFailureDecrement, - int? maxMessageRetries, + int? directRetries, + int? floodRetries, + int? loginAttempts, bool? channelMinHopsEnabled, int? channelMinHops, int? channelMinHopsRetries, @@ -791,7 +817,9 @@ class AppSettings { routeWeightSuccessIncrement ?? this.routeWeightSuccessIncrement, routeWeightFailureDecrement: routeWeightFailureDecrement ?? this.routeWeightFailureDecrement, - maxMessageRetries: maxMessageRetries ?? this.maxMessageRetries, + directRetries: directRetries ?? this.directRetries, + floodRetries: floodRetries ?? this.floodRetries, + loginAttempts: loginAttempts ?? this.loginAttempts, channelMinHopsEnabled: channelMinHopsEnabled ?? this.channelMinHopsEnabled, channelMinHops: channelMinHops ?? this.channelMinHops, diff --git a/lib/models/send_attempt_plan.dart b/lib/models/send_attempt_plan.dart new file mode 100644 index 00000000..7fea0b1e --- /dev/null +++ b/lib/models/send_attempt_plan.dart @@ -0,0 +1,88 @@ +/// How many times a direct message is sent, split by route kind. +/// +/// Direct attempts use a known route. Flood attempts ask the mesh to flood. +/// With [rotateRoutes] on (and no manual path), the direct attempts run first +/// and the flood attempts follow. With it off, every attempt stays on the +/// contact's current path and only that path's limit applies. +class SendAttemptPlan { + static const int minDirectRetries = 0; + static const int maxDirectRetries = 15; + static const int defaultDirectRetries = 4; + + static const int minFloodRetries = 0; + static const int maxFloodRetries = 10; + + /// One flood, matching the previous single limit of 5 whose last attempt + /// flooded when auto route rotation was on (4 direct + 1 flood). + static const int defaultFloodRetries = 1; + + static const int minLoginAttempts = 1; + static const int maxLoginAttempts = 10; + static const int defaultLoginAttempts = 5; + + final int directRetries; + final int floodRetries; + + /// When true, direct attempts may change route and are followed by floods. + final bool rotateRoutes; + + const SendAttemptPlan({ + required this.directRetries, + required this.floodRetries, + required this.rotateRoutes, + }); + + static int clampDirect(int value) => + value.clamp(minDirectRetries, maxDirectRetries); + + static int clampFlood(int value) => + value.clamp(minFloodRetries, maxFloodRetries); + + static int clampLogin(int value) => + value.clamp(minLoginAttempts, maxLoginAttempts); + + /// Reads the split limits, or derives them from the old single + /// `max_message_retries` value. That value was a total: every attempt but + /// the last used a route, then one attempt flooded. + static ({int direct, int flood}) retriesFromJson(Map json) { + final direct = json['max_direct_retries']; + final flood = json['max_flood_retries']; + if (direct is num || flood is num) { + return ( + direct: clampDirect( + direct is num ? direct.toInt() : defaultDirectRetries, + ), + flood: clampFlood(flood is num ? flood.toInt() : defaultFloodRetries), + ); + } + final legacy = json['max_message_retries']; + if (legacy is num) { + return ( + direct: clampDirect(legacy.toInt() - 1), + flood: defaultFloodRetries, + ); + } + return (direct: defaultDirectRetries, flood: defaultFloodRetries); + } + + /// How many times to send before giving up. + /// + /// [floodPath] is the contact's fixed path. It is ignored while rotating, + /// because those sends spend [directRetries] then [floodRetries]. A plan + /// with both limits at 0 still sends once, on the current path. + int attemptLimit({required bool floodPath}) { + if (rotateRoutes) { + final total = directRetries + floodRetries; + return total < 1 ? 1 : total; + } + final count = floodPath ? floodRetries : directRetries; + return count < 1 ? 1 : count; + } + + /// First attempt index that should flood, or null when this plan never + /// switches onto a flood (rotation off, or no flood attempts configured). + int? get floodFromAttempt { + if (!rotateRoutes || floodRetries < 1) return null; + return directRetries; + } +} diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 126216cb..fa89851d 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -19,6 +19,8 @@ import '../widgets/language_picker_sheet.dart'; import '../widgets/mesh_nav_tile.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/network_map_settings_section.dart'; +import '../models/send_attempt_plan.dart'; +import '../widgets/settings_reveal.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/translation_settings_section.dart'; import '../helpers/snack_bar_builder.dart'; @@ -414,29 +416,6 @@ class AppSettingsScreen extends StatelessWidget { ) { return Column( children: [ - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: const Icon(Icons.refresh_outlined, size: 24), - title: Text(context.l10n.appSettings_clearPathOnMaxRetry), - subtitle: Text(context.l10n.appSettings_clearPathOnMaxRetrySubtitle), - value: settingsService.settings.clearPathOnMaxRetry, - onChanged: (value) { - settingsService.setClearPathOnMaxRetry(value); - showDismissibleSnackBar( - context, - content: Text( - value - ? context.l10n.appSettings_pathsWillBeCleared - : context.l10n.appSettings_pathsWillNotBeCleared, - ), - duration: const Duration(seconds: 2), - ); - }, - ), - const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -496,104 +475,82 @@ class AppSettingsScreen extends StatelessWidget { BuildContext context, AppSettingsService settingsService, ) { - final autoRouteEnabled = settingsService.settings.autoRouteRotationEnabled; + final settings = settingsService.settings; + final l10n = context.l10n; return Column( children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.refresh_outlined, size: 24), + title: Text(l10n.appSettings_clearPathOnMaxRetry), + subtitle: Text(l10n.appSettings_clearPathOnMaxRetrySubtitle), + value: settings.clearPathOnMaxRetry, + onChanged: (value) { + settingsService.setClearPathOnMaxRetry(value); + showDismissibleSnackBar( + context, + content: Text( + value + ? l10n.appSettings_pathsWillBeCleared + : l10n.appSettings_pathsWillNotBeCleared, + ), + duration: const Duration(seconds: 2), + ); + }, + ), + const Divider(height: 1, indent: 16), + SettingsValueSlider( + title: l10n.appSettings_directRetries(settings.directRetries), + subtitle: l10n.appSettings_directRetriesSubtitle, + value: settings.directRetries, + min: SendAttemptPlan.minDirectRetries, + max: SendAttemptPlan.maxDirectRetries, + onChanged: settingsService.setDirectRetries, + ), + const Divider(height: 1, indent: 16), + SettingsValueSlider( + title: l10n.appSettings_floodRetries(settings.floodRetries), + subtitle: l10n.appSettings_floodRetriesSubtitle, + value: settings.floodRetries, + min: SendAttemptPlan.minFloodRetries, + max: SendAttemptPlan.maxFloodRetries, + onChanged: settingsService.setFloodRetries, + ), + const Divider(height: 1, indent: 16), + SettingsValueSlider( + title: l10n.appSettings_loginAttempts(settings.loginAttempts), + subtitle: l10n.appSettings_loginAttemptsSubtitle, + value: settings.loginAttempts, + min: SendAttemptPlan.minLoginAttempts, + max: SendAttemptPlan.maxLoginAttempts, + onChanged: settingsService.setLoginAttempts, + ), + const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, vertical: 4, ), secondary: const Icon(Icons.alt_route, size: 24), - title: Text(context.l10n.appSettings_autoRouteRotation), - subtitle: Text(context.l10n.appSettings_autoRouteRotationSubtitle), - value: autoRouteEnabled, + title: Text(l10n.appSettings_autoRouteRotation), + subtitle: Text(l10n.appSettings_autoRouteRotationSubtitle), + value: settings.autoRouteRotationEnabled, onChanged: (value) { settingsService.setAutoRouteRotationEnabled(value); showDismissibleSnackBar( context, content: Text( value - ? context.l10n.appSettings_autoRouteRotationEnabled - : context.l10n.appSettings_autoRouteRotationDisabled, + ? l10n.appSettings_autoRouteRotationEnabled + : l10n.appSettings_autoRouteRotationDisabled, ), duration: const Duration(seconds: 2), ); }, ), - // AnimatedSize sub-options for auto-route rotation - AnimatedSize( - duration: const Duration(milliseconds: 200), - alignment: Alignment.topCenter, - child: autoRouteEnabled - ? Container( - color: Theme.of(context).colorScheme.surfaceContainerHighest, - padding: const EdgeInsets.only(left: 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Divider(height: 1), - ListTile( - title: Text(context.l10n.appSettings_maxMessageRetries), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context - .l10n - .appSettings_maxMessageRetriesSubtitle, - ), - Slider( - value: settingsService.settings.maxMessageRetries - .toDouble(), - min: 2, - max: 10, - divisions: 8, - label: settingsService.settings.maxMessageRetries - .toString(), - onChanged: (value) => settingsService - .setMaxMessageRetries(value.toInt()), - ), - ], - ), - ), - const Divider(height: 1), - ListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - leading: const Icon(Icons.restart_alt, size: 24), - title: Text( - context.l10n.appSettings_resetRoutingToDefault, - ), - subtitle: Text( - context - .l10n - .appSettings_resetRoutingToDefaultSubtitle, - ), - trailing: const Icon( - Icons.keyboard_arrow_right, - size: 18, - ), - onTap: () async { - await settingsService.resetRoutingSettingsToDefault(); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.appSettings_routingResetToDefault, - ), - duration: const Duration(seconds: 2), - ); - } - }, - ), - ], - ), - ) - : const SizedBox.shrink(), - ), const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( @@ -601,60 +558,70 @@ class AppSettingsScreen extends StatelessWidget { vertical: 4, ), secondary: const Icon(Icons.cell_tower, size: 24), - title: Text(context.l10n.appSettings_channelMinHops), - subtitle: Text(context.l10n.appSettings_channelMinHopsSubtitle), - value: settingsService.settings.channelMinHopsEnabled, + title: Text(l10n.appSettings_channelMinHops), + subtitle: Text(l10n.appSettings_channelMinHopsSubtitle), + value: settings.channelMinHopsEnabled, onChanged: settingsService.setChannelMinHopsEnabled, ), - if (settingsService.settings.channelMinHopsEnabled) ...[ - ListTile( - title: Text( - context.l10n.appSettings_channelMinHopsCount( - settingsService.settings.channelMinHops, + SettingsReveal( + visible: settings.channelMinHopsEnabled, + children: [ + SettingsValueSlider( + title: l10n.appSettings_channelMinHopsCount( + settings.channelMinHops, ), - ), - subtitle: Slider( - value: settingsService.settings.channelMinHops.toDouble(), + value: settings.channelMinHops, min: 1, max: 8, - divisions: 7, - label: settingsService.settings.channelMinHops.toString(), - onChanged: (value) => - settingsService.setChannelMinHops(value.toInt()), + onChanged: settingsService.setChannelMinHops, ), - ), - ListTile( - title: Text( - context.l10n.appSettings_channelMinHopsRetries( - settingsService.settings.channelMinHopsRetries, + SettingsValueSlider( + title: l10n.appSettings_channelMinHopsRetries( + settings.channelMinHopsRetries, ), - ), - subtitle: Slider( - value: settingsService.settings.channelMinHopsRetries.toDouble(), + value: settings.channelMinHopsRetries, min: 1, max: 5, - divisions: 4, - label: settingsService.settings.channelMinHopsRetries.toString(), - onChanged: (value) => - settingsService.setChannelMinHopsRetries(value.toInt()), + onChanged: settingsService.setChannelMinHopsRetries, ), - ), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: const Icon(Icons.hub_outlined, size: 24), - title: Text(context.l10n.appSettings_channelMinHopsCountRepeaters), - subtitle: Text( - context.l10n.appSettings_channelMinHopsCountRepeatersSubtitle( - settingsService.settings.channelMinHops, + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, ), + secondary: const Icon(Icons.hub_outlined, size: 24), + title: Text(l10n.appSettings_channelMinHopsCountRepeaters), + subtitle: Text( + l10n.appSettings_channelMinHopsCountRepeatersSubtitle( + settings.channelMinHops, + ), + ), + value: settings.channelMinHopsCountRepeaters, + onChanged: settingsService.setChannelMinHopsCountRepeaters, ), - value: settingsService.settings.channelMinHopsCountRepeaters, - onChanged: settingsService.setChannelMinHopsCountRepeaters, + ], + ), + const Divider(height: 1, indent: 16), + ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, ), - ], + leading: const Icon(Icons.restart_alt, size: 24), + title: Text(l10n.appSettings_resetRoutingToDefault), + subtitle: Text(l10n.appSettings_resetRoutingToDefaultSubtitle), + trailing: const Icon(Icons.keyboard_arrow_right, size: 18), + onTap: () async { + await settingsService.resetRoutingSettingsToDefault(); + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text(l10n.appSettings_routingResetToDefault), + duration: const Duration(seconds: 2), + ); + } + }, + ), ], ); } @@ -726,21 +693,24 @@ class AppSettingsScreen extends StatelessWidget { }, ), ), - if (settingsService.settings.imageMessagesEnabled) ...[ - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, + SettingsReveal( + visible: settingsService.settings.imageMessagesEnabled, + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.auto_awesome_outlined, size: 24), + title: Text(context.l10n.imageMessages_autoProcessTitle), + subtitle: Text(context.l10n.imageMessages_autoProcessSubtitle), + value: settingsService.settings.imageProcessAutomatically, + onChanged: (value) => + settingsService.setImageProcessAutomatically(value), ), - secondary: const Icon(Icons.auto_awesome_outlined, size: 24), - title: Text(context.l10n.imageMessages_autoProcessTitle), - subtitle: Text(context.l10n.imageMessages_autoProcessSubtitle), - value: settingsService.settings.imageProcessAutomatically, - onChanged: (value) => - settingsService.setImageProcessAutomatically(value), - ), - _buildImageCodecModels(context), - ], + _buildImageCodecModels(context), + ], + ), ], ); } diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 6f247343..e3e64935 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -25,6 +25,7 @@ import '../widgets/connect_sheet.dart'; import '../widgets/list_filter_widget.dart'; import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/settings_reveal.dart'; import '../widgets/network_map_opt_in_dialog.dart'; import '../widgets/qr_code_display.dart'; import '../widgets/quick_switch_bar.dart'; @@ -2045,8 +2046,9 @@ void showEditChannelSheet( } }), ), - if (cyr2latEnabled) ...[ - Padding( + RevealOnEnable( + visible: cyr2latEnabled, + child: Padding( padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), child: DropdownButtonFormField( isExpanded: true, @@ -2073,7 +2075,7 @@ void showEditChannelSheet( }), ), ), - ], + ), SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(sheetContext.l10n.urlImage_enable), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index ad509b82..572835db 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -19,6 +19,7 @@ import '../helpers/message_url_image_helper.dart'; import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; import '../widgets/message_status_icon.dart'; +import '../widgets/settings_reveal.dart'; import '../widgets/empty_state.dart'; import '../helpers/chat_scroll_controller.dart'; import '../helpers/gif_helper.dart'; @@ -707,6 +708,13 @@ class _ChatScreenState extends State { } final messageIndex = index; Contact contact = _resolveContact(connector); + final sendSettings = context.read().settings; + final retryLimit = sendSettings.sendAttemptLimit( + rotating: + sendSettings.autoRouteRotationEnabled && + contact.pathOverride == null, + floodPath: (contact.pathOverride ?? contact.pathLength) < 0, + ); final bool isRoom = contact.type == advTypeRoom; final message = reversedMessages[messageIndex]; String fourByteHex = ''; @@ -736,6 +744,7 @@ class _ChatScreenState extends State { ); final bubble = _MessageBubble( message: message, + maxSendAttempts: retryLimit, senderName: isRoom ? (roomAuthor != null ? "${roomAuthor.name} [$fourByteHex]" @@ -1209,8 +1218,9 @@ class _ChatScreenState extends State { }); }, ), - if (cyr2latEnabled) ...[ - Padding( + RevealOnEnable( + visible: cyr2latEnabled, + child: Padding( padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), child: DropdownButtonFormField( isExpanded: true, @@ -1242,7 +1252,7 @@ class _ChatScreenState extends State { }, ), ), - ], + ), const Divider(height: 8), SwitchListTile( contentPadding: EdgeInsets.zero, @@ -1623,6 +1633,7 @@ class _ChatScreenState extends State { class _MessageBubble extends StatelessWidget { final Message message; + final int maxSendAttempts; final String senderName; final VoidCallback? onLongPress; final void Function(Message message, String emoji)? onRetryReaction; @@ -1632,6 +1643,7 @@ class _MessageBubble extends StatelessWidget { const _MessageBubble({ required this.message, + required this.maxSendAttempts, required this.senderName, required this.sourceId, required this.textScale, @@ -1871,10 +1883,7 @@ class _MessageBubble extends StatelessWidget { child: Text( context.l10n.chat_retryCount( message.retryCount, - context - .read() - .settings - .maxMessageRetries, + maxSendAttempts, ), style: MeshTheme.mono( fontSize: 12 * textScale, diff --git a/lib/screens/filtered_messages_screen.dart b/lib/screens/filtered_messages_screen.dart index c981f692..c1eac3d2 100644 --- a/lib/screens/filtered_messages_screen.dart +++ b/lib/screens/filtered_messages_screen.dart @@ -12,6 +12,7 @@ import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/chat_send_pipeline.dart'; import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/settings_reveal.dart'; /// Recent filtered channel messages across all channels, newest first. /// @@ -286,7 +287,8 @@ class _FilteredMessageCard extends StatelessWidget { ), const SizedBox(height: 8), AnimatedSize( - duration: const Duration(milliseconds: 150), + duration: RevealOnEnable.duration, + curve: RevealOnEnable.curve, alignment: AlignmentDirectional.topStart, child: Padding( padding: const EdgeInsetsDirectional.only(end: 8), diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart index 3d416501..c668dd12 100644 --- a/lib/screens/scanner_screen.dart +++ b/lib/screens/scanner_screen.dart @@ -15,6 +15,7 @@ import '../widgets/device_tile.dart'; import '../widgets/empty_state.dart'; import '../widgets/get_node_banner.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/settings_reveal.dart'; import '../helpers/snack_bar_builder.dart'; import '../review_mode/review_mode_entry.dart'; import '../utils/main_navigation.dart'; @@ -151,17 +152,13 @@ class _ScannerScreenState extends State { builder: (context, connector, child) { return Column( children: [ - // Bluetooth off warning — slides in/out with AnimatedSize - AnimatedSize( - duration: const Duration(milliseconds: 250), - curve: Curves.easeInOut, - child: _bluetoothState == BluetoothAdapterState.off - ? _BluetoothOffBanner( - onEnable: PlatformInfo.isAndroid - ? () => FlutterBluePlus.turnOn() - : null, - ) - : const SizedBox.shrink(), + RevealOnEnable( + visible: _bluetoothState == BluetoothAdapterState.off, + child: _BluetoothOffBanner( + onEnable: PlatformInfo.isAndroid + ? () => FlutterBluePlus.turnOn() + : null, + ), ), // Connection status header diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 9a6bc11e..1be0b39f 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -14,6 +14,7 @@ import '../helpers/snack_bar_builder.dart'; import '../helpers/utf8_length_limiter.dart'; import '../widgets/mesh_nav_tile.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/settings_reveal.dart'; import '../widgets/radio_settings_dialog.dart'; import 'app_settings_screen.dart'; import 'app_debug_log_screen.dart'; @@ -301,62 +302,58 @@ class _SettingsScreenState extends State { ), ), - // Expandable detail rows - AnimatedSize( - duration: const Duration(milliseconds: 200), - alignment: Alignment.topCenter, - child: _deviceInfoExpanded - ? Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 14), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Divider(height: 1), - const SizedBox(height: 10), - _infoRow( - context, - label: l10n.settings_infoId, - value: connector.deviceIdLabel, - ), - _buildBatteryInfoRow(context, connector), - if (connector.manufacturerName != null) - _infoRow( - context, - label: l10n.settings_infoHardware, - value: connector.manufacturerName!, - ), - if (connector.firmwareVersionString != null) - _infoRow( - context, - label: l10n.settings_infoFirmware, - value: connector.firmwareVersionString!, - ), - if (connector.selfName != null) - _infoRow( - context, - label: l10n.settings_nodeName, - value: connector.selfName!, - ), - if (connector.selfPublicKey != null) - _publicKeyRow( - context, - label: l10n.settings_infoPublicKey, - publicKeyHex: pubKeyToHex(connector.selfPublicKey!), - ), - _infoRow( - context, - label: l10n.settings_infoContactsCount, - value: '${connector.contacts.length}', - ), - _infoRow( - context, - label: l10n.settings_infoChannelCount, - value: '${connector.channels.length}', - ), - ], + RevealOnEnable( + visible: _deviceInfoExpanded, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Divider(height: 1), + const SizedBox(height: 10), + _infoRow( + context, + label: l10n.settings_infoId, + value: connector.deviceIdLabel, + ), + _buildBatteryInfoRow(context, connector), + if (connector.manufacturerName != null) + _infoRow( + context, + label: l10n.settings_infoHardware, + value: connector.manufacturerName!, ), - ) - : const SizedBox.shrink(), + if (connector.firmwareVersionString != null) + _infoRow( + context, + label: l10n.settings_infoFirmware, + value: connector.firmwareVersionString!, + ), + if (connector.selfName != null) + _infoRow( + context, + label: l10n.settings_nodeName, + value: connector.selfName!, + ), + if (connector.selfPublicKey != null) + _publicKeyRow( + context, + label: l10n.settings_infoPublicKey, + publicKeyHex: pubKeyToHex(connector.selfPublicKey!), + ), + _infoRow( + context, + label: l10n.settings_infoContactsCount, + value: '${connector.contacts.length}', + ), + _infoRow( + context, + label: l10n.settings_infoChannelCount, + value: '${connector.channels.length}', + ), + ], + ), + ), ), ], ); diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index d0758681..ae761062 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; import '../models/app_settings.dart'; import '../models/custom_theme.dart'; +import '../models/send_attempt_plan.dart'; import '../models/holiday_schedule.dart'; import '../models/image_codec_support.dart'; import '../models/translation_support.dart'; @@ -228,8 +229,22 @@ class AppSettingsService extends ChangeNotifier { ); } - Future setMaxMessageRetries(int value) async { - await updateSettings(_settings.copyWith(maxMessageRetries: value)); + Future setDirectRetries(int value) async { + await updateSettings( + _settings.copyWith(directRetries: SendAttemptPlan.clampDirect(value)), + ); + } + + Future setFloodRetries(int value) async { + await updateSettings( + _settings.copyWith(floodRetries: SendAttemptPlan.clampFlood(value)), + ); + } + + Future setLoginAttempts(int value) async { + await updateSettings( + _settings.copyWith(loginAttempts: SendAttemptPlan.clampLogin(value)), + ); } Future setChannelMinHopsEnabled(bool value) async { @@ -714,13 +729,21 @@ class AppSettingsService extends ChangeNotifier { Future resetRoutingSettingsToDefault() async { await updateSettings( _settings.copyWith( + clearPathOnMaxRetry: false, + autoRouteRotationEnabled: true, maxRouteWeight: AppSettings.defaultMaxRouteWeight, initialRouteWeight: AppSettings.defaultInitialRouteWeight, routeWeightSuccessIncrement: AppSettings.defaultRouteWeightSuccessIncrement, routeWeightFailureDecrement: AppSettings.defaultRouteWeightFailureDecrement, - maxMessageRetries: AppSettings.defaultMaxMessageRetries, + directRetries: AppSettings.defaultDirectRetries, + floodRetries: AppSettings.defaultFloodRetries, + loginAttempts: AppSettings.defaultLoginAttempts, + channelMinHopsEnabled: false, + channelMinHops: 2, + channelMinHopsRetries: 1, + channelMinHopsCountRepeaters: false, ), ); } diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 4495ce91..835facdb 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -7,6 +7,7 @@ import '../connector/meshcore_protocol.dart'; import '../models/contact.dart'; import '../models/message.dart'; import '../models/path_selection.dart'; +import '../models/send_attempt_plan.dart'; import 'app_settings_service.dart'; import 'app_debug_log_service.dart'; @@ -58,7 +59,7 @@ class RetryServiceConfig { final PathSelection? Function( String contactKey, int attemptIndex, - int maxRetries, + int directRetries, List recentSelections, )? selectRetryPath; @@ -88,8 +89,21 @@ class MessageRetryService extends ChangeNotifier { /// shared globally; cap at 6 to leave two slots of headroom. static const int _maxGlobalInFlight = 6; - int _maxRetries = 5; - int get maxRetries => _maxRetries; + int? _directOverride; + int? _floodOverride; + bool? _rotateOverride; + + /// Pins both limits and turns rotation off. Tests use this to send a fixed + /// number of attempts on the contact's current path. + void setMaxRetries(int value) { + final attempts = value < 1 ? 1 : value; + _directOverride = attempts; + _floodOverride = attempts.clamp( + SendAttemptPlan.minFloodRetries, + SendAttemptPlan.maxFloodRetries, + ); + _rotateOverride = false; + } final Map _timeoutTimers = {}; final Map _pendingMessages = {}; @@ -110,6 +124,7 @@ class MessageRetryService extends ChangeNotifier { final Set _activeMessages = {}; final Set _resolvedMessages = {}; final Map _expectedHashToMessageId = {}; + final Map _attemptLimits = {}; RetryServiceConfig? _config; @@ -123,8 +138,26 @@ class MessageRetryService extends ChangeNotifier { _config = config; } - void setMaxRetries(int value) { - _maxRetries = value.clamp(2, 10); + SendAttemptPlan _planFor(Contact contact) { + final settings = _config?.appSettingsService?.settings; + final direct = + _directOverride ?? + settings?.directRetries ?? + SendAttemptPlan.defaultDirectRetries; + final flood = + _floodOverride ?? + settings?.floodRetries ?? + SendAttemptPlan.defaultFloodRetries; + final rotateFlag = + _rotateOverride ?? settings?.autoRouteRotationEnabled ?? true; + return SendAttemptPlan( + directRetries: direct, + floodRetries: flood, + rotateRoutes: + rotateFlag && + contact.pathOverride == null && + _config?.selectRetryPath != null, + ); } /// Compute expected ACK hash using same algorithm as firmware: @@ -176,6 +209,9 @@ class MessageRetryService extends ChangeNotifier { pathBytes ?? Uint8List.fromList(resolved.pathBytes); final messagePathLength = pathLength ?? (resolved.useFlood ? -1 : resolved.hopCount); + _attemptLimits[messageId] = _planFor( + contact, + ).attemptLimit(floodPath: messagePathLength < 0); final message = Message( senderKey: contact.publicKey, text: text, @@ -289,11 +325,8 @@ class MessageRetryService extends ChangeNotifier { PathSelection? _selectPathForAttempt(Message message, Contact contact) { final config = _config; if (config == null) return null; - final autoRotationEnabled = - config.appSettingsService?.settings.autoRouteRotationEnabled == true; - if (!autoRotationEnabled || - contact.pathOverride != null || - config.selectRetryPath == null) { + final plan = _planFor(contact); + if (!plan.rotateRoutes || config.selectRetryPath == null) { return null; } @@ -303,7 +336,7 @@ class MessageRetryService extends ChangeNotifier { return config.selectRetryPath!( contact.publicKeyHex, message.retryCount, - maxRetries, + plan.floodFromAttempt ?? (1 << 30), recentSelections, ); } @@ -626,6 +659,7 @@ class MessageRetryService extends ChangeNotifier { _pendingMessages.remove(messageId); _pendingContacts.remove(messageId); _attemptPathHistory.remove(messageId); + _attemptLimits.remove(messageId); _deferredRouteFailures.remove(messageId); _timeoutTimers.remove(messageId); _resolvedMessages.remove(messageId); @@ -657,9 +691,16 @@ class MessageRetryService extends ChangeNotifier { tag: 'AckHash', ); - if (message.retryCount < maxRetries - 1 && + final limit = + _attemptLimits[messageId] ?? + _planFor( + contact, + ).attemptLimit(floodPath: resolvePathSelection(contact).useFlood); + if (message.retryCount < limit - 1 && _textFitsAttempt(message, contact, message.retryCount + 1)) { - final backoffMs = 1000 * (1 << message.retryCount); + // Cap the shift so a high retry limit does not wait for minutes. + final shift = message.retryCount.clamp(0, 5); + final backoffMs = 1000 * (1 << shift); if (selection != null) { _deferredRouteFailures.putIfAbsent(messageId, () => []).add(( diff --git a/lib/services/path_history_service.dart b/lib/services/path_history_service.dart index 43cec96b..2c5562b1 100644 --- a/lib/services/path_history_service.dart +++ b/lib/services/path_history_service.dart @@ -259,18 +259,19 @@ class PathHistoryService extends ChangeNotifier { /// Route for one send attempt of a message to [contactPubKeyHex]. /// - /// The last attempt always floods. Otherwise a known route is drawn by - /// Thompson sampling over faded delivery stats, weighted by how well it - /// fits [context]; routes used for this message's recent attempts score - /// lower so retries usually try something different. + /// Attempts before [directRetries] draw a known route by Thompson sampling + /// over faded delivery stats, weighted by how well it fits [context]; + /// routes used for this message's recent attempts score lower so retries + /// usually try something different. From [directRetries] on, the attempt + /// floods. [directRetries] of 0 floods immediately. PathSelection selectPathForAttempt( String contactPubKeyHex, { required int attemptIndex, - required int maxRetries, + required int directRetries, List recentSelections = const [], RouteContext context = RouteContext.unknown, }) { - if (maxRetries <= 0 || attemptIndex >= maxRetries - 1) { + if (directRetries <= 0 || attemptIndex >= directRetries) { return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true); } diff --git a/lib/widgets/repeater_login_dialog.dart b/lib/widgets/repeater_login_dialog.dart index 041a8b25..9402a719 100644 --- a/lib/widgets/repeater_login_dialog.dart +++ b/lib/widgets/repeater_login_dialog.dart @@ -6,6 +6,7 @@ import 'package:provider/provider.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../l10n/contact_localization.dart'; +import '../services/app_settings_service.dart'; import '../services/storage_service.dart'; import '../services/repeater_command_service.dart'; import '../connector/meshcore_connector.dart'; @@ -40,7 +41,9 @@ class _RepeaterLoginDialogState extends State { String? _loginError; late MeshCoreConnector _connector; int _currentAttempt = 0; - static const int _maxAttempts = 5; + + int get _maxAttempts => + context.read().settings.loginAttempts; @override void initState() { diff --git a/lib/widgets/room_login_dialog.dart b/lib/widgets/room_login_dialog.dart index 42b46f6c..5ea47a06 100644 --- a/lib/widgets/room_login_dialog.dart +++ b/lib/widgets/room_login_dialog.dart @@ -7,6 +7,7 @@ import 'package:provider/provider.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../l10n/contact_localization.dart'; +import '../services/app_settings_service.dart'; import '../services/storage_service.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; @@ -36,7 +37,9 @@ class _RoomLoginDialogState extends State { bool _obscurePassword = true; late MeshCoreConnector _connector; int _currentAttempt = 0; - static const int _maxAttempts = 5; + + int get _maxAttempts => + context.read().settings.loginAttempts; @override void initState() { diff --git a/lib/widgets/settings_reveal.dart b/lib/widgets/settings_reveal.dart new file mode 100644 index 00000000..7e84951c --- /dev/null +++ b/lib/widgets/settings_reveal.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; + +/// Shows or hides [child] by animating its height. +/// +/// Use this wherever turning something on reveals more controls, and for any +/// other block that grows or collapses in place. Hidden controls are not in +/// the tree, so they are not announced. The duration and curve are fixed so +/// every reveal moves the same way. See documentation/design.md. +class RevealOnEnable extends StatelessWidget { + static const Duration duration = Duration(milliseconds: 200); + static const Curve curve = Curves.easeInOut; + + final bool visible; + final Widget child; + final AlignmentGeometry alignment; + + const RevealOnEnable({ + super.key, + required this.visible, + required this.child, + this.alignment = Alignment.topCenter, + }); + + @override + Widget build(BuildContext context) { + return AnimatedSize( + duration: duration, + curve: curve, + alignment: alignment, + child: visible + ? child + : const SizedBox(width: double.infinity, height: 0), + ); + } +} + +/// Nested controls under a settings switch: the shared reveal animation on a +/// tinted, indented panel. +class SettingsReveal extends StatelessWidget { + final bool visible; + final List children; + + const SettingsReveal({ + super.key, + required this.visible, + required this.children, + }); + + @override + Widget build(BuildContext context) { + return RevealOnEnable( + visible: visible, + child: Material( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Padding( + padding: const EdgeInsets.only(left: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), + ), + ), + ); + } +} + +/// A settings slider whose selected value stays visible in the title. +/// +/// The drag bubble repeats the same number. Pass a [title] that already +/// includes [value], the way the channel-hop titles do. +class SettingsValueSlider extends StatelessWidget { + final String title; + final String? subtitle; + final int value; + final int min; + final int max; + final ValueChanged onChanged; + + const SettingsValueSlider({ + super.key, + required this.title, + this.subtitle, + required this.value, + required this.min, + required this.max, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + final clamped = value.clamp(min, max); + return ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + title: Text(title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (subtitle != null) Text(subtitle!), + Slider( + value: clamped.toDouble(), + min: min.toDouble(), + max: max.toDouble(), + divisions: max > min ? max - min : null, + label: '$clamped', + onChanged: (next) => onChanged(next.round()), + ), + ], + ), + ); + } +} diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 1815e9d9..db09207a 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -404,7 +404,9 @@ void main() { expect(settings.initialRouteWeight, equals(3.0)); expect(settings.routeWeightSuccessIncrement, equals(0.5)); expect(settings.routeWeightFailureDecrement, equals(0.2)); - expect(settings.maxMessageRetries, equals(5)); + expect(settings.directRetries, equals(4)); + expect(settings.floodRetries, equals(1)); + expect(settings.loginAttempts, equals(5)); expect(settings.evictDiscoveredContactsEnabled, isTrue); }); @@ -415,13 +417,17 @@ void main() { expect(json.containsKey('initial_route_weight'), isTrue); expect(json.containsKey('route_weight_success_increment'), isTrue); expect(json.containsKey('route_weight_failure_decrement'), isTrue); - expect(json.containsKey('max_message_retries'), isTrue); + expect(json.containsKey('max_direct_retries'), isTrue); + expect(json.containsKey('max_flood_retries'), isTrue); + expect(json.containsKey('login_attempts'), isTrue); expect(json.containsKey('evict_discovered_contacts_enabled'), isTrue); expect(json['max_route_weight'], equals(5.0)); expect(json['initial_route_weight'], equals(3.0)); expect(json['route_weight_success_increment'], equals(0.5)); expect(json['route_weight_failure_decrement'], equals(0.2)); - expect(json['max_message_retries'], equals(5)); + expect(json['max_direct_retries'], equals(4)); + expect(json['max_flood_retries'], equals(1)); + expect(json['login_attempts'], equals(5)); expect(json['evict_discovered_contacts_enabled'], isTrue); }); @@ -431,7 +437,9 @@ void main() { 'initial_route_weight': 2.0, 'route_weight_success_increment': 1.0, 'route_weight_failure_decrement': 1.5, - 'max_message_retries': 8, + 'max_direct_retries': 8, + 'max_flood_retries': 3, + 'login_attempts': 7, 'evict_discovered_contacts_enabled': false, }; final settings = AppSettings.fromJson(json); @@ -439,7 +447,9 @@ void main() { expect(settings.initialRouteWeight, equals(2.0)); expect(settings.routeWeightSuccessIncrement, equals(1.0)); expect(settings.routeWeightFailureDecrement, equals(1.5)); - expect(settings.maxMessageRetries, equals(8)); + expect(settings.directRetries, equals(8)); + expect(settings.floodRetries, equals(3)); + expect(settings.loginAttempts, equals(7)); expect(settings.evictDiscoveredContactsEnabled, isFalse); }); @@ -503,7 +513,9 @@ void main() { expect(settings.initialRouteWeight, equals(3.0)); expect(settings.routeWeightSuccessIncrement, equals(0.5)); expect(settings.routeWeightFailureDecrement, equals(0.2)); - expect(settings.maxMessageRetries, equals(5)); + expect(settings.directRetries, equals(4)); + expect(settings.floodRetries, equals(1)); + expect(settings.loginAttempts, equals(5)); }, ); @@ -513,7 +525,7 @@ void main() { expect(updated.maxRouteWeight, equals(8.0)); // Other fields should be unchanged expect(updated.initialRouteWeight, equals(settings.initialRouteWeight)); - expect(updated.maxMessageRetries, equals(settings.maxMessageRetries)); + expect(updated.directRetries, equals(settings.directRetries)); }); test('copyWith works for initialRouteWeight', () { @@ -543,10 +555,10 @@ void main() { ); }); - test('copyWith works for maxMessageRetries', () { + test('copyWith works for directRetries', () { final settings = AppSettings(); - final updated = settings.copyWith(maxMessageRetries: 10); - expect(updated.maxMessageRetries, equals(10)); + final updated = settings.copyWith(directRetries: 10); + expect(updated.directRetries, equals(10)); expect(updated.maxRouteWeight, equals(settings.maxRouteWeight)); }); }); diff --git a/test/models/send_attempt_plan_test.dart b/test/models/send_attempt_plan_test.dart new file mode 100644 index 00000000..13ad8ec0 --- /dev/null +++ b/test/models/send_attempt_plan_test.dart @@ -0,0 +1,151 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/models/send_attempt_plan.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; + +void main() { + group('SendAttemptPlan', () { + const rotating = SendAttemptPlan( + directRetries: 4, + floodRetries: 1, + rotateRoutes: true, + ); + const fixed = SendAttemptPlan( + directRetries: 4, + floodRetries: 2, + rotateRoutes: false, + ); + + test('rotation spends direct attempts then flood attempts', () { + expect(rotating.attemptLimit(floodPath: false), 5); + expect(rotating.attemptLimit(floodPath: true), 5); + expect(rotating.floodFromAttempt, 4); + }); + + test('a fixed path uses only that path kind', () { + expect(fixed.attemptLimit(floodPath: false), 4); + expect(fixed.attemptLimit(floodPath: true), 2); + expect(fixed.floodFromAttempt, isNull); + }); + + test('both limits at zero still send once and do not switch to flood', () { + const plan = SendAttemptPlan( + directRetries: 0, + floodRetries: 0, + rotateRoutes: true, + ); + expect(plan.attemptLimit(floodPath: false), 1); + expect(plan.floodFromAttempt, isNull); + }); + + test('direct zero with rotation floods from the first attempt', () { + const plan = SendAttemptPlan( + directRetries: 0, + floodRetries: 3, + rotateRoutes: true, + ); + expect(plan.attemptLimit(floodPath: false), 3); + expect(plan.floodFromAttempt, 0); + }); + + test('flood zero with rotation never switches to flood', () { + const plan = SendAttemptPlan( + directRetries: 6, + floodRetries: 0, + rotateRoutes: true, + ); + expect(plan.attemptLimit(floodPath: true), 6); + expect(plan.floodFromAttempt, isNull); + }); + }); + + group('AppSettings retry migration', () { + test('a saved single retry limit becomes direct plus one flood', () { + final settings = AppSettings.fromJson({'max_message_retries': 5}); + expect(settings.directRetries, 4); + expect(settings.floodRetries, 1); + expect(settings.toJson().containsKey('max_message_retries'), isFalse); + }); + + test('the old maximum of 10 keeps nine direct attempts and one flood', () { + final settings = AppSettings.fromJson({'max_message_retries': 10}); + expect(settings.directRetries, 9); + expect(settings.floodRetries, 1); + }); + + test('new keys win over a leftover single limit and are clamped', () { + final settings = AppSettings.fromJson({ + 'max_message_retries': 5, + 'max_direct_retries': 40, + 'max_flood_retries': -2, + 'login_attempts': 0, + }); + expect(settings.directRetries, SendAttemptPlan.maxDirectRetries); + expect(settings.floodRetries, SendAttemptPlan.minFloodRetries); + expect(settings.loginAttempts, SendAttemptPlan.minLoginAttempts); + }); + + test('round trip keeps the split limits', () { + final saved = AppSettings( + directRetries: 12, + floodRetries: 7, + loginAttempts: 3, + clearPathOnMaxRetry: true, + autoRouteRotationEnabled: false, + channelMinHopsEnabled: true, + ).toJson(); + final restored = AppSettings.fromJson(saved); + expect(restored.directRetries, 12); + expect(restored.floodRetries, 7); + expect(restored.loginAttempts, 3); + expect(restored.clearPathOnMaxRetry, isTrue); + expect(restored.autoRouteRotationEnabled, isFalse); + expect(restored.channelMinHopsEnabled, isTrue); + }); + }); + + test('reset routing settings restores the moved controls', () async { + SharedPreferences.setMockInitialValues({}); + await PrefsManager.initialize(); + final service = AppSettingsService(); + await service.loadSettings(); + await service.updateSettings( + service.settings.copyWith( + clearPathOnMaxRetry: true, + autoRouteRotationEnabled: false, + directRetries: 15, + floodRetries: 10, + loginAttempts: 9, + channelMinHopsEnabled: true, + channelMinHops: 6, + channelMinHopsRetries: 4, + channelMinHopsCountRepeaters: true, + maxRouteWeight: 9, + ), + ); + + await service.resetRoutingSettingsToDefault(); + final settings = service.settings; + expect(settings.clearPathOnMaxRetry, isFalse); + expect(settings.autoRouteRotationEnabled, isTrue); + expect(settings.directRetries, SendAttemptPlan.defaultDirectRetries); + expect(settings.floodRetries, SendAttemptPlan.defaultFloodRetries); + expect(settings.loginAttempts, SendAttemptPlan.defaultLoginAttempts); + expect(settings.channelMinHopsEnabled, isFalse); + expect(settings.channelMinHops, 2); + expect(settings.channelMinHopsRetries, 1); + expect(settings.channelMinHopsCountRepeaters, isFalse); + expect(settings.maxRouteWeight, AppSettings.defaultMaxRouteWeight); + + final reloaded = AppSettingsService(); + await reloaded.loadSettings(); + expect( + reloaded.settings.directRetries, + SendAttemptPlan.defaultDirectRetries, + ); + expect(reloaded.settings.floodRetries, SendAttemptPlan.defaultFloodRetries); + }); +} diff --git a/test/screens/routing_settings_screen_test.dart b/test/screens/routing_settings_screen_test.dart new file mode 100644 index 00000000..402d95cb --- /dev/null +++ b/test/screens/routing_settings_screen_test.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/send_attempt_plan.dart'; +import 'package:meshcore_open/screens/app_settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/widgets/settings_reveal.dart'; + +void main() { + testWidgets( + 'routing settings show both retry limits and reveal channel options', + (tester) async { + SharedPreferences.setMockInitialValues({}); + await PrefsManager.initialize(); + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith(autoRouteRotationEnabled: false), + ); + + tester.view.physicalSize = const Size(800, 8000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final connector = MeshCoreConnector(); + final translation = TranslationService(settings); + final uploads = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + addTearDown(connector.dispose); + addTearDown(translation.dispose); + addTearDown(uploads.dispose); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: uploads), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: AppSettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + final context = tester.element(find.byType(AppSettingsScreen)); + final l10n = AppLocalizations.of(context); + + expect(find.text(l10n.appSettings_clearPathOnMaxRetry), findsOneWidget); + expect( + find.text( + l10n.appSettings_directRetries(SendAttemptPlan.defaultDirectRetries), + ), + findsOneWidget, + ); + expect( + find.text( + l10n.appSettings_floodRetries(SendAttemptPlan.defaultFloodRetries), + ), + findsOneWidget, + ); + expect( + find.text( + l10n.appSettings_loginAttempts(SendAttemptPlan.defaultLoginAttempts), + ), + findsOneWidget, + ); + // Retry limits stay visible while route rotation is off. + expect(find.text(l10n.appSettings_autoRouteRotation), findsOneWidget); + expect(find.text(l10n.appSettings_channelMinHopsCount(2)), findsNothing); + expect(find.text(l10n.appSettings_resetRoutingToDefault), findsOneWidget); + + final channelSwitch = find.text(l10n.appSettings_channelMinHops); + await tester.tap(channelSwitch); + await tester.pump(); + await tester.pump(RevealOnEnable.duration); + await tester.pumpAndSettle(); + + expect( + find.text(l10n.appSettings_channelMinHopsCount(2)), + findsOneWidget, + ); + expect( + find.text(l10n.appSettings_channelMinHopsRetries(1)), + findsOneWidget, + ); + + await tester.tap(channelSwitch); + await tester.pumpAndSettle(); + expect(find.text(l10n.appSettings_channelMinHopsCount(2)), findsNothing); + }, + ); +} diff --git a/test/services/message_retry_split_limits_test.dart b/test/services/message_retry_split_limits_test.dart new file mode 100644 index 00000000..f2fdcc4d --- /dev/null +++ b/test/services/message_retry_split_limits_test.dart @@ -0,0 +1,168 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/models/path_selection.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; + +Contact _contact({int pathLength = 1, List path = const [0x11]}) => + Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), + name: 'Test', + type: 1, + pathLength: pathLength, + path: Uint8List.fromList(path), + lastSeen: DateTime.now(), + ); + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + await PrefsManager.initialize(); + }); + + test('rotation sends direct attempts, then flood, then stops', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: true, + directRetries: 1, + floodRetries: 1, + ), + ); + + final service = MessageRetryService( + sentWatchdogGrace: const Duration(milliseconds: 5), + ); + addTearDown(service.dispose); + final sends = []; + final thresholds = []; + service.initialize( + RetryServiceConfig( + sendMessage: (_, _, attempt, _) async { + sends.add(attempt); + }, + addMessage: (_, _) {}, + updateMessage: (_) {}, + calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) => + 15, + appSettingsService: settings, + selectRetryPath: (_, attemptIndex, directRetries, _) { + thresholds.add(directRetries); + if (attemptIndex >= directRetries) { + return const PathSelection( + pathBytes: [], + hopCount: -1, + useFlood: true, + ); + } + return const PathSelection( + pathBytes: [0x22], + hopCount: 1, + useFlood: false, + ); + }, + ), + ); + + await service.sendMessageWithRetry(contact: _contact(), text: 'hello'); + await pumpEventQueue(); + await Future.delayed(const Duration(milliseconds: 1400)); + + expect(sends, [0, 1]); + expect(thresholds, [1, 1]); + }); + + test('rotation off keeps retrying a direct path without flooding', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: false, + directRetries: 2, + floodRetries: 5, + ), + ); + + final service = MessageRetryService( + sentWatchdogGrace: const Duration(milliseconds: 5), + ); + addTearDown(service.dispose); + final sends = []; + var picked = false; + service.initialize( + RetryServiceConfig( + sendMessage: (_, _, attempt, _) async { + sends.add(attempt); + }, + addMessage: (_, _) {}, + updateMessage: (_) {}, + calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) => + 15, + appSettingsService: settings, + selectRetryPath: (_, _, _, _) { + picked = true; + return const PathSelection( + pathBytes: [], + hopCount: -1, + useFlood: true, + ); + }, + ), + ); + + await service.sendMessageWithRetry(contact: _contact(), text: 'hello'); + await pumpEventQueue(); + await Future.delayed(const Duration(milliseconds: 1400)); + + expect(sends, [0, 1]); + expect(picked, isFalse); + }); + + test('a flood path without rotation stops after the flood budget', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: false, + directRetries: 4, + floodRetries: 1, + ), + ); + + final service = MessageRetryService( + sentWatchdogGrace: const Duration(milliseconds: 5), + ); + addTearDown(service.dispose); + final latest = []; + final sends = []; + service.initialize( + RetryServiceConfig( + sendMessage: (_, _, attempt, _) async { + sends.add(attempt); + }, + addMessage: (_, message) => latest.add(message), + updateMessage: (message) => latest.add(message), + calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) => + 15, + appSettingsService: settings, + ), + ); + + await service.sendMessageWithRetry( + contact: _contact(pathLength: -1, path: const []), + text: 'hello', + ); + await pumpEventQueue(); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(sends, [0]); + expect(latest.last.status, MessageStatus.failed); + }); +} diff --git a/test/services/message_retry_watchdog_test.dart b/test/services/message_retry_watchdog_test.dart index 9b0f29ec..b000d024 100644 --- a/test/services/message_retry_watchdog_test.dart +++ b/test/services/message_retry_watchdog_test.dart @@ -56,7 +56,12 @@ void main() { ); test('missing RESP_CODE_SENT times out and retries', () async { - await service.sendMessageWithRetry(contact: _contact(), text: 'hello'); + // A direct path uses the direct budget (default 4). A flood path would + // stop after the default single flood attempt. + await service.sendMessageWithRetry( + contact: _contact(pathLength: 1, path: const [0x11]), + text: 'hello', + ); await pumpEventQueue(); expect(sends.map((s) => s.attempt), [0]); @@ -80,7 +85,10 @@ void main() { }); test('late ACK for an attempt whose SENT was lost still delivers', () async { - await service.sendMessageWithRetry(contact: _contact(), text: 'hello'); + await service.sendMessageWithRetry( + contact: _contact(pathLength: 1, path: const [0x11]), + text: 'hello', + ); await pumpEventQueue(); // Let the watchdog fire; the retry is now waiting on its backoff. diff --git a/test/services/path_history_service_test.dart b/test/services/path_history_service_test.dart index 95f3b497..532c64b4 100644 --- a/test/services/path_history_service_test.dart +++ b/test/services/path_history_service_test.dart @@ -121,7 +121,7 @@ void main() { final pick = svc.selectPathForAttempt( pubKey, attemptIndex: attemptIndex, - maxRetries: 5, + directRetries: 4, recentSelections: recent, ); final key = pick.useFlood @@ -139,7 +139,7 @@ void main() { final selection = svc.selectPathForAttempt( pubKey, attemptIndex: 0, - maxRetries: 5, + directRetries: 4, ); expect(selection.useFlood, isTrue); }); @@ -150,7 +150,7 @@ void main() { final selection = svc.selectPathForAttempt( pubKey, attemptIndex: 0, - maxRetries: 0, + directRetries: 0, ); expect(selection.useFlood, isTrue); }); @@ -163,7 +163,7 @@ void main() { final selection = svc.selectPathForAttempt( pubKey, attemptIndex: i, - maxRetries: 5, + directRetries: 4, ); expect( selection.useFlood, @@ -274,7 +274,7 @@ void main() { final pick = svc.selectPathForAttempt( pubKey, attemptIndex: 0, - maxRetries: 5, + directRetries: 4, ); expect(pick.useFlood, isFalse); expect(pick.hopCount, 0); @@ -299,21 +299,28 @@ void main() { expect(resolved.pathBytes, isEmpty); }); - test('final attempt is always flood regardless of known paths', () async { + test('attempts at and after directRetries flood', () async { final pubKey = _hex('ef01'); await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1); - for (final retries in [1, 2, 5, 10]) { - final lastAttempt = svc.selectPathForAttempt( + for (final direct in [0, 1, 4, 9]) { + final flooded = svc.selectPathForAttempt( pubKey, - attemptIndex: retries - 1, - maxRetries: retries, + attemptIndex: direct, + directRetries: direct, ); expect( - lastAttempt.useFlood, + flooded.useFlood, isTrue, - reason: 'maxRetries=$retries: last attempt must be flood', + reason: 'directRetries=$direct: that attempt floods', ); + if (direct == 0) continue; + final routed = svc.selectPathForAttempt( + pubKey, + attemptIndex: direct - 1, + directRetries: direct, + ); + expect(routed.useFlood, isFalse); } }); }); diff --git a/test/services/route_chooser_test.dart b/test/services/route_chooser_test.dart index 33330614..b78f4fb3 100644 --- a/test/services/route_chooser_test.dart +++ b/test/services/route_chooser_test.dart @@ -205,7 +205,7 @@ void main() { final pick = svc.selectPathForAttempt( contact, attemptIndex: attempt, - maxRetries: maxRetries, + directRetries: maxRetries - 1, recentSelections: used, context: context, ); diff --git a/untranslated.json b/untranslated.json index 75375aac..bd211125 100644 --- a/untranslated.json +++ b/untranslated.json @@ -12,7 +12,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "cs": [ @@ -28,7 +35,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "de": [ @@ -44,7 +58,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "es": [ @@ -60,7 +81,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "fr": [ @@ -76,7 +104,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "hu": [ @@ -92,7 +127,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "it": [ @@ -108,7 +150,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "ja": [ @@ -124,7 +173,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "ko": [ @@ -140,7 +196,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "nl": [ @@ -156,7 +219,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "pl": [ @@ -172,7 +242,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "pt": [ @@ -188,7 +265,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "pt_PT": [ @@ -204,7 +288,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "ru": [ @@ -220,7 +311,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "sk": [ @@ -236,7 +334,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "sl": [ @@ -252,7 +357,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "sv": [ @@ -268,7 +380,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "uk": [ @@ -284,7 +403,14 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" + "settings_exportBookmarksNoBookmarks", + "receivedImage_packetEchoes", + "receivedImage_recoveryPacketEchoes", + "imageSend_preparingPreview", + "imageSend_tryAnother", + "imageSend_versionsHint", + "imageSend_versionLabel", + "imageSend_versionPackets" ], "zh": [ @@ -300,187 +426,7 @@ "settings_exportBookmarks", "settings_exportBookmarksSubtitle", "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks" - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "cs": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "de": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "es": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "fr": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "hu": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "it": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "ja": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "ko": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "nl": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "pl": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "pt": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "pt_PT": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "ru": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "sk": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "sl": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "sv": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "uk": [ - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets" - ], - - "zh": [ + "settings_exportBookmarksNoBookmarks", "receivedImage_packetEchoes", "receivedImage_recoveryPacketEchoes", "imageSend_preparingPreview", From dca270e5ad94192d50386294327d54d47912c5d6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 01:06:26 +0000 Subject: [PATCH 17/50] Add Repeaters and Rooms settings for login and clock sync Move login attempts and auto-fetch into the new section, and let a global clock-sync default be overridden per repeater. Co-authored-by: zjs81 --- documentation/additional-features.md | 1 - documentation/repeater-management.md | 6 +- documentation/settings.md | 9 +- lib/l10n/app_bg.arb | 15 ++- lib/l10n/app_cs.arb | 15 ++- lib/l10n/app_de.arb | 15 ++- lib/l10n/app_en.arb | 13 ++- lib/l10n/app_es.arb | 15 ++- lib/l10n/app_fr.arb | 15 ++- lib/l10n/app_hu.arb | 15 ++- lib/l10n/app_it.arb | 15 ++- lib/l10n/app_ja.arb | 15 ++- lib/l10n/app_ko.arb | 15 ++- lib/l10n/app_localizations.dart | 68 ++++++++++- lib/l10n/app_localizations_bg.dart | 42 ++++++- lib/l10n/app_localizations_cs.dart | 41 ++++++- lib/l10n/app_localizations_de.dart | 41 ++++++- lib/l10n/app_localizations_en.dart | 40 ++++++- lib/l10n/app_localizations_es.dart | 42 ++++++- lib/l10n/app_localizations_fr.dart | 42 ++++++- lib/l10n/app_localizations_hu.dart | 41 ++++++- lib/l10n/app_localizations_it.dart | 41 ++++++- lib/l10n/app_localizations_ja.dart | 39 ++++++- lib/l10n/app_localizations_ko.dart | 38 ++++++- lib/l10n/app_localizations_nl.dart | 41 ++++++- lib/l10n/app_localizations_pl.dart | 41 ++++++- lib/l10n/app_localizations_pt.dart | 83 +++++++++++++- lib/l10n/app_localizations_ru.dart | 41 ++++++- lib/l10n/app_localizations_sk.dart | 41 ++++++- lib/l10n/app_localizations_sl.dart | 41 ++++++- lib/l10n/app_localizations_sv.dart | 41 ++++++- lib/l10n/app_localizations_uk.dart | 41 ++++++- lib/l10n/app_localizations_zh.dart | 39 ++++++- lib/l10n/app_nl.arb | 15 ++- lib/l10n/app_pl.arb | 15 ++- lib/l10n/app_pt.arb | 15 ++- lib/l10n/app_pt_PT.arb | 15 ++- lib/l10n/app_ru.arb | 15 ++- lib/l10n/app_sk.arb | 15 ++- lib/l10n/app_sl.arb | 15 ++- lib/l10n/app_sv.arb | 15 ++- lib/l10n/app_uk.arb | 15 ++- lib/l10n/app_zh.arb | 15 ++- lib/models/app_settings.dart | 20 ++++ lib/screens/app_settings_screen.dart | 107 ++++++++++++++---- lib/screens/repeater_settings_screen.dart | 81 +++++++++---- lib/services/app_settings_service.dart | 20 +++- lib/services/storage_service.dart | 92 +++++++++++++-- lib/widgets/repeater_login_dialog.dart | 18 ++- lib/widgets/room_login_dialog.dart | 4 + test/models/send_attempt_plan_test.dart | 27 ++++- .../screens/routing_settings_screen_test.dart | 13 +++ test/services/repeater_clock_sync_test.dart | 81 +++++++++++++ 53 files changed, 1533 insertions(+), 128 deletions(-) create mode 100644 test/services/repeater_clock_sync_test.dart diff --git a/documentation/additional-features.md b/documentation/additional-features.md index 86739e68..0c630856 100644 --- a/documentation/additional-features.md +++ b/documentation/additional-features.md @@ -175,7 +175,6 @@ Handles reliable delivery of outgoing direct messages: ### Configurable Settings (App Settings → Routing) - Direct attempts (0–15, default 4) and flood attempts (0–10, default 1), set separately from auto route rotation -- Login attempts for a repeater or room server (1–10, default 5). Telemetry requests are not retried - Clear path on max retry (on/off) - Auto route rotation diff --git a/documentation/repeater-management.md b/documentation/repeater-management.md index b6d8a2d4..f3186edd 100644 --- a/documentation/repeater-management.md +++ b/documentation/repeater-management.md @@ -19,7 +19,7 @@ From the Contacts screen: - Routing mode selector and "Manage Paths" link are available directly in the dialog (configure routing before login) - Auto-retries up to 5 times on timeout, showing progress ("Attempt 2 of 5"). A wrong password (explicit failure response) stops immediately — only timeouts trigger retries - CLI commands to a repeater are matched to their reply by a short prefix. A reply that arrives late for an earlier attempt still completes the command, and no further attempts are sent -- If auto-clock-sync is enabled for this repeater (configured in Repeater Settings), a `clock sync` command is sent automatically on successful login +- If clock sync on login is on for this repeater, a `clock sync` command is sent automatically on successful login. The repeater's choice is Default, On, or Off. Default follows **Sync repeater clock on login** in App Settings → Repeaters and Rooms, which is off unless you turn it on --- @@ -179,7 +179,7 @@ Most settings are declared once in `repeaterSettingSpecs` (`lib/models/repeater_ - Packet forwarding toggle (`set repeat`) - Guest access toggle (`set allow.read.only`) - Multi-ACKs toggle (`set multi.acks`) -- Auto clock sync after login toggle (local app setting only, not sent to repeater) +- Clock sync after login (Default / On / Off; local app setting only, not sent to repeater). Default follows App Settings → Repeaters and Rooms **5. Network Health** - Loop detection dropdown (off / minimal / moderate / strict; `set loop.detect`) @@ -218,7 +218,7 @@ Most settings are declared once in `repeaterSettingSpecs` (`lib/models/repeater_ - Erase filesystem (serial-only; shown disabled with an explanation — no command is sent over the air) ### Key Interactions -- **Settings are not fetched on open by default.** Each `get` is a separate LoRa round trip, so fetching everything is slow and uses airtime. Turn on **Auto-fetch repeater settings** in App Settings to fetch everything when the screen opens; otherwise use **Refresh all** or the per-setting refresh buttons. Name and location are pre-filled from cached contact data +- **Settings are not fetched on open by default.** Each `get` is a separate LoRa round trip, so fetching everything is slow and uses airtime. Turn on **Auto-fetch repeater settings** in App Settings → Repeaters and Rooms to fetch everything when the screen opens; otherwise use **Refresh all** or the per-setting refresh buttons. Name and location are pre-filled from cached contact data - Every control can be edited before its value has been fetched. Unfetched values show as "—" (or off) until fetched or edited, and only edited settings are sent on save - Save button in app bar appears when any change is detected; failed commands keep those settings dirty for retry, and a saved value counts as the repeater's current value - Settings are sent sequentially with 200ms delays between commands; firmware responses are checked and partial failures are reported in a snackbar diff --git a/documentation/settings.md b/documentation/settings.md index 2efb4be9..f8326618 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -120,7 +120,6 @@ Individual channels can be muted from the channel chat bell icon, the channel li ### Messaging - **Jump to Oldest Unread**: When opening a chat, scrolls to the oldest unread message instead of the newest -- **Auto-fetch Repeater Settings** (off by default): Requests every setting when a repeater's settings screen opens. Each setting is a separate request over LoRa, so this is slow and uses airtime; when off, use Refresh All or the per-setting refresh buttons. See [Repeater Settings](repeater-management.md#repeater-settings) - **Enable Message Tracing**: Shows path trace overlays and extra metadata on messages - **Region next to hop count** (default off): Shows a channel message's region chip on the same line as its hop count instead of below it @@ -130,7 +129,6 @@ What happens when a message is sent. Each slider shows its selected number in th - **Clear Path on Max Retry**: Erases the stored routing path after every send attempt fails - **Direct attempts** (0–15, default 4): How many times to try a known route. Available whether or not auto route rotation is on - **Flood attempts** (0–10, default 1): How many times to flood. Floods use more airtime. With rotation on, these run after the direct attempts. With it off, they apply only when the contact's path is already Flood -- **Login attempts** (1–10, default 5): How many times to try logging in to a repeater or room server. Telemetry fetches are sent once and have no retry setting - **Auto Route Rotation**: Lets the app choose each direct attempt's route from the routes that have worked for that contact (see [Auto route selection](routing-paths.md#auto-route-selection)). Off keeps the contact's current path for every attempt - **Resend channel messages until they travel far enough** (default off): If your channel message isn't heard coming back through enough repeaters, it's sent again. Uses more airtime. When on, it shows: - Required hops (1–8, default 2) @@ -140,6 +138,13 @@ What happens when a message is sent. Each slider shows its selected number in th If both direct and flood attempts are 0, the message is still sent once on the current path. A saved `max_message_retries` value from an older version becomes that many attempts minus one direct, plus one flood, which keeps the old "last attempt floods" behaviour for the previous default of 5 (4 direct + 1 flood). +### Repeaters and Rooms +- **Sync repeater clock on login** (off by default): After a successful repeater login, send `clock sync`. Off is the previous default: a repeater only synced when its own switch was on. Each repeater can override this with Default, On, or Off. Default follows this switch. A saved per-repeater on or off stays an override +- **Focus the password field** (off by default): On keeps the previous login dialog: the cursor goes into an empty password field (room login still skips this on a phone). Off waits until you tap the field, so the keyboard does not cover the dialog +- **Login attempts** (1–10, default 5): How many times to try logging in to a repeater or room server. Telemetry fetches are sent once and have no retry setting +- **Auto-fetch Repeater Settings** (off by default): Requests every setting when a repeater's settings screen opens. Each setting is a separate request over LoRa, so this is slow and uses airtime; when off, use Refresh All or the per-setting refresh buttons. See [Repeater Settings](repeater-management.md#repeater-settings) +- **Reset repeater and room settings to defaults**: Restores the controls in this section. Choices saved on individual repeaters are left alone + ### Battery - **Battery Chemistry**: NMC / LiFePO4 / LiPo (per device, used to calibrate percentage from voltage) diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 47ddb12f..c76032b7 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -2383,7 +2383,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Автоматично изпращайте съобщение \"синхронизиране на часовника\" след успешно влизане.", + "repeater_clockSyncAfterLoginSubtitle": "По подразбиране следва „Повторители и стаи“ в настройките. Вкл. и Изкл. важат само за този повторител.", "repeater_clockSyncAfterLogin": "Синхронизиране на часовника след влизане", "chat_sendMessage": "Изпратете съобщение", "room_guest": "Информация за сървъра на стаята", @@ -3782,5 +3782,16 @@ "appSettings_floodRetries": "Опити Flood: {count}", "appSettings_floodRetriesSubtitle": "Колко пъти да се използва Flood. Flood заема повече ефирно време. При включена ротация идват след директните опити.", "appSettings_loginAttempts": "Опити за вход: {count}", - "appSettings_loginAttemptsSubtitle": "Колко пъти да се опитва вход към ретранслатор или room сървър, преди да се откаже." + "appSettings_loginAttemptsSubtitle": "Колко пъти да се опитва вход към ретранслатор или room сървър, преди да се откаже.", + "appSettings_repeatersAndRooms": "Повторители и стаи", + "appSettings_clockSyncAfterLogin": "Синхронизиране на часовника при вход", + "appSettings_clockSyncAfterLoginSubtitle": "След успешен вход в повторител се изпраща clock sync. Всеки повторител пак може да е По подразбиране, Вкл. или Изкл.", + "appSettings_loginPasswordAutofocus": "Фокус върху полето за парола", + "appSettings_loginPasswordAutofocusSubtitle": "При отваряне на вход в повторител или стая курсорът отива в празното поле за парола. Изключено оставя диалога видим, докато не докоснете полето.", + "appSettings_resetRepeaterRoomSettings": "Нулиране на настройките за повторители и стаи", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Възстановява настройките в този раздел. Изборите за отделни повторители остават.", + "appSettings_repeaterRoomSettingsReset": "Настройките за повторители и стаи са нулирани", + "repeater_clockSyncDefault": "По подразбиране", + "repeater_clockSyncOn": "Вкл.", + "repeater_clockSyncOff": "Изкл." } diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index 1d9843eb..ce3a853b 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -1639,7 +1639,7 @@ "repeater_settings": "Nastavení", "repeater_settingsSubtitle": "Konfigurace parametrů opakovače", "repeater_clockSyncAfterLogin": "Synchronizace hodin po přihlášení", - "repeater_clockSyncAfterLoginSubtitle": "Automaticky odeslat „clock sync“ po úspěšném přihlášení", + "repeater_clockSyncAfterLoginSubtitle": "Výchozí se řídí Opakovači a místnostmi v nastavení aplikace. Zapnuto a Vypnuto platí jen pro tento opakovač.", "repeater_statusTitle": "Stav opakovače", "repeater_routingMode": "Režim směrování", "repeater_refresh": "Obnovit", @@ -4395,5 +4395,16 @@ "appSettings_floodRetries": "Pokusy Flood: {count}", "appSettings_floodRetriesSubtitle": "Kolikrát se použije Flood. Flood zabere víc vysílacího času. Při zapnutém střídání následují po přímých pokusech.", "appSettings_loginAttempts": "Pokusy o přihlášení: {count}", - "appSettings_loginAttemptsSubtitle": "Kolikrát se zkusí přihlášení k opakovači nebo room serveru, než se to vzdá." + "appSettings_loginAttemptsSubtitle": "Kolikrát se zkusí přihlášení k opakovači nebo room serveru, než se to vzdá.", + "appSettings_repeatersAndRooms": "Opakovače a místnosti", + "appSettings_clockSyncAfterLogin": "Synchronizovat hodiny opakovače při přihlášení", + "appSettings_clockSyncAfterLoginSubtitle": "Po úspěšném přihlášení k opakovači se odešle clock sync. Každý opakovač může dál zvolit Výchozí, Zapnuto nebo Vypnuto.", + "appSettings_loginPasswordAutofocus": "Zaměřit pole hesla", + "appSettings_loginPasswordAutofocusSubtitle": "Při otevření přihlášení k opakovači nebo místnosti je kurzor v prázdném poli hesla. Vypnuto nechá dialog viditelný, dokud na pole neklepnete.", + "appSettings_resetRepeaterRoomSettings": "Obnovit nastavení opakovačů a místností", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Obnoví nastavení v této části. Volby uložené u jednotlivých opakovačů zůstanou.", + "appSettings_repeaterRoomSettingsReset": "Nastavení opakovačů a místností obnoveno", + "repeater_clockSyncDefault": "Výchozí", + "repeater_clockSyncOn": "Zapnuto", + "repeater_clockSyncOff": "Vypnuto" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index e996a4d4..08aebcc5 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -2511,7 +2511,7 @@ "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, "repeater_clockSyncAfterLogin": "Uhrzeit-Synchronisation nach dem Anmelden", - "repeater_clockSyncAfterLoginSubtitle": "Automatisch \"Uhrzeit-Synchronisierung\" nach erfolgreicher Anmeldung senden.", + "repeater_clockSyncAfterLoginSubtitle": "Standard folgt Repeater und Räume in den App-Einstellungen. An und Aus gelten nur für diesen Repeater.", "repeater_guest": "Informationen zu Repeatern", "repeater_guestTools": "Gastwerkzeuge", "chat_sendMessage": "Nachricht senden", @@ -3917,5 +3917,16 @@ "appSettings_floodRetries": "Flood-Versuche: {count}", "appSettings_floodRetriesSubtitle": "Wie oft geflutet wird. Flood verbraucht mehr Sendezeit. Bei eingeschalteter Rotation folgen diese auf die direkten Versuche.", "appSettings_loginAttempts": "Anmeldeversuche: {count}", - "appSettings_loginAttemptsSubtitle": "Wie oft die Anmeldung an einem Repeater oder Room-Server versucht wird, bevor abgebrochen wird." + "appSettings_loginAttemptsSubtitle": "Wie oft die Anmeldung an einem Repeater oder Room-Server versucht wird, bevor abgebrochen wird.", + "appSettings_repeatersAndRooms": "Repeater und Räume", + "appSettings_clockSyncAfterLogin": "Repeater-Uhr bei Anmeldung synchronisieren", + "appSettings_clockSyncAfterLoginSubtitle": "Nach einer erfolgreichen Repeater-Anmeldung wird clock sync gesendet. Jeder Repeater kann weiter Standard, An oder Aus wählen.", + "appSettings_loginPasswordAutofocus": "Passwortfeld fokussieren", + "appSettings_loginPasswordAutofocusSubtitle": "Beim Öffnen einer Repeater- oder Raum-Anmeldung steht der Cursor im leeren Passwortfeld. Aus lässt den Dialog sichtbar, bis du das Feld antippst.", + "appSettings_resetRepeaterRoomSettings": "Repeater- und Raum-Einstellungen zurücksetzen", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Stellt die Einstellungen in diesem Abschnitt wieder her. Gespeicherte Wahl bei einzelnen Repeatern bleibt.", + "appSettings_repeaterRoomSettingsReset": "Repeater- und Raum-Einstellungen zurückgesetzt", + "repeater_clockSyncDefault": "Standard", + "repeater_clockSyncOn": "An", + "repeater_clockSyncOff": "Aus" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 52461453..a32c729b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -653,6 +653,14 @@ } }, "appSettings_loginAttemptsSubtitle": "How many times to try logging in to a repeater or room server before giving up.", + "appSettings_repeatersAndRooms": "Repeaters and Rooms", + "appSettings_clockSyncAfterLogin": "Sync repeater clock on login", + "appSettings_clockSyncAfterLoginSubtitle": "After a successful repeater login, send clock sync. Each repeater can still choose Default, On, or Off.", + "appSettings_loginPasswordAutofocus": "Focus the password field", + "appSettings_loginPasswordAutofocusSubtitle": "When opening a repeater or room login, put the cursor in the password field if it is empty. Off leaves the dialog visible until you tap the field.", + "appSettings_resetRepeaterRoomSettings": "Reset repeater and room settings to defaults", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Restore the settings in this section to their defaults. Choices saved on individual repeaters stay as they are.", + "appSettings_repeaterRoomSettingsReset": "Repeater and room settings reset to defaults", "appSettings_ipfsImageLinks": "IPFS provider configuration", "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", "appSettings_loadLinkImages": "Load images from links", @@ -1883,7 +1891,10 @@ "@repeater_clockSyncAfterLogin": { "description": "Repeater setting: auto sync device clock after successful login" }, - "repeater_clockSyncAfterLoginSubtitle": "Automatically send \"clock sync\" after a successful login", + "repeater_clockSyncAfterLoginSubtitle": "Default follows Repeaters and Rooms in App Settings. On and Off apply only to this repeater.", + "repeater_clockSyncDefault": "Default", + "repeater_clockSyncOn": "On", + "repeater_clockSyncOff": "Off", "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 95c9fb04..78bbba3f 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -2426,7 +2426,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Enviar automáticamente la función de \"sincronización de reloj\" después de un inicio de sesión exitoso.", + "repeater_clockSyncAfterLoginSubtitle": "Predeterminado sigue Repetidores y salas en Ajustes. Activado y Desactivado valen solo para este repetidor.", "repeater_clockSyncAfterLogin": "Sincronización del reloj después de iniciar sesión", "repeater_guest": "Información sobre repetidores", "chat_sendMessage": "Enviar mensaje", @@ -3968,5 +3968,16 @@ "appSettings_floodRetries": "Intentos Flood: {count}", "appSettings_floodRetriesSubtitle": "Cuántas veces usar Flood. Flood usa más tiempo de aire. Con la rotación activada, van después de los intentos directos.", "appSettings_loginAttempts": "Intentos de inicio de sesión: {count}", - "appSettings_loginAttemptsSubtitle": "Cuántas veces intentar iniciar sesión en un repetidor o servidor de sala antes de rendirse." + "appSettings_loginAttemptsSubtitle": "Cuántas veces intentar iniciar sesión en un repetidor o servidor de sala antes de rendirse.", + "appSettings_repeatersAndRooms": "Repetidores y salas", + "appSettings_clockSyncAfterLogin": "Sincronizar el reloj del repetidor al iniciar sesión", + "appSettings_clockSyncAfterLoginSubtitle": "Tras un inicio de sesión correcto en un repetidor se envía clock sync. Cada repetidor puede seguir eligiendo Predeterminado, Activado o Desactivado.", + "appSettings_loginPasswordAutofocus": "Enfocar el campo de contraseña", + "appSettings_loginPasswordAutofocusSubtitle": "Al abrir el inicio de sesión de un repetidor o una sala, el cursor va al campo de contraseña si está vacío. Desactivado deja el diálogo visible hasta que toques el campo.", + "appSettings_resetRepeaterRoomSettings": "Restablecer ajustes de repetidores y salas", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Restaura los ajustes de esta sección. Las elecciones guardadas en cada repetidor se quedan.", + "appSettings_repeaterRoomSettingsReset": "Ajustes de repetidores y salas restablecidos", + "repeater_clockSyncDefault": "Predeterminado", + "repeater_clockSyncOn": "Activado", + "repeater_clockSyncOff": "Desactivado" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 7328109b..a66f165c 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2418,7 +2418,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Envoyer automatiquement une notification \"synchronisation de l'heure\" après une connexion réussie.", + "repeater_clockSyncAfterLoginSubtitle": "Défaut suit Répéteurs et salons dans les paramètres. Activé et Désactivé ne concernent que ce répéteur.", "repeater_clockSyncAfterLogin": "Synchronisation de l'horloge après la connexion", "repeater_guestTools": "Outils pour les invités", "chat_sendMessage": "Envoyer un message", @@ -3916,5 +3916,16 @@ "appSettings_floodRetries": "Tentatives Flood : {count}", "appSettings_floodRetriesSubtitle": "Nombre de Flood. Un Flood utilise plus de temps d'antenne. Avec la rotation activée, ils suivent les tentatives directes.", "appSettings_loginAttempts": "Tentatives de connexion : {count}", - "appSettings_loginAttemptsSubtitle": "Nombre d'essais de connexion à un répéteur ou à un serveur de salon avant d'abandonner." + "appSettings_loginAttemptsSubtitle": "Nombre d'essais de connexion à un répéteur ou à un serveur de salon avant d'abandonner.", + "appSettings_repeatersAndRooms": "Répéteurs et salons", + "appSettings_clockSyncAfterLogin": "Synchroniser l'horloge du répéteur à la connexion", + "appSettings_clockSyncAfterLoginSubtitle": "Après une connexion réussie à un répéteur, clock sync est envoyé. Chaque répéteur peut encore choisir Défaut, Activé ou Désactivé.", + "appSettings_loginPasswordAutofocus": "Placer le curseur dans le mot de passe", + "appSettings_loginPasswordAutofocusSubtitle": "À l'ouverture d'une connexion répéteur ou salon, le curseur va dans le mot de passe s'il est vide. Désactivé laisse la fenêtre visible jusqu'à ce que vous touchiez le champ.", + "appSettings_resetRepeaterRoomSettings": "Réinitialiser les paramètres répéteurs et salons", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Restaure les paramètres de cette section. Les choix enregistrés sur chaque répéteur restent.", + "appSettings_repeaterRoomSettingsReset": "Paramètres répéteurs et salons réinitialisés", + "repeater_clockSyncDefault": "Défaut", + "repeater_clockSyncOn": "Activé", + "repeater_clockSyncOff": "Désactivé" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 243963b5..2a0234dc 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -2421,7 +2421,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "„Óraszinkronizálás” automatikus küldése sikeres bejelentkezés után", + "repeater_clockSyncAfterLoginSubtitle": "Az Alapértelmezett az alkalmazás Átjátszók és szobák beállítását követi. A Be és a Ki csak erre az átjátszóra vonatkozik.", "repeater_clockSyncAfterLogin": "Óra szinkronizálás bejelentkezés után", "repeater_guestTools": "Vendégeszközök", "room_guest": "Szobaszerver információ", @@ -3873,5 +3873,16 @@ "appSettings_floodRetries": "Flood próbálkozások: {count}", "appSettings_floodRetriesSubtitle": "Hányszor használjon Floodot. A Flood több adásidőt használ. Bekapcsolt váltásnál a közvetlen próbálkozások után jönnek.", "appSettings_loginAttempts": "Bejelentkezési próbálkozások: {count}", - "appSettings_loginAttemptsSubtitle": "Hányszor próbáljon bejelentkezni egy átjátszóra vagy room szerverre, mielőtt feladja." + "appSettings_loginAttemptsSubtitle": "Hányszor próbáljon bejelentkezni egy átjátszóra vagy room szerverre, mielőtt feladja.", + "appSettings_repeatersAndRooms": "Átjátszók és szobák", + "appSettings_clockSyncAfterLogin": "Átjátszó órájának szinkronizálása belépéskor", + "appSettings_clockSyncAfterLoginSubtitle": "Sikeres átjátszó-belépés után clock sync megy ki. Minden átjátszó továbbra lehet Alapértelmezett, Be vagy Ki.", + "appSettings_loginPasswordAutofocus": "Jelszómező fókuszba", + "appSettings_loginPasswordAutofocusSubtitle": "Átjátszó vagy szoba belépésének megnyitásakor a kurzor az üres jelszómezőbe kerül. Kikapcsolva a párbeszéd látható marad, amíg meg nem érinti a mezőt.", + "appSettings_resetRepeaterRoomSettings": "Átjátszó- és szobabeállítások visszaállítása", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Visszaállítja a szakasz beállításait. Az egyes átjátszóknál mentett választás megmarad.", + "appSettings_repeaterRoomSettingsReset": "Átjátszó- és szobabeállítások visszaállítva", + "repeater_clockSyncDefault": "Alapért.", + "repeater_clockSyncOn": "Be", + "repeater_clockSyncOff": "Ki" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 9ef267fc..130e2ef3 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -2432,7 +2432,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Invia automaticamente il comando \"sincronizzazione dell'orologio\" dopo un login riuscito.", + "repeater_clockSyncAfterLoginSubtitle": "Predefinito segue Ripetitori e stanze nelle impostazioni. Attivo e Disattivo valgono solo per questo ripetitore.", "repeater_clockSyncAfterLogin": "Sincronizzazione dell'orologio dopo il login", "repeater_guest": "Informazioni sul ripetitore", "repeater_guestTools": "Strumenti per gli ospiti", @@ -3916,5 +3916,16 @@ "appSettings_floodRetries": "Tentativi Flood: {count}", "appSettings_floodRetriesSubtitle": "Quante volte usare Flood. Flood usa più tempo in aria. Con la rotazione attiva, seguono i tentativi diretti.", "appSettings_loginAttempts": "Tentativi di accesso: {count}", - "appSettings_loginAttemptsSubtitle": "Quante volte provare l'accesso a un ripetitore o a un server room prima di rinunciare." + "appSettings_loginAttemptsSubtitle": "Quante volte provare l'accesso a un ripetitore o a un server room prima di rinunciare.", + "appSettings_repeatersAndRooms": "Ripetitori e stanze", + "appSettings_clockSyncAfterLogin": "Sincronizza l'orologio del ripetitore all'accesso", + "appSettings_clockSyncAfterLoginSubtitle": "Dopo un accesso riuscito a un ripetitore viene inviato clock sync. Ogni ripetitore può ancora scegliere Predefinito, Attivo o Disattivo.", + "appSettings_loginPasswordAutofocus": "Attiva il campo password", + "appSettings_loginPasswordAutofocusSubtitle": "All'apertura dell'accesso a un ripetitore o a una stanza, il cursore va nel campo password se è vuoto. Disattivo lascia visibile la finestra finché non tocchi il campo.", + "appSettings_resetRepeaterRoomSettings": "Reimposta le impostazioni di ripetitori e stanze", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Ripristina le impostazioni di questa sezione. Le scelte salvate sui singoli ripetitori restano.", + "appSettings_repeaterRoomSettingsReset": "Impostazioni di ripetitori e stanze reimpostate", + "repeater_clockSyncDefault": "Predefinito", + "repeater_clockSyncOn": "Attivo", + "repeater_clockSyncOff": "Disattivo" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 10a5b039..38f7bbb4 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -2432,7 +2432,7 @@ "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, "repeater_clockSyncAfterLogin": "ログイン後に時刻を同期", - "repeater_clockSyncAfterLoginSubtitle": "ログイン成功時に自動で時刻同期を送信します", + "repeater_clockSyncAfterLoginSubtitle": "「既定」はアプリ設定の「リピーターとルーム」に従います。「オン」と「オフ」はこのリピーターだけです。", "room_guest": "ルームサーバーに関する情報", "chat_sendMessage": "メッセージを送信する", "repeater_guest": "リピータに関する情報", @@ -4122,5 +4122,16 @@ "appSettings_floodRetries": "Flood の試行: {count}", "appSettings_floodRetriesSubtitle": "Flood する回数です。Flood は通信時間を多く使います。切り替えがオンのとき、直接の試行の後に行います。", "appSettings_loginAttempts": "ログイン試行: {count}", - "appSettings_loginAttemptsSubtitle": "リピータまたはルームサーバーへのログインをあきらめるまでの回数です。" + "appSettings_loginAttemptsSubtitle": "リピータまたはルームサーバーへのログインをあきらめるまでの回数です。", + "appSettings_repeatersAndRooms": "リピーターとルーム", + "appSettings_clockSyncAfterLogin": "ログイン時にリピーターの時刻を同期", + "appSettings_clockSyncAfterLoginSubtitle": "リピーターへのログインに成功すると clock sync を送ります。各リピーターは「既定」「オン」「オフ」を選べます。", + "appSettings_loginPasswordAutofocus": "パスワード欄にフォーカス", + "appSettings_loginPasswordAutofocusSubtitle": "リピーターまたはルームのログインを開いたとき、パスワードが空ならその欄にカーソルを置きます。オフでは欄をタップするまで画面全体が見えます。", + "appSettings_resetRepeaterRoomSettings": "リピーターとルームの設定をリセット", + "appSettings_resetRepeaterRoomSettingsSubtitle": "このセクションの設定を戻します。各リピーターに保存した選択はそのままです。", + "appSettings_repeaterRoomSettingsReset": "リピーターとルームの設定をリセットしました", + "repeater_clockSyncDefault": "既定", + "repeater_clockSyncOn": "オン", + "repeater_clockSyncOff": "オフ" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 39f55216..17e1de09 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -2337,7 +2337,7 @@ "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, "repeater_clockSyncAfterLogin": "로그인 후 시계 동기화", - "repeater_clockSyncAfterLoginSubtitle": "성공적인 로그인 후, 자동으로 \"시간 동기화\"를 전송합니다.", + "repeater_clockSyncAfterLoginSubtitle": "기본은 앱 설정의 리피터와 방을 따릅니다. 켜기와 끄기는 이 리피터에만 적용됩니다.", "repeater_guestTools": "게스트 도구", "chat_sendMessage": "메시지를 보내기", "repeater_guest": "리피터 정보", @@ -4122,5 +4122,16 @@ "appSettings_floodRetries": "Flood 시도: {count}", "appSettings_floodRetriesSubtitle": "Flood를 사용하는 횟수입니다. Flood는 전파 시간을 더 씁니다. 순환이 켜져 있으면 직접 시도 다음에 실행됩니다.", "appSettings_loginAttempts": "로그인 시도: {count}", - "appSettings_loginAttemptsSubtitle": "중계기나 룸 서버 로그인을 포기하기 전까지의 시도 횟수입니다." + "appSettings_loginAttemptsSubtitle": "중계기나 룸 서버 로그인을 포기하기 전까지의 시도 횟수입니다.", + "appSettings_repeatersAndRooms": "리피터와 방", + "appSettings_clockSyncAfterLogin": "로그인 시 리피터 시계 동기화", + "appSettings_clockSyncAfterLoginSubtitle": "리피터 로그인에 성공하면 clock sync를 보냅니다. 각 리피터는 기본, 켜기, 끄기를 고를 수 있습니다.", + "appSettings_loginPasswordAutofocus": "비밀번호 칸에 포커스", + "appSettings_loginPasswordAutofocusSubtitle": "리피터나 방 로그인을 열 때 비밀번호가 비어 있으면 그 칸에 커서를 둡니다. 끄면 칸을 누를 때까지 대화상자가 보입니다.", + "appSettings_resetRepeaterRoomSettings": "리피터와 방 설정을 기본값으로", + "appSettings_resetRepeaterRoomSettingsSubtitle": "이 섹션의 설정을 되돌립니다. 각 리피터에 저장한 선택은 그대로입니다.", + "appSettings_repeaterRoomSettingsReset": "리피터와 방 설정을 되돌렸습니다", + "repeater_clockSyncDefault": "기본", + "repeater_clockSyncOn": "켜기", + "repeater_clockSyncOff": "끄기" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 48f7031a..217d45c3 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2719,6 +2719,54 @@ abstract class AppLocalizations { /// **'How many times to try logging in to a repeater or room server before giving up.'** String get appSettings_loginAttemptsSubtitle; + /// No description provided for @appSettings_repeatersAndRooms. + /// + /// In en, this message translates to: + /// **'Repeaters and Rooms'** + String get appSettings_repeatersAndRooms; + + /// No description provided for @appSettings_clockSyncAfterLogin. + /// + /// In en, this message translates to: + /// **'Sync repeater clock on login'** + String get appSettings_clockSyncAfterLogin; + + /// No description provided for @appSettings_clockSyncAfterLoginSubtitle. + /// + /// In en, this message translates to: + /// **'After a successful repeater login, send clock sync. Each repeater can still choose Default, On, or Off.'** + String get appSettings_clockSyncAfterLoginSubtitle; + + /// No description provided for @appSettings_loginPasswordAutofocus. + /// + /// In en, this message translates to: + /// **'Focus the password field'** + String get appSettings_loginPasswordAutofocus; + + /// No description provided for @appSettings_loginPasswordAutofocusSubtitle. + /// + /// In en, this message translates to: + /// **'When opening a repeater or room login, put the cursor in the password field if it is empty. Off leaves the dialog visible until you tap the field.'** + String get appSettings_loginPasswordAutofocusSubtitle; + + /// No description provided for @appSettings_resetRepeaterRoomSettings. + /// + /// In en, this message translates to: + /// **'Reset repeater and room settings to defaults'** + String get appSettings_resetRepeaterRoomSettings; + + /// No description provided for @appSettings_resetRepeaterRoomSettingsSubtitle. + /// + /// In en, this message translates to: + /// **'Restore the settings in this section to their defaults. Choices saved on individual repeaters stay as they are.'** + String get appSettings_resetRepeaterRoomSettingsSubtitle; + + /// No description provided for @appSettings_repeaterRoomSettingsReset. + /// + /// In en, this message translates to: + /// **'Repeater and room settings reset to defaults'** + String get appSettings_repeaterRoomSettingsReset; + /// No description provided for @appSettings_ipfsImageLinks. /// /// In en, this message translates to: @@ -6165,9 +6213,27 @@ abstract class AppLocalizations { /// Repeater setting subtitle: describes the clock sync after login behavior /// /// In en, this message translates to: - /// **'Automatically send \"clock sync\" after a successful login'** + /// **'Default follows Repeaters and Rooms in App Settings. On and Off apply only to this repeater.'** String get repeater_clockSyncAfterLoginSubtitle; + /// No description provided for @repeater_clockSyncDefault. + /// + /// In en, this message translates to: + /// **'Default'** + String get repeater_clockSyncDefault; + + /// No description provided for @repeater_clockSyncOn. + /// + /// In en, this message translates to: + /// **'On'** + String get repeater_clockSyncOn; + + /// No description provided for @repeater_clockSyncOff. + /// + /// In en, this message translates to: + /// **'Off'** + String get repeater_clockSyncOff; + /// No description provided for @repeater_statusTitle. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index ca492bc5..bccc215e 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1504,6 +1504,37 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Колко пъти да се опитва вход към ретранслатор или room сървър, преди да се откаже.'; + @override + String get appSettings_repeatersAndRooms => 'Повторители и стаи'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Синхронизиране на часовника при вход'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'След успешен вход в повторител се изпраща clock sync. Всеки повторител пак може да е По подразбиране, Вкл. или Изкл.'; + + @override + String get appSettings_loginPasswordAutofocus => + 'Фокус върху полето за парола'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'При отваряне на вход в повторител или стая курсорът отива в празното поле за парола. Изключено оставя диалога видим, докато не докоснете полето.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Нулиране на настройките за повторители и стаи'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Възстановява настройките в този раздел. Изборите за отделни повторители остават.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Настройките за повторители и стаи са нулирани'; + @override String get appSettings_ipfsImageLinks => 'Конфигурация на IPFS доставчик'; @@ -3534,7 +3565,16 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Автоматично изпращайте съобщение \"синхронизиране на часовника\" след успешно влизане.'; + 'По подразбиране следва „Повторители и стаи“ в настройките. Вкл. и Изкл. важат само за този повторител.'; + + @override + String get repeater_clockSyncDefault => 'По подразбиране'; + + @override + String get repeater_clockSyncOn => 'Вкл.'; + + @override + String get repeater_clockSyncOff => 'Изкл.'; @override String get repeater_statusTitle => 'Статус на повтарянето'; diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 81ff8f3f..15dd9704 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -1493,6 +1493,36 @@ class AppLocalizationsCs extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Kolikrát se zkusí přihlášení k opakovači nebo room serveru, než se to vzdá.'; + @override + String get appSettings_repeatersAndRooms => 'Opakovače a místnosti'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Synchronizovat hodiny opakovače při přihlášení'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Po úspěšném přihlášení k opakovači se odešle clock sync. Každý opakovač může dál zvolit Výchozí, Zapnuto nebo Vypnuto.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Zaměřit pole hesla'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Při otevření přihlášení k opakovači nebo místnosti je kurzor v prázdném poli hesla. Vypnuto nechá dialog viditelný, dokud na pole neklepnete.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Obnovit nastavení opakovačů a místností'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Obnoví nastavení v této části. Volby uložené u jednotlivých opakovačů zůstanou.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Nastavení opakovačů a místností obnoveno'; + @override String get appSettings_ipfsImageLinks => 'Konfigurace poskytovatele IPFS'; @@ -3519,7 +3549,16 @@ class AppLocalizationsCs extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Automaticky odeslat „clock sync“ po úspěšném přihlášení'; + 'Výchozí se řídí Opakovači a místnostmi v nastavení aplikace. Zapnuto a Vypnuto platí jen pro tento opakovač.'; + + @override + String get repeater_clockSyncDefault => 'Výchozí'; + + @override + String get repeater_clockSyncOn => 'Zapnuto'; + + @override + String get repeater_clockSyncOff => 'Vypnuto'; @override String get repeater_statusTitle => 'Stav opakovače'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index d43bf080..5440f98d 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1505,6 +1505,36 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Wie oft die Anmeldung an einem Repeater oder Room-Server versucht wird, bevor abgebrochen wird.'; + @override + String get appSettings_repeatersAndRooms => 'Repeater und Räume'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Repeater-Uhr bei Anmeldung synchronisieren'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Nach einer erfolgreichen Repeater-Anmeldung wird clock sync gesendet. Jeder Repeater kann weiter Standard, An oder Aus wählen.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Passwortfeld fokussieren'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Beim Öffnen einer Repeater- oder Raum-Anmeldung steht der Cursor im leeren Passwortfeld. Aus lässt den Dialog sichtbar, bis du das Feld antippst.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Repeater- und Raum-Einstellungen zurücksetzen'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Stellt die Einstellungen in diesem Abschnitt wieder her. Gespeicherte Wahl bei einzelnen Repeatern bleibt.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Repeater- und Raum-Einstellungen zurückgesetzt'; + @override String get appSettings_ipfsImageLinks => 'IPFS-Anbieter-Konfiguration'; @@ -3537,7 +3567,16 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Automatisch \"Uhrzeit-Synchronisierung\" nach erfolgreicher Anmeldung senden.'; + 'Standard folgt Repeater und Räume in den App-Einstellungen. An und Aus gelten nur für diesen Repeater.'; + + @override + String get repeater_clockSyncDefault => 'Standard'; + + @override + String get repeater_clockSyncOn => 'An'; + + @override + String get repeater_clockSyncOff => 'Aus'; @override String get repeater_statusTitle => 'Repeater-Status'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 6b8136a3..0f00916d 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1476,6 +1476,35 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'How many times to try logging in to a repeater or room server before giving up.'; + @override + String get appSettings_repeatersAndRooms => 'Repeaters and Rooms'; + + @override + String get appSettings_clockSyncAfterLogin => 'Sync repeater clock on login'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'After a successful repeater login, send clock sync. Each repeater can still choose Default, On, or Off.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Focus the password field'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'When opening a repeater or room login, put the cursor in the password field if it is empty. Off leaves the dialog visible until you tap the field.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Reset repeater and room settings to defaults'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Restore the settings in this section to their defaults. Choices saved on individual repeaters stay as they are.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Repeater and room settings reset to defaults'; + @override String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; @@ -3478,7 +3507,16 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Automatically send \"clock sync\" after a successful login'; + 'Default follows Repeaters and Rooms in App Settings. On and Off apply only to this repeater.'; + + @override + String get repeater_clockSyncDefault => 'Default'; + + @override + String get repeater_clockSyncOn => 'On'; + + @override + String get repeater_clockSyncOff => 'Off'; @override String get repeater_statusTitle => 'Repeater Status'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 2acf9ddc..15f9a763 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1496,6 +1496,37 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Cuántas veces intentar iniciar sesión en un repetidor o servidor de sala antes de rendirse.'; + @override + String get appSettings_repeatersAndRooms => 'Repetidores y salas'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Sincronizar el reloj del repetidor al iniciar sesión'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Tras un inicio de sesión correcto en un repetidor se envía clock sync. Cada repetidor puede seguir eligiendo Predeterminado, Activado o Desactivado.'; + + @override + String get appSettings_loginPasswordAutofocus => + 'Enfocar el campo de contraseña'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Al abrir el inicio de sesión de un repetidor o una sala, el cursor va al campo de contraseña si está vacío. Desactivado deja el diálogo visible hasta que toques el campo.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Restablecer ajustes de repetidores y salas'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Restaura los ajustes de esta sección. Las elecciones guardadas en cada repetidor se quedan.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Ajustes de repetidores y salas restablecidos'; + @override String get appSettings_ipfsImageLinks => 'Configuración del proveedor IPFS'; @@ -3523,7 +3554,16 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Enviar automáticamente la función de \"sincronización de reloj\" después de un inicio de sesión exitoso.'; + 'Predeterminado sigue Repetidores y salas en Ajustes. Activado y Desactivado valen solo para este repetidor.'; + + @override + String get repeater_clockSyncDefault => 'Predeterminado'; + + @override + String get repeater_clockSyncOn => 'Activado'; + + @override + String get repeater_clockSyncOff => 'Desactivado'; @override String get repeater_statusTitle => 'Estado del Repetidor'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index c24ec931..c7d576a3 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1502,6 +1502,37 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Nombre d\'essais de connexion à un répéteur ou à un serveur de salon avant d\'abandonner.'; + @override + String get appSettings_repeatersAndRooms => 'Répéteurs et salons'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Synchroniser l\'horloge du répéteur à la connexion'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Après une connexion réussie à un répéteur, clock sync est envoyé. Chaque répéteur peut encore choisir Défaut, Activé ou Désactivé.'; + + @override + String get appSettings_loginPasswordAutofocus => + 'Placer le curseur dans le mot de passe'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'À l\'ouverture d\'une connexion répéteur ou salon, le curseur va dans le mot de passe s\'il est vide. Désactivé laisse la fenêtre visible jusqu\'à ce que vous touchiez le champ.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Réinitialiser les paramètres répéteurs et salons'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Restaure les paramètres de cette section. Les choix enregistrés sur chaque répéteur restent.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Paramètres répéteurs et salons réinitialisés'; + @override String get appSettings_ipfsImageLinks => 'Configuration du fournisseur IPFS'; @@ -3533,7 +3564,16 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Envoyer automatiquement une notification \"synchronisation de l\'heure\" après une connexion réussie.'; + 'Défaut suit Répéteurs et salons dans les paramètres. Activé et Désactivé ne concernent que ce répéteur.'; + + @override + String get repeater_clockSyncDefault => 'Défaut'; + + @override + String get repeater_clockSyncOn => 'Activé'; + + @override + String get repeater_clockSyncOff => 'Désactivé'; @override String get repeater_statusTitle => 'État du répéteur'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index c6954bba..6f619ce9 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1494,6 +1494,36 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Hányszor próbáljon bejelentkezni egy átjátszóra vagy room szerverre, mielőtt feladja.'; + @override + String get appSettings_repeatersAndRooms => 'Átjátszók és szobák'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Átjátszó órájának szinkronizálása belépéskor'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Sikeres átjátszó-belépés után clock sync megy ki. Minden átjátszó továbbra lehet Alapértelmezett, Be vagy Ki.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Jelszómező fókuszba'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Átjátszó vagy szoba belépésének megnyitásakor a kurzor az üres jelszómezőbe kerül. Kikapcsolva a párbeszéd látható marad, amíg meg nem érinti a mezőt.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Átjátszó- és szobabeállítások visszaállítása'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Visszaállítja a szakasz beállításait. Az egyes átjátszóknál mentett választás megmarad.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Átjátszó- és szobabeállítások visszaállítva'; + @override String get appSettings_ipfsImageLinks => 'IPFS-szolgáltató beállítása'; @@ -3526,7 +3556,16 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - '„Óraszinkronizálás” automatikus küldése sikeres bejelentkezés után'; + 'Az Alapértelmezett az alkalmazás Átjátszók és szobák beállítását követi. A Be és a Ki csak erre az átjátszóra vonatkozik.'; + + @override + String get repeater_clockSyncDefault => 'Alapért.'; + + @override + String get repeater_clockSyncOn => 'Be'; + + @override + String get repeater_clockSyncOff => 'Ki'; @override String get repeater_statusTitle => 'Átjátszó állapota'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index e3e38cca..5c53e2e8 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1500,6 +1500,36 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Quante volte provare l\'accesso a un ripetitore o a un server room prima di rinunciare.'; + @override + String get appSettings_repeatersAndRooms => 'Ripetitori e stanze'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Sincronizza l\'orologio del ripetitore all\'accesso'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Dopo un accesso riuscito a un ripetitore viene inviato clock sync. Ogni ripetitore può ancora scegliere Predefinito, Attivo o Disattivo.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Attiva il campo password'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'All\'apertura dell\'accesso a un ripetitore o a una stanza, il cursore va nel campo password se è vuoto. Disattivo lascia visibile la finestra finché non tocchi il campo.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Reimposta le impostazioni di ripetitori e stanze'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Ripristina le impostazioni di questa sezione. Le scelte salvate sui singoli ripetitori restano.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Impostazioni di ripetitori e stanze reimpostate'; + @override String get appSettings_ipfsImageLinks => 'Configurazione del provider IPFS'; @@ -3528,7 +3558,16 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Invia automaticamente il comando \"sincronizzazione dell\'orologio\" dopo un login riuscito.'; + 'Predefinito segue Ripetitori e stanze nelle impostazioni. Attivo e Disattivo valgono solo per questo ripetitore.'; + + @override + String get repeater_clockSyncDefault => 'Predefinito'; + + @override + String get repeater_clockSyncOn => 'Attivo'; + + @override + String get repeater_clockSyncOff => 'Disattivo'; @override String get repeater_statusTitle => 'Stato del ripetitore'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index f9c76c8b..9492aa9c 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1424,6 +1424,33 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'リピータまたはルームサーバーへのログインをあきらめるまでの回数です。'; + @override + String get appSettings_repeatersAndRooms => 'リピーターとルーム'; + + @override + String get appSettings_clockSyncAfterLogin => 'ログイン時にリピーターの時刻を同期'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'リピーターへのログインに成功すると clock sync を送ります。各リピーターは「既定」「オン」「オフ」を選べます。'; + + @override + String get appSettings_loginPasswordAutofocus => 'パスワード欄にフォーカス'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'リピーターまたはルームのログインを開いたとき、パスワードが空ならその欄にカーソルを置きます。オフでは欄をタップするまで画面全体が見えます。'; + + @override + String get appSettings_resetRepeaterRoomSettings => 'リピーターとルームの設定をリセット'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'このセクションの設定を戻します。各リピーターに保存した選択はそのままです。'; + + @override + String get appSettings_repeaterRoomSettingsReset => 'リピーターとルームの設定をリセットしました'; + @override String get appSettings_ipfsImageLinks => 'IPFSプロバイダー設定'; @@ -3383,7 +3410,17 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_clockSyncAfterLogin => 'ログイン後に時刻を同期'; @override - String get repeater_clockSyncAfterLoginSubtitle => 'ログイン成功時に自動で時刻同期を送信します'; + String get repeater_clockSyncAfterLoginSubtitle => + '「既定」はアプリ設定の「リピーターとルーム」に従います。「オン」と「オフ」はこのリピーターだけです。'; + + @override + String get repeater_clockSyncDefault => '既定'; + + @override + String get repeater_clockSyncOn => 'オン'; + + @override + String get repeater_clockSyncOff => 'オフ'; @override String get repeater_statusTitle => '再送ステータス'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 9a6c10bc..24790944 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1427,6 +1427,33 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => '중계기나 룸 서버 로그인을 포기하기 전까지의 시도 횟수입니다.'; + @override + String get appSettings_repeatersAndRooms => '리피터와 방'; + + @override + String get appSettings_clockSyncAfterLogin => '로그인 시 리피터 시계 동기화'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + '리피터 로그인에 성공하면 clock sync를 보냅니다. 각 리피터는 기본, 켜기, 끄기를 고를 수 있습니다.'; + + @override + String get appSettings_loginPasswordAutofocus => '비밀번호 칸에 포커스'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + '리피터나 방 로그인을 열 때 비밀번호가 비어 있으면 그 칸에 커서를 둡니다. 끄면 칸을 누를 때까지 대화상자가 보입니다.'; + + @override + String get appSettings_resetRepeaterRoomSettings => '리피터와 방 설정을 기본값으로'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + '이 섹션의 설정을 되돌립니다. 각 리피터에 저장한 선택은 그대로입니다.'; + + @override + String get appSettings_repeaterRoomSettingsReset => '리피터와 방 설정을 되돌렸습니다'; + @override String get appSettings_ipfsImageLinks => 'IPFS 제공자 설정'; @@ -3384,7 +3411,16 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - '성공적인 로그인 후, 자동으로 \"시간 동기화\"를 전송합니다.'; + '기본은 앱 설정의 리피터와 방을 따릅니다. 켜기와 끄기는 이 리피터에만 적용됩니다.'; + + @override + String get repeater_clockSyncDefault => '기본'; + + @override + String get repeater_clockSyncOn => '켜기'; + + @override + String get repeater_clockSyncOff => '끄기'; @override String get repeater_statusTitle => '리피터 상태'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index d1c1ace3..87c5611f 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1492,6 +1492,36 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Hoe vaak wordt geprobeerd in te loggen op een repeater of roomserver voordat het stopt.'; + @override + String get appSettings_repeatersAndRooms => 'Repeaters en rooms'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Repeaterklok synchroniseren bij aanmelden'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Na een geslaagde repeater-aanmelding wordt clock sync gestuurd. Elke repeater kan nog Standaard, Aan of Uit kiezen.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Wachtwoordveld focussen'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Bij het openen van een repeater- of room-aanmelding staat de cursor in het lege wachtwoordveld. Uit laat het venster zichtbaar tot je het veld aantikt.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Repeater- en roominstellingen resetten'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Zet de instellingen in deze sectie terug. Keuzes die per repeater zijn opgeslagen blijven staan.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Repeater- en roominstellingen gereset'; + @override String get appSettings_ipfsImageLinks => 'IPFS-providerconfiguratie'; @@ -3510,7 +3540,16 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Automatisch een \"klok synchroniseren\" bericht versturen na een succesvolle inlog.'; + 'Standaard volgt Repeaters en rooms in de app-instellingen. Aan en Uit gelden alleen voor deze repeater.'; + + @override + String get repeater_clockSyncDefault => 'Standaard'; + + @override + String get repeater_clockSyncOn => 'Aan'; + + @override + String get repeater_clockSyncOff => 'Uit'; @override String get repeater_statusTitle => 'Status repeater'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 51954827..df1aaf9d 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1507,6 +1507,36 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Ile razy próbować logowania do przemiennika lub serwera room, zanim aplikacja zrezygnuje.'; + @override + String get appSettings_repeatersAndRooms => 'Przemienniki i pokoje'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Synchronizuj zegar przemiennika przy logowaniu'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Po udanym logowaniu do przemiennika wysyłane jest clock sync. Każdy przemiennik może nadal wybrać Domyślnie, Wł. lub Wył.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Uaktywnij pole hasła'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Przy otwieraniu logowania do przemiennika lub pokoju kursor trafia w puste pole hasła. Wyłączenie zostawia okno widoczne, aż dotkniesz pola.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Resetuj ustawienia przemienników i pokoi'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Przywraca ustawienia w tej sekcji. Wybory zapisane przy poszczególnych przemiennikach zostają.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Ustawienia przemienników i pokoi zresetowane'; + @override String get appSettings_ipfsImageLinks => 'Konfiguracja dostawcy IPFS'; @@ -3557,7 +3587,16 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Automatycznie wysyłaj powiadomienie \"synchronizacja zegara\" po pomyślnym zalogowaniu.'; + 'Domyślnie podąża za Przemienniki i pokoje w ustawieniach. Wł. i Wył. dotyczą tylko tego przemiennika.'; + + @override + String get repeater_clockSyncDefault => 'Domyślnie'; + + @override + String get repeater_clockSyncOn => 'Wł.'; + + @override + String get repeater_clockSyncOff => 'Wył.'; @override String get repeater_statusTitle => 'Status przekaźnika'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 1b367341..fa9d2307 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1499,6 +1499,36 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Quantas vezes tentar entrar em um repetidor ou servidor de sala antes de desistir.'; + @override + String get appSettings_repeatersAndRooms => 'Repetidores e salas'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Sincronizar o relógio do repetidor ao entrar'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Depois de entrar em um repetidor, clock sync é enviado. Cada repetidor ainda pode escolher Padrão, Ligado ou Desligado.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Focar o campo de senha'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Ao abrir o login de um repetidor ou sala, o cursor vai para a senha se ela estiver vazia. Desligado deixa o diálogo visível até você tocar no campo.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Redefinir configurações de repetidores e salas'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Restaura as configurações desta seção. As escolhas salvas em cada repetidor permanecem.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Configurações de repetidores e salas redefinidas'; + @override String get appSettings_ipfsImageLinks => 'Configuração do provedor IPFS'; @@ -3523,7 +3553,16 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Enviar automaticamente a sincronização do \"relógio\" após um login bem-sucedido.'; + 'Padrão segue Repetidores e salas nas configurações. Ligado e Desligado valem só para este repetidor.'; + + @override + String get repeater_clockSyncDefault => 'Padrão'; + + @override + String get repeater_clockSyncOn => 'Ligado'; + + @override + String get repeater_clockSyncOff => 'Desligado'; @override String get repeater_statusTitle => 'Status do Repetidor'; @@ -9079,6 +9118,37 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { String get appSettings_loginAttemptsSubtitle => 'Quantas vezes tentar iniciar sessão num repetidor ou servidor de sala antes de desistir.'; + @override + String get appSettings_repeatersAndRooms => 'Repetidores e salas'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Sincronizar o relógio do repetidor ao iniciar sessão'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Depois de iniciar sessão num repetidor, é enviado clock sync. Cada repetidor pode continuar a escolher Predefinição, Ligado ou Desligado.'; + + @override + String get appSettings_loginPasswordAutofocus => + 'Focar o campo da palavra-passe'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Ao abrir o início de sessão de um repetidor ou sala, o cursor vai para a palavra-passe se estiver vazia. Desligado deixa o diálogo visível até tocar no campo.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Repor definições de repetidores e salas'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Repõe as definições desta secção. As escolhas guardadas em cada repetidor mantêm-se.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Definições de repetidores e salas repostas'; + @override String get appSettings_ipfsImageLinks => 'Configuração do fornecedor IPFS'; @@ -11073,7 +11143,16 @@ class AppLocalizationsPtPt extends AppLocalizationsPt { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Enviar automaticamente \"clock sync\" após um login bem-sucedido'; + 'Predefinição segue Repetidores e salas nas definições. Ligado e Desligado valem só para este repetidor.'; + + @override + String get repeater_clockSyncDefault => 'Predefinição'; + + @override + String get repeater_clockSyncOn => 'Ligado'; + + @override + String get repeater_clockSyncOff => 'Desligado'; @override String get repeater_statusTitle => 'Estado do repetidor'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 3d4111b2..ef0d7fcc 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1499,6 +1499,36 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Сколько раз пытаться войти на ретранслятор или room-сервер, прежде чем сдаться.'; + @override + String get appSettings_repeatersAndRooms => 'Ретрансляторы и комнаты'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Синхронизировать часы ретранслятора при входе'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'После успешного входа на ретранслятор отправляется clock sync. Для каждого ретранслятора по-прежнему можно выбрать По умолчанию, Вкл. или Выкл.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Фокус на поле пароля'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'При открытии входа на ретранслятор или в комнату курсор ставится в пустое поле пароля. Выключено оставляет окно видимым, пока вы не нажмёте на поле.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Сбросить настройки ретрансляторов и комнат'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Возвращает настройки этого раздела. Выбор, сохранённый для отдельных ретрансляторов, остаётся.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Настройки ретрансляторов и комнат сброшены'; + @override String get appSettings_ipfsImageLinks => 'Настройка провайдера IPFS'; @@ -3533,7 +3563,16 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Автоматически отправлять сообщение \"синхронизация времени\" после успешной авторизации.'; + '«По умолчанию» следует разделу «Ретрансляторы и комнаты» в настройках. «Вкл.» и «Выкл.» только для этого ретранслятора.'; + + @override + String get repeater_clockSyncDefault => 'По умолчанию'; + + @override + String get repeater_clockSyncOn => 'Вкл.'; + + @override + String get repeater_clockSyncOff => 'Выкл.'; @override String get repeater_statusTitle => 'Статус репитера'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 932b79d4..a116fdfd 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1493,6 +1493,36 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Koľkokrát sa skúsi prihlásenie k opakovaču alebo room serveru, kým sa to vzdá.'; + @override + String get appSettings_repeatersAndRooms => 'Opakovače a miestnosti'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Synchronizovať hodiny opakovača pri prihlásení'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Po úspešnom prihlásení k opakovaču sa odošle clock sync. Každý opakovač môže ďalej zvoliť Predvolené, Zapnuté alebo Vypnuté.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Zamerať pole hesla'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Pri otvorení prihlásenia k opakovaču alebo miestnosti je kurzor v prázdnom poli hesla. Vypnuté nechá okno viditeľné, kým na pole neťuknete.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Obnoviť nastavenia opakovačov a miestností'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Obnoví nastavenia v tejto časti. Voľby uložené pri jednotlivých opakovačoch ostanú.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Nastavenia opakovačov a miestností obnovené'; + @override String get appSettings_ipfsImageLinks => 'Konfigurácia poskytovateľa IPFS'; @@ -3526,7 +3556,16 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Po úspešnom prihlásení automaticky odoslať „synchronizáciu hodín“'; + 'Predvolené sleduje Opakovače a miestnosti v nastaveniach. Zapnuté a Vypnuté platia len pre tento opakovač.'; + + @override + String get repeater_clockSyncDefault => 'Predvolené'; + + @override + String get repeater_clockSyncOn => 'Zapnuté'; + + @override + String get repeater_clockSyncOff => 'Vypnuté'; @override String get repeater_statusTitle => 'Stav opakovača'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 40527806..60ae9226 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1491,6 +1491,36 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Kolikokrat se poskusi prijava v ponavljalnik ali room strežnik, preden obupa.'; + @override + String get appSettings_repeatersAndRooms => 'Repetitorji in sobe'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Sinhroniziraj uro repetitorja ob prijavi'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Po uspešni prijavi v repetitor se pošlje clock sync. Vsak repetitor lahko še vedno izbere Privzeto, Vklop ali Izklop.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Fokus na polje gesla'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Ob odprtju prijave v repetitor ali sobo gre kazalec v prazno polje gesla. Izklop pusti okno vidno, dokler se ne dotaknete polja.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Ponastavi nastavitve repetitorjev in sob'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Obnovi nastavitve v tem razdelku. Izbire, shranjene pri posameznih repetitorjih, ostanejo.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Nastavitve repetitorjev in sob so ponastavljene'; + @override String get appSettings_ipfsImageLinks => 'Konfiguracija ponudnika IPFS'; @@ -3523,7 +3553,16 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Po uspešni prijavi samodejno pošlji »sinhronizacijo ure«'; + 'Privzeto sledi Repetitorjem in sobam v nastavitvah. Vklop in Izklop veljata samo za ta repetitor.'; + + @override + String get repeater_clockSyncDefault => 'Privzeto'; + + @override + String get repeater_clockSyncOn => 'Vklop'; + + @override + String get repeater_clockSyncOff => 'Izklop'; @override String get repeater_statusTitle => 'Status repetitora'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index fae3713e..d104df63 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1480,6 +1480,36 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Hur många gånger inloggning till en repeater eller room-server provas innan den ger upp.'; + @override + String get appSettings_repeatersAndRooms => 'Repeatrar och rum'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Synka repeaterklockan vid inloggning'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Efter en lyckad repeaterinloggning skickas clock sync. Varje repeater kan fortfarande välja Standard, På eller Av.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Fokusera lösenordsfältet'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'När en repeater- eller ruminloggning öppnas hamnar markören i lösenordsfältet om det är tomt. Av lämnar dialogrutan synlig tills du trycker på fältet.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Återställ repeater- och ruminställningar'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Återställer inställningarna i det här avsnittet. Val som sparats på enskilda repeatrar blir kvar.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Repeater- och ruminställningar återställda'; + @override String get appSettings_ipfsImageLinks => 'Konfiguration av IPFS-leverantör'; @@ -3499,7 +3529,16 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Automatiskt skicka \"klocksynkronisering\" efter en lyckad inloggning.'; + 'Standard följer Repeatrar och rum i appinställningarna. På och Av gäller bara den här repeatern.'; + + @override + String get repeater_clockSyncDefault => 'Standard'; + + @override + String get repeater_clockSyncOn => 'På'; + + @override + String get repeater_clockSyncOff => 'Av'; @override String get repeater_statusTitle => 'Repeaterstatus'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 32159140..06c13718 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1493,6 +1493,36 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_loginAttemptsSubtitle => 'Скільки разів пробувати вхід до ретранслятора або room-сервера, перш ніж здатися.'; + @override + String get appSettings_repeatersAndRooms => 'Ретранслятори та кімнати'; + + @override + String get appSettings_clockSyncAfterLogin => + 'Синхронізувати годинник ретранслятора під час входу'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + 'Після успішного входу на ретранслятор надсилається clock sync. Для кожного ретранслятора можна лишити Типово, Увімк. або Вимк.'; + + @override + String get appSettings_loginPasswordAutofocus => 'Фокус на полі пароля'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + 'Коли відкривається вхід на ретранслятор або в кімнату, курсор стає в порожнє поле пароля. Вимкнено лишає вікно видимим, доки ви не торкнетеся поля.'; + + @override + String get appSettings_resetRepeaterRoomSettings => + 'Скинути налаштування ретрансляторів і кімнат'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + 'Відновлює налаштування цього розділу. Вибір, збережений для окремих ретрансляторів, лишається.'; + + @override + String get appSettings_repeaterRoomSettingsReset => + 'Налаштування ретрансляторів і кімнат скинуто'; + @override String get appSettings_ipfsImageLinks => 'Налаштування IPFS-провайдера'; @@ -3531,7 +3561,16 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_clockSyncAfterLoginSubtitle => - 'Автоматично надсилати повідомлення \"синхронізація годин\" після успішного входу.'; + '«Типово» йде за розділом «Ретранслятори та кімнати» в налаштуваннях. «Увімк.» і «Вимк.» лише для цього ретранслятора.'; + + @override + String get repeater_clockSyncDefault => 'Типово'; + + @override + String get repeater_clockSyncOn => 'Увімк.'; + + @override + String get repeater_clockSyncOff => 'Вимк.'; @override String get repeater_statusTitle => 'Статус ретранслятора'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a1d5c7f1..1ff13a99 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1400,6 +1400,33 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_loginAttemptsSubtitle => '登录中继或房间服务器时,放弃前的尝试次数。'; + @override + String get appSettings_repeatersAndRooms => '中继和房间'; + + @override + String get appSettings_clockSyncAfterLogin => '登录时同步中继时钟'; + + @override + String get appSettings_clockSyncAfterLoginSubtitle => + '成功登录中继后会发送 clock sync。每个中继仍可选择默认、开或关。'; + + @override + String get appSettings_loginPasswordAutofocus => '聚焦密码框'; + + @override + String get appSettings_loginPasswordAutofocusSubtitle => + '打开中继或房间登录时,如果密码为空,光标会进入密码框。关闭后,在你点按该框之前对话框保持可见。'; + + @override + String get appSettings_resetRepeaterRoomSettings => '将中继和房间设置重置为默认'; + + @override + String get appSettings_resetRepeaterRoomSettingsSubtitle => + '恢复这一节的设置。保存在各个中继上的选择保持不变。'; + + @override + String get appSettings_repeaterRoomSettingsReset => '中继和房间设置已重置'; + @override String get appSettings_ipfsImageLinks => 'IPFS 提供商配置'; @@ -3333,7 +3360,17 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_clockSyncAfterLogin => '登录后,自动同步时钟'; @override - String get repeater_clockSyncAfterLoginSubtitle => '在成功登录后,自动发送“时钟同步”指令。'; + String get repeater_clockSyncAfterLoginSubtitle => + '默认跟随应用设置里的“中继和房间”。开和关只作用于这个中继。'; + + @override + String get repeater_clockSyncDefault => '默认'; + + @override + String get repeater_clockSyncOn => '开'; + + @override + String get repeater_clockSyncOff => '关'; @override String get repeater_statusTitle => '转发节点状态'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 5a7dbd73..a26e107a 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -2430,7 +2430,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Automatisch een \"klok synchroniseren\" bericht versturen na een succesvolle inlog.", + "repeater_clockSyncAfterLoginSubtitle": "Standaard volgt Repeaters en rooms in de app-instellingen. Aan en Uit gelden alleen voor deze repeater.", "repeater_clockSyncAfterLogin": "Na het inloggen, klok synchroniseren", "repeater_guestTools": "Gastenfuncties", "repeater_roleAdmin": "ADMIN", @@ -3683,5 +3683,16 @@ "appSettings_floodRetries": "Flood-pogingen: {count}", "appSettings_floodRetriesSubtitle": "Hoe vaak Flood wordt gebruikt. Flood kost meer zendtijd. Met rotatie aan volgen ze op de directe pogingen.", "appSettings_loginAttempts": "Inlogpogingen: {count}", - "appSettings_loginAttemptsSubtitle": "Hoe vaak wordt geprobeerd in te loggen op een repeater of roomserver voordat het stopt." + "appSettings_loginAttemptsSubtitle": "Hoe vaak wordt geprobeerd in te loggen op een repeater of roomserver voordat het stopt.", + "appSettings_repeatersAndRooms": "Repeaters en rooms", + "appSettings_clockSyncAfterLogin": "Repeaterklok synchroniseren bij aanmelden", + "appSettings_clockSyncAfterLoginSubtitle": "Na een geslaagde repeater-aanmelding wordt clock sync gestuurd. Elke repeater kan nog Standaard, Aan of Uit kiezen.", + "appSettings_loginPasswordAutofocus": "Wachtwoordveld focussen", + "appSettings_loginPasswordAutofocusSubtitle": "Bij het openen van een repeater- of room-aanmelding staat de cursor in het lege wachtwoordveld. Uit laat het venster zichtbaar tot je het veld aantikt.", + "appSettings_resetRepeaterRoomSettings": "Repeater- en roominstellingen resetten", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Zet de instellingen in deze sectie terug. Keuzes die per repeater zijn opgeslagen blijven staan.", + "appSettings_repeaterRoomSettingsReset": "Repeater- en roominstellingen gereset", + "repeater_clockSyncDefault": "Standaard", + "repeater_clockSyncOn": "Aan", + "repeater_clockSyncOff": "Uit" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index f0abd6ed..ef8a0f1b 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -2416,7 +2416,7 @@ "repeater_cliQuickClockSync": "Synchronizacja zegara", "repeater_cliQuickDiscovery": "Odkryj Sąsiadów", "repeater_clockSyncAfterLogin": "Synchronizacja zegara po zalogowaniu", - "repeater_clockSyncAfterLoginSubtitle": "Automatycznie wysyłaj powiadomienie \"synchronizacja zegara\" po pomyślnym zalogowaniu.", + "repeater_clockSyncAfterLoginSubtitle": "Domyślnie podąża za Przemienniki i pokoje w ustawieniach. Wł. i Wył. dotyczą tylko tego przemiennika.", "chat_sendMessage": "Wyślij wiadomość", "repeater_guestTools": "Narzędzia dla gości", "repeater_guest": "Informacje dotyczące urządzenia powtarzającego", @@ -4021,5 +4021,16 @@ "appSettings_floodRetries": "Próby Flood: {count}", "appSettings_floodRetriesSubtitle": "Ile razy użyć Flood. Flood zużywa więcej czasu antenowego. Przy włączonej rotacji następują po próbach bezpośrednich.", "appSettings_loginAttempts": "Próby logowania: {count}", - "appSettings_loginAttemptsSubtitle": "Ile razy próbować logowania do przemiennika lub serwera room, zanim aplikacja zrezygnuje." + "appSettings_loginAttemptsSubtitle": "Ile razy próbować logowania do przemiennika lub serwera room, zanim aplikacja zrezygnuje.", + "appSettings_repeatersAndRooms": "Przemienniki i pokoje", + "appSettings_clockSyncAfterLogin": "Synchronizuj zegar przemiennika przy logowaniu", + "appSettings_clockSyncAfterLoginSubtitle": "Po udanym logowaniu do przemiennika wysyłane jest clock sync. Każdy przemiennik może nadal wybrać Domyślnie, Wł. lub Wył.", + "appSettings_loginPasswordAutofocus": "Uaktywnij pole hasła", + "appSettings_loginPasswordAutofocusSubtitle": "Przy otwieraniu logowania do przemiennika lub pokoju kursor trafia w puste pole hasła. Wyłączenie zostawia okno widoczne, aż dotkniesz pola.", + "appSettings_resetRepeaterRoomSettings": "Resetuj ustawienia przemienników i pokoi", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Przywraca ustawienia w tej sekcji. Wybory zapisane przy poszczególnych przemiennikach zostają.", + "appSettings_repeaterRoomSettingsReset": "Ustawienia przemienników i pokoi zresetowane", + "repeater_clockSyncDefault": "Domyślnie", + "repeater_clockSyncOn": "Wł.", + "repeater_clockSyncOff": "Wył." } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 9b7c454a..cc329399 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -2299,7 +2299,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Enviar automaticamente a sincronização do \"relógio\" após um login bem-sucedido.", + "repeater_clockSyncAfterLoginSubtitle": "Padrão segue Repetidores e salas nas configurações. Ligado e Desligado valem só para este repetidor.", "repeater_clockSyncAfterLogin": "Sincronização do relógio após o login", "room_guest": "Informações do Servidor", "chat_sendMessage": "Enviar mensagem", @@ -3834,5 +3834,16 @@ "appSettings_floodRetries": "Tentativas Flood: {count}", "appSettings_floodRetriesSubtitle": "Quantas vezes usar Flood. Flood usa mais tempo de ar. Com a rotação ligada, vêm depois das tentativas diretas.", "appSettings_loginAttempts": "Tentativas de login: {count}", - "appSettings_loginAttemptsSubtitle": "Quantas vezes tentar entrar em um repetidor ou servidor de sala antes de desistir." + "appSettings_loginAttemptsSubtitle": "Quantas vezes tentar entrar em um repetidor ou servidor de sala antes de desistir.", + "appSettings_repeatersAndRooms": "Repetidores e salas", + "appSettings_clockSyncAfterLogin": "Sincronizar o relógio do repetidor ao entrar", + "appSettings_clockSyncAfterLoginSubtitle": "Depois de entrar em um repetidor, clock sync é enviado. Cada repetidor ainda pode escolher Padrão, Ligado ou Desligado.", + "appSettings_loginPasswordAutofocus": "Focar o campo de senha", + "appSettings_loginPasswordAutofocusSubtitle": "Ao abrir o login de um repetidor ou sala, o cursor vai para a senha se ela estiver vazia. Desligado deixa o diálogo visível até você tocar no campo.", + "appSettings_resetRepeaterRoomSettings": "Redefinir configurações de repetidores e salas", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Restaura as configurações desta seção. As escolhas salvas em cada repetidor permanecem.", + "appSettings_repeaterRoomSettingsReset": "Configurações de repetidores e salas redefinidas", + "repeater_clockSyncDefault": "Padrão", + "repeater_clockSyncOn": "Ligado", + "repeater_clockSyncOff": "Desligado" } diff --git a/lib/l10n/app_pt_PT.arb b/lib/l10n/app_pt_PT.arb index 5b326773..5695247a 100644 --- a/lib/l10n/app_pt_PT.arb +++ b/lib/l10n/app_pt_PT.arb @@ -989,7 +989,7 @@ "repeater_settings": "Definições", "repeater_settingsSubtitle": "Configurar parâmetros do repetidor", "repeater_clockSyncAfterLogin": "Sincronizar relógio após login", - "repeater_clockSyncAfterLoginSubtitle": "Enviar automaticamente \"clock sync\" após um login bem-sucedido", + "repeater_clockSyncAfterLoginSubtitle": "Predefinição segue Repetidores e salas nas definições. Ligado e Desligado valem só para este repetidor.", "repeater_statusTitle": "Estado do repetidor", "repeater_routingMode": "Modo de encaminhamento", "repeater_refresh": "Atualizar", @@ -2061,5 +2061,16 @@ "appSettings_floodRetries": "Tentativas Flood: {count}", "appSettings_floodRetriesSubtitle": "Quantas vezes usar Flood. Flood usa mais tempo de ar. Com a rotação ligada, vêm a seguir às tentativas diretas.", "appSettings_loginAttempts": "Tentativas de início de sessão: {count}", - "appSettings_loginAttemptsSubtitle": "Quantas vezes tentar iniciar sessão num repetidor ou servidor de sala antes de desistir." + "appSettings_loginAttemptsSubtitle": "Quantas vezes tentar iniciar sessão num repetidor ou servidor de sala antes de desistir.", + "appSettings_repeatersAndRooms": "Repetidores e salas", + "appSettings_clockSyncAfterLogin": "Sincronizar o relógio do repetidor ao iniciar sessão", + "appSettings_clockSyncAfterLoginSubtitle": "Depois de iniciar sessão num repetidor, é enviado clock sync. Cada repetidor pode continuar a escolher Predefinição, Ligado ou Desligado.", + "appSettings_loginPasswordAutofocus": "Focar o campo da palavra-passe", + "appSettings_loginPasswordAutofocusSubtitle": "Ao abrir o início de sessão de um repetidor ou sala, o cursor vai para a palavra-passe se estiver vazia. Desligado deixa o diálogo visível até tocar no campo.", + "appSettings_resetRepeaterRoomSettings": "Repor definições de repetidores e salas", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Repõe as definições desta secção. As escolhas guardadas em cada repetidor mantêm-se.", + "appSettings_repeaterRoomSettingsReset": "Definições de repetidores e salas repostas", + "repeater_clockSyncDefault": "Predefinição", + "repeater_clockSyncOn": "Ligado", + "repeater_clockSyncOff": "Desligado" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 2bf49032..5cbed144 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -1550,7 +1550,7 @@ "repeater_cliQuickDiscovery": "Обнаружить Соседей", "repeater_cliQuickClockSync": "Синхронизация часов", "repeater_clockSyncAfterLogin": "Синхронизация часов после входа в систему", - "repeater_clockSyncAfterLoginSubtitle": "Автоматически отправлять сообщение \"синхронизация времени\" после успешной авторизации.", + "repeater_clockSyncAfterLoginSubtitle": "«По умолчанию» следует разделу «Ретрансляторы и комнаты» в настройках. «Вкл.» и «Выкл.» только для этого ретранслятора.", "chat_sendMessage": "Отправить сообщение", "repeater_guest": "Информация о ретрансляторе", "room_guest": "Информация о сервере", @@ -3079,5 +3079,16 @@ "appSettings_floodRetries": "Попытки Flood: {count}", "appSettings_floodRetriesSubtitle": "Сколько раз использовать Flood. Flood занимает больше эфирного времени. При включённой ротации они идут после прямых попыток.", "appSettings_loginAttempts": "Попытки входа: {count}", - "appSettings_loginAttemptsSubtitle": "Сколько раз пытаться войти на ретранслятор или room-сервер, прежде чем сдаться." + "appSettings_loginAttemptsSubtitle": "Сколько раз пытаться войти на ретранслятор или room-сервер, прежде чем сдаться.", + "appSettings_repeatersAndRooms": "Ретрансляторы и комнаты", + "appSettings_clockSyncAfterLogin": "Синхронизировать часы ретранслятора при входе", + "appSettings_clockSyncAfterLoginSubtitle": "После успешного входа на ретранслятор отправляется clock sync. Для каждого ретранслятора по-прежнему можно выбрать По умолчанию, Вкл. или Выкл.", + "appSettings_loginPasswordAutofocus": "Фокус на поле пароля", + "appSettings_loginPasswordAutofocusSubtitle": "При открытии входа на ретранслятор или в комнату курсор ставится в пустое поле пароля. Выключено оставляет окно видимым, пока вы не нажмёте на поле.", + "appSettings_resetRepeaterRoomSettings": "Сбросить настройки ретрансляторов и комнат", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Возвращает настройки этого раздела. Выбор, сохранённый для отдельных ретрансляторов, остаётся.", + "appSettings_repeaterRoomSettingsReset": "Настройки ретрансляторов и комнат сброшены", + "repeater_clockSyncDefault": "По умолчанию", + "repeater_clockSyncOn": "Вкл.", + "repeater_clockSyncOff": "Выкл." } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index c4c5e618..e1c5545f 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -2385,7 +2385,7 @@ "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, "repeater_clockSyncAfterLogin": "Synchronizácia hodín po prihlásení", - "repeater_clockSyncAfterLoginSubtitle": "Po úspešnom prihlásení automaticky odoslať „synchronizáciu hodín“", + "repeater_clockSyncAfterLoginSubtitle": "Predvolené sleduje Opakovače a miestnosti v nastaveniach. Zapnuté a Vypnuté platia len pre tento opakovač.", "chat_sendMessage": "Odoslať správu", "repeater_guest": "Informácie o opakovači", "room_guest": "Informácie o serveri", @@ -3835,5 +3835,16 @@ "appSettings_floodRetries": "Pokusy Flood: {count}", "appSettings_floodRetriesSubtitle": "Koľkokrát sa použije Flood. Flood zaberie viac vysielacieho času. Pri zapnutom striedaní nasledujú po priamych pokusoch.", "appSettings_loginAttempts": "Pokusy o prihlásenie: {count}", - "appSettings_loginAttemptsSubtitle": "Koľkokrát sa skúsi prihlásenie k opakovaču alebo room serveru, kým sa to vzdá." + "appSettings_loginAttemptsSubtitle": "Koľkokrát sa skúsi prihlásenie k opakovaču alebo room serveru, kým sa to vzdá.", + "appSettings_repeatersAndRooms": "Opakovače a miestnosti", + "appSettings_clockSyncAfterLogin": "Synchronizovať hodiny opakovača pri prihlásení", + "appSettings_clockSyncAfterLoginSubtitle": "Po úspešnom prihlásení k opakovaču sa odošle clock sync. Každý opakovač môže ďalej zvoliť Predvolené, Zapnuté alebo Vypnuté.", + "appSettings_loginPasswordAutofocus": "Zamerať pole hesla", + "appSettings_loginPasswordAutofocusSubtitle": "Pri otvorení prihlásenia k opakovaču alebo miestnosti je kurzor v prázdnom poli hesla. Vypnuté nechá okno viditeľné, kým na pole neťuknete.", + "appSettings_resetRepeaterRoomSettings": "Obnoviť nastavenia opakovačov a miestností", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Obnoví nastavenia v tejto časti. Voľby uložené pri jednotlivých opakovačoch ostanú.", + "appSettings_repeaterRoomSettingsReset": "Nastavenia opakovačov a miestností obnovené", + "repeater_clockSyncDefault": "Predvolené", + "repeater_clockSyncOn": "Zapnuté", + "repeater_clockSyncOff": "Vypnuté" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 53088560..2ec931b7 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -2291,7 +2291,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Po uspešni prijavi samodejno pošlji »sinhronizacijo ure«", + "repeater_clockSyncAfterLoginSubtitle": "Privzeto sledi Repetitorjem in sobam v nastavitvah. Vklop in Izklop veljata samo za ta repetitor.", "repeater_clockSyncAfterLogin": "Sinhronizacija ure po prijavi", "repeater_guest": "Informacije o repetitorju", "chat_sendMessage": "Pošlji sporočilo", @@ -3989,5 +3989,16 @@ "appSettings_floodRetries": "Poskusi Flood: {count}", "appSettings_floodRetriesSubtitle": "Kolikokrat se uporabi Flood. Flood porabi več oddajnega časa. Ob vklopljenem kroženju sledijo neposrednim poskusom.", "appSettings_loginAttempts": "Poskusi prijave: {count}", - "appSettings_loginAttemptsSubtitle": "Kolikokrat se poskusi prijava v ponavljalnik ali room strežnik, preden obupa." + "appSettings_loginAttemptsSubtitle": "Kolikokrat se poskusi prijava v ponavljalnik ali room strežnik, preden obupa.", + "appSettings_repeatersAndRooms": "Repetitorji in sobe", + "appSettings_clockSyncAfterLogin": "Sinhroniziraj uro repetitorja ob prijavi", + "appSettings_clockSyncAfterLoginSubtitle": "Po uspešni prijavi v repetitor se pošlje clock sync. Vsak repetitor lahko še vedno izbere Privzeto, Vklop ali Izklop.", + "appSettings_loginPasswordAutofocus": "Fokus na polje gesla", + "appSettings_loginPasswordAutofocusSubtitle": "Ob odprtju prijave v repetitor ali sobo gre kazalec v prazno polje gesla. Izklop pusti okno vidno, dokler se ne dotaknete polja.", + "appSettings_resetRepeaterRoomSettings": "Ponastavi nastavitve repetitorjev in sob", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Obnovi nastavitve v tem razdelku. Izbire, shranjene pri posameznih repetitorjih, ostanejo.", + "appSettings_repeaterRoomSettingsReset": "Nastavitve repetitorjev in sob so ponastavljene", + "repeater_clockSyncDefault": "Privzeto", + "repeater_clockSyncOn": "Vklop", + "repeater_clockSyncOff": "Izklop" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 64039433..9dd5deda 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -2287,7 +2287,7 @@ "scanner_linuxPairingHidePin": "Dölj PIN", "repeater_cliQuickDiscovery": "Upptäck grannar", "repeater_cliQuickClockSync": "Synkronisera klocka", - "repeater_clockSyncAfterLoginSubtitle": "Automatiskt skicka \"klocksynkronisering\" efter en lyckad inloggning.", + "repeater_clockSyncAfterLoginSubtitle": "Standard följer Repeatrar och rum i appinställningarna. På och Av gäller bara den här repeatern.", "repeater_clockSyncAfterLogin": "Synkronisera klockan efter inloggning", "repeater_guest": "Repeaterinformation", "chat_sendMessage": "Skicka meddelande", @@ -3829,5 +3829,16 @@ "appSettings_floodRetries": "Flood-försök: {count}", "appSettings_floodRetriesSubtitle": "Hur många gånger Flood används. Flood tar mer sändningstid. Med rotation på kommer de efter de direkta försöken.", "appSettings_loginAttempts": "Inloggningsförsök: {count}", - "appSettings_loginAttemptsSubtitle": "Hur många gånger inloggning till en repeater eller room-server provas innan den ger upp." + "appSettings_loginAttemptsSubtitle": "Hur många gånger inloggning till en repeater eller room-server provas innan den ger upp.", + "appSettings_repeatersAndRooms": "Repeatrar och rum", + "appSettings_clockSyncAfterLogin": "Synka repeaterklockan vid inloggning", + "appSettings_clockSyncAfterLoginSubtitle": "Efter en lyckad repeaterinloggning skickas clock sync. Varje repeater kan fortfarande välja Standard, På eller Av.", + "appSettings_loginPasswordAutofocus": "Fokusera lösenordsfältet", + "appSettings_loginPasswordAutofocusSubtitle": "När en repeater- eller ruminloggning öppnas hamnar markören i lösenordsfältet om det är tomt. Av lämnar dialogrutan synlig tills du trycker på fältet.", + "appSettings_resetRepeaterRoomSettings": "Återställ repeater- och ruminställningar", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Återställer inställningarna i det här avsnittet. Val som sparats på enskilda repeatrar blir kvar.", + "appSettings_repeaterRoomSettingsReset": "Repeater- och ruminställningar återställda", + "repeater_clockSyncDefault": "Standard", + "repeater_clockSyncOn": "På", + "repeater_clockSyncOff": "Av" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 8b3847e9..7fdb988b 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -2386,7 +2386,7 @@ "@repeater_clockSyncAfterLoginSubtitle": { "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, - "repeater_clockSyncAfterLoginSubtitle": "Автоматично надсилати повідомлення \"синхронізація годин\" після успішного входу.", + "repeater_clockSyncAfterLoginSubtitle": "«Типово» йде за розділом «Ретранслятори та кімнати» в налаштуваннях. «Увімк.» і «Вимк.» лише для цього ретранслятора.", "repeater_clockSyncAfterLogin": "Синхронізація годин після входу", "repeater_guestTools": "Гостьові інструменти", "repeater_guest": "Інформація про ретранслятор", @@ -3762,5 +3762,16 @@ "appSettings_floodRetries": "Спроби Flood: {count}", "appSettings_floodRetriesSubtitle": "Скільки разів використовувати Flood. Flood займає більше ефірного часу. Якщо ротацію ввімкнено, вони йдуть після прямих спроб.", "appSettings_loginAttempts": "Спроби входу: {count}", - "appSettings_loginAttemptsSubtitle": "Скільки разів пробувати вхід до ретранслятора або room-сервера, перш ніж здатися." + "appSettings_loginAttemptsSubtitle": "Скільки разів пробувати вхід до ретранслятора або room-сервера, перш ніж здатися.", + "appSettings_repeatersAndRooms": "Ретранслятори та кімнати", + "appSettings_clockSyncAfterLogin": "Синхронізувати годинник ретранслятора під час входу", + "appSettings_clockSyncAfterLoginSubtitle": "Після успішного входу на ретранслятор надсилається clock sync. Для кожного ретранслятора можна лишити Типово, Увімк. або Вимк.", + "appSettings_loginPasswordAutofocus": "Фокус на полі пароля", + "appSettings_loginPasswordAutofocusSubtitle": "Коли відкривається вхід на ретранслятор або в кімнату, курсор стає в порожнє поле пароля. Вимкнено лишає вікно видимим, доки ви не торкнетеся поля.", + "appSettings_resetRepeaterRoomSettings": "Скинути налаштування ретрансляторів і кімнат", + "appSettings_resetRepeaterRoomSettingsSubtitle": "Відновлює налаштування цього розділу. Вибір, збережений для окремих ретрансляторів, лишається.", + "appSettings_repeaterRoomSettingsReset": "Налаштування ретрансляторів і кімнат скинуто", + "repeater_clockSyncDefault": "Типово", + "repeater_clockSyncOn": "Увімк.", + "repeater_clockSyncOff": "Вимк." } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 05e27bb4..231cc564 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2298,7 +2298,7 @@ "description": "Repeater setting subtitle: describes the clock sync after login behavior" }, "repeater_clockSyncAfterLogin": "登录后,自动同步时钟", - "repeater_clockSyncAfterLoginSubtitle": "在成功登录后,自动发送“时钟同步”指令。", + "repeater_clockSyncAfterLoginSubtitle": "默认跟随应用设置里的“中继和房间”。开和关只作用于这个中继。", "repeater_guestTools": "访客工具", "repeater_guest": "重复器信息", "chat_sendMessage": "发送消息", @@ -3839,5 +3839,16 @@ "appSettings_floodRetries": "Flood 尝试:{count}", "appSettings_floodRetriesSubtitle": "使用 Flood 的次数。Flood 占用更多空中时间。开启轮换时,这些尝试排在直接尝试之后。", "appSettings_loginAttempts": "登录尝试:{count}", - "appSettings_loginAttemptsSubtitle": "登录中继或房间服务器时,放弃前的尝试次数。" + "appSettings_loginAttemptsSubtitle": "登录中继或房间服务器时,放弃前的尝试次数。", + "appSettings_repeatersAndRooms": "中继和房间", + "appSettings_clockSyncAfterLogin": "登录时同步中继时钟", + "appSettings_clockSyncAfterLoginSubtitle": "成功登录中继后会发送 clock sync。每个中继仍可选择默认、开或关。", + "appSettings_loginPasswordAutofocus": "聚焦密码框", + "appSettings_loginPasswordAutofocusSubtitle": "打开中继或房间登录时,如果密码为空,光标会进入密码框。关闭后,在你点按该框之前对话框保持可见。", + "appSettings_resetRepeaterRoomSettings": "将中继和房间设置重置为默认", + "appSettings_resetRepeaterRoomSettingsSubtitle": "恢复这一节的设置。保存在各个中继上的选择保持不变。", + "appSettings_repeaterRoomSettingsReset": "中继和房间设置已重置", + "repeater_clockSyncDefault": "默认", + "repeater_clockSyncOn": "开", + "repeater_clockSyncOff": "关" } diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 20c8ab63..eebce2a3 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -145,6 +145,14 @@ class AppSettings { /// How many times a repeater or room-server login is sent before giving up. final int loginAttempts; + + /// Send `clock sync` after a repeater login when that repeater follows the + /// app default. Off matches the previous per-repeater default. + final bool clockSyncAfterLogin; + + /// Put the cursor in an empty repeater or room password field on open. + /// Off leaves the dialog alone until the field is tapped. + final bool loginPasswordAutofocus; final bool channelMinHopsEnabled; final int channelMinHops; final int channelMinHopsRetries; @@ -311,6 +319,8 @@ class AppSettings { this.directRetries = defaultDirectRetries, this.floodRetries = defaultFloodRetries, this.loginAttempts = defaultLoginAttempts, + this.clockSyncAfterLogin = false, + this.loginPasswordAutofocus = false, this.channelMinHopsEnabled = false, this.channelMinHops = 2, this.channelMinHopsRetries = 1, @@ -411,6 +421,8 @@ class AppSettings { 'max_direct_retries': directRetries, 'max_flood_retries': floodRetries, 'login_attempts': loginAttempts, + 'clock_sync_after_login': clockSyncAfterLogin, + 'login_password_autofocus': loginPasswordAutofocus, 'channel_min_hops_enabled': channelMinHopsEnabled, 'channel_min_hops': channelMinHops, 'channel_min_hops_retries': channelMinHopsRetries, @@ -565,6 +577,9 @@ class AppSettings { loginAttempts: SendAttemptPlan.clampLogin( (json['login_attempts'] as num?)?.toInt() ?? defaultLoginAttempts, ), + clockSyncAfterLogin: json['clock_sync_after_login'] as bool? ?? false, + loginPasswordAutofocus: + json['login_password_autofocus'] as bool? ?? false, channelMinHopsEnabled: json['channel_min_hops_enabled'] as bool? ?? false, channelMinHops: json['channel_min_hops'] as int? ?? 2, channelMinHopsRetries: json['channel_min_hops_retries'] as int? ?? 1, @@ -725,6 +740,8 @@ class AppSettings { int? directRetries, int? floodRetries, int? loginAttempts, + bool? clockSyncAfterLogin, + bool? loginPasswordAutofocus, bool? channelMinHopsEnabled, int? channelMinHops, int? channelMinHopsRetries, @@ -820,6 +837,9 @@ class AppSettings { directRetries: directRetries ?? this.directRetries, floodRetries: floodRetries ?? this.floodRetries, loginAttempts: loginAttempts ?? this.loginAttempts, + clockSyncAfterLogin: clockSyncAfterLogin ?? this.clockSyncAfterLogin, + loginPasswordAutofocus: + loginPasswordAutofocus ?? this.loginPasswordAutofocus, channelMinHopsEnabled: channelMinHopsEnabled ?? this.channelMinHopsEnabled, channelMinHops: channelMinHops ?? this.channelMinHops, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index fa89851d..c7c79f1c 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -83,6 +83,13 @@ class AppSettingsScreen extends StatelessWidget { child: _settingsCard(_buildRoutingContent), ), + // REPEATERS AND ROOMS + SectionHeader(context.l10n.appSettings_repeatersAndRooms), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildRepeaterRoomContent), + ), + // IMAGE MESSAGES SectionHeader(context.l10n.appSettings_imageMessagesSection), MeshCard( @@ -428,20 +435,6 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setJumpToOldestUnread, ), const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: const Icon(Icons.settings_remote_outlined, size: 24), - title: Text(context.l10n.appSettings_autoFetchRepeaterSettings), - subtitle: Text( - context.l10n.appSettings_autoFetchRepeaterSettingsSubtitle, - ), - value: settingsService.settings.autoFetchRepeaterSettings, - onChanged: settingsService.setAutoFetchRepeaterSettings, - ), - const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -520,15 +513,6 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setFloodRetries, ), const Divider(height: 1, indent: 16), - SettingsValueSlider( - title: l10n.appSettings_loginAttempts(settings.loginAttempts), - subtitle: l10n.appSettings_loginAttemptsSubtitle, - value: settings.loginAttempts, - min: SendAttemptPlan.minLoginAttempts, - max: SendAttemptPlan.maxLoginAttempts, - onChanged: settingsService.setLoginAttempts, - ), - const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -626,6 +610,83 @@ class AppSettingsScreen extends StatelessWidget { ); } + Widget _buildRepeaterRoomContent( + BuildContext context, + AppSettingsService settingsService, + ) { + final settings = settingsService.settings; + final l10n = context.l10n; + return Column( + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.schedule, size: 24), + title: Text(l10n.appSettings_clockSyncAfterLogin), + subtitle: Text(l10n.appSettings_clockSyncAfterLoginSubtitle), + value: settings.clockSyncAfterLogin, + onChanged: settingsService.setClockSyncAfterLogin, + ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.password, size: 24), + title: Text(l10n.appSettings_loginPasswordAutofocus), + subtitle: Text(l10n.appSettings_loginPasswordAutofocusSubtitle), + value: settings.loginPasswordAutofocus, + onChanged: settingsService.setLoginPasswordAutofocus, + ), + const Divider(height: 1, indent: 16), + SettingsValueSlider( + title: l10n.appSettings_loginAttempts(settings.loginAttempts), + subtitle: l10n.appSettings_loginAttemptsSubtitle, + value: settings.loginAttempts, + min: SendAttemptPlan.minLoginAttempts, + max: SendAttemptPlan.maxLoginAttempts, + onChanged: settingsService.setLoginAttempts, + ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.settings_remote_outlined, size: 24), + title: Text(l10n.appSettings_autoFetchRepeaterSettings), + subtitle: Text(l10n.appSettings_autoFetchRepeaterSettingsSubtitle), + value: settings.autoFetchRepeaterSettings, + onChanged: settingsService.setAutoFetchRepeaterSettings, + ), + const Divider(height: 1, indent: 16), + ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + leading: const Icon(Icons.restart_alt, size: 24), + title: Text(l10n.appSettings_resetRepeaterRoomSettings), + subtitle: Text(l10n.appSettings_resetRepeaterRoomSettingsSubtitle), + trailing: const Icon(Icons.keyboard_arrow_right, size: 18), + onTap: () async { + await settingsService.resetRepeaterRoomSettingsToDefault(); + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text(l10n.appSettings_repeaterRoomSettingsReset), + duration: const Duration(seconds: 2), + ); + } + }, + ), + ], + ); + } + Widget _buildImageMessagesContent( BuildContext context, AppSettingsService settingsService, diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index 37eb7ef0..8ae5e5f4 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -112,7 +112,8 @@ class _RepeaterSettingsScreenState extends State { int? _spreadingFactor; int? _codingRate; - bool _autoClockSyncAfterLogin = false; + RepeaterClockSyncOverride _clockSyncOverride = + RepeaterClockSyncOverride.followDefault; // Identity keys final TextEditingController _prvKeyController = TextEditingController(); @@ -527,13 +528,12 @@ class _RepeaterSettingsScreenState extends State { } }); - final autoClockSync = await _storage - .getRepeaterAutoClockSyncAfterLoginEnabled( - widget.repeater.publicKeyHex, - ); + final clockSync = await _storage.getRepeaterClockSyncOverride( + widget.repeater.publicKeyHex, + ); if (!mounted) return; setState(() { - _autoClockSyncAfterLogin = autoClockSync; + _clockSyncOverride = clockSync; }); } @@ -953,7 +953,7 @@ class _RepeaterSettingsScreenState extends State { _buildSectionCard( l10n.repeater_features, RepeaterSettingSection.features, - extra: [_buildClockSyncToggle()], + extra: [_buildClockSyncChoice()], ), _buildSectionCard( l10n.repeater_networkHealth, @@ -1366,22 +1366,59 @@ class _RepeaterSettingsScreenState extends State { ]; } - Widget _buildClockSyncToggle() { + Widget _buildClockSyncChoice() { final l10n = context.l10n; - return SwitchListTile( - title: Text(l10n.repeater_clockSyncAfterLogin), - subtitle: Text(l10n.repeater_clockSyncAfterLoginSubtitle), - value: _autoClockSyncAfterLogin, - onChanged: (value) async { - setState(() { - _autoClockSyncAfterLogin = value; - }); - await _storage.setRepeaterAutoClockSyncAfterLoginEnabled( - widget.repeater.publicKeyHex, - value, - ); - }, - contentPadding: EdgeInsets.zero, + final textTheme = Theme.of(context).textTheme; + ButtonSegment segment( + RepeaterClockSyncOverride value, + String label, + ) => ButtonSegment(value: value, label: MeshSegmentLabel(label)); + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.repeater_clockSyncAfterLogin, + style: textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 2), + Text( + l10n.repeater_clockSyncAfterLoginSubtitle, + style: textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + SegmentedButton( + showSelectedIcon: false, + style: const ButtonStyle( + minimumSize: WidgetStatePropertyAll(Size.fromHeight(40)), + visualDensity: VisualDensity.compact, + ), + segments: [ + segment( + RepeaterClockSyncOverride.followDefault, + l10n.repeater_clockSyncDefault, + ), + segment(RepeaterClockSyncOverride.on, l10n.repeater_clockSyncOn), + segment( + RepeaterClockSyncOverride.off, + l10n.repeater_clockSyncOff, + ), + ], + selected: {_clockSyncOverride}, + onSelectionChanged: (selected) async { + final value = selected.first; + setState(() => _clockSyncOverride = value); + await _storage.setRepeaterClockSyncOverride( + widget.repeater.publicKeyHex, + value, + ); + }, + ), + ], + ), ); } diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index ae761062..923c26f7 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -247,6 +247,14 @@ class AppSettingsService extends ChangeNotifier { ); } + Future setClockSyncAfterLogin(bool value) async { + await updateSettings(_settings.copyWith(clockSyncAfterLogin: value)); + } + + Future setLoginPasswordAutofocus(bool value) async { + await updateSettings(_settings.copyWith(loginPasswordAutofocus: value)); + } + Future setChannelMinHopsEnabled(bool value) async { await updateSettings(_settings.copyWith(channelMinHopsEnabled: value)); } @@ -739,7 +747,6 @@ class AppSettingsService extends ChangeNotifier { AppSettings.defaultRouteWeightFailureDecrement, directRetries: AppSettings.defaultDirectRetries, floodRetries: AppSettings.defaultFloodRetries, - loginAttempts: AppSettings.defaultLoginAttempts, channelMinHopsEnabled: false, channelMinHops: 2, channelMinHopsRetries: 1, @@ -747,4 +754,15 @@ class AppSettingsService extends ChangeNotifier { ), ); } + + Future resetRepeaterRoomSettingsToDefault() async { + await updateSettings( + _settings.copyWith( + clockSyncAfterLogin: false, + loginPasswordAutofocus: false, + autoFetchRepeaterSettings: false, + loginAttempts: AppSettings.defaultLoginAttempts, + ), + ); + } } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index d4532b32..d4d04ae8 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -6,6 +6,13 @@ import '../storage/prefs_manager.dart'; import '../storage/history_store.dart'; import '../utils/app_logger.dart'; +/// Per-repeater clock sync, on top of the app-wide default. +/// +/// A missing entry follows the Repeaters and Rooms setting. `true` and +/// `false` in the saved map are explicit On and Off from before that choice +/// existed, and they keep winning over the global default. +enum RepeaterClockSyncOverride { followDefault, on, off } + class StorageService { static const String _pathHistoryPrefix = 'path_history_'; static const String _pendingMessagesKey = 'pending_messages'; @@ -29,36 +36,101 @@ class StorageService { ? '$_pathHistoryPrefix$contactPubKeyHex' : '$_pathHistoryPrefix${_publicKeyHex}_$contactPubKeyHex'; - Future> _loadRepeaterAutoClockSyncAfterLogin() async { + Future> + _loadRepeaterClockSyncOverrides() async { final prefs = PrefsManager.instance; final jsonStr = prefs.getString(_repeaterAutoClockSyncAfterLoginKey); - if (jsonStr == null) return {}; try { final json = jsonDecode(jsonStr) as Map; - return json.map((key, value) => MapEntry(key, value == true)); + final overrides = {}; + for (final entry in json.entries) { + final override = switch (entry.value) { + true || 'on' => RepeaterClockSyncOverride.on, + false || 'off' => RepeaterClockSyncOverride.off, + _ => RepeaterClockSyncOverride.followDefault, + }; + if (override != RepeaterClockSyncOverride.followDefault) { + overrides[entry.key] = override; + } + } + return overrides; } catch (e) { return {}; } } + Future _saveRepeaterClockSyncOverrides( + Map overrides, + ) async { + final prefs = PrefsManager.instance; + final stored = { + for (final entry in overrides.entries) + if (entry.value == RepeaterClockSyncOverride.on) + entry.key: true + else if (entry.value == RepeaterClockSyncOverride.off) + entry.key: false, + }; + if (stored.isEmpty) { + await prefs.remove(_repeaterAutoClockSyncAfterLoginKey); + return; + } + await prefs.setString( + _repeaterAutoClockSyncAfterLoginKey, + jsonEncode(stored), + ); + } + + Future getRepeaterClockSyncOverride( + String repeaterPubKeyHex, + ) async { + final overrides = await _loadRepeaterClockSyncOverrides(); + return overrides[repeaterPubKeyHex] ?? + RepeaterClockSyncOverride.followDefault; + } + + /// Whether this repeater should receive `clock sync` after login. + /// + /// An explicit per-repeater choice wins. Otherwise [globalDefault] applies. + Future repeaterClockSyncAfterLogin( + String repeaterPubKeyHex, { + required bool globalDefault, + }) async { + return switch (await getRepeaterClockSyncOverride(repeaterPubKeyHex)) { + RepeaterClockSyncOverride.followDefault => globalDefault, + RepeaterClockSyncOverride.on => true, + RepeaterClockSyncOverride.off => false, + }; + } + + Future setRepeaterClockSyncOverride( + String repeaterPubKeyHex, + RepeaterClockSyncOverride override, + ) async { + final overrides = await _loadRepeaterClockSyncOverrides(); + if (override == RepeaterClockSyncOverride.followDefault) { + overrides.remove(repeaterPubKeyHex); + } else { + overrides[repeaterPubKeyHex] = override; + } + await _saveRepeaterClockSyncOverrides(overrides); + } + Future getRepeaterAutoClockSyncAfterLoginEnabled( String repeaterPubKeyHex, ) async { - final settings = await _loadRepeaterAutoClockSyncAfterLogin(); - return settings[repeaterPubKeyHex] ?? false; + return repeaterClockSyncAfterLogin(repeaterPubKeyHex, globalDefault: false); } Future setRepeaterAutoClockSyncAfterLoginEnabled( String repeaterPubKeyHex, bool enabled, ) async { - final prefs = PrefsManager.instance; - final settings = await _loadRepeaterAutoClockSyncAfterLogin(); - settings[repeaterPubKeyHex] = enabled; - final jsonStr = jsonEncode(settings); - await prefs.setString(_repeaterAutoClockSyncAfterLoginKey, jsonStr); + await setRepeaterClockSyncOverride( + repeaterPubKeyHex, + enabled ? RepeaterClockSyncOverride.on : RepeaterClockSyncOverride.off, + ); } Future savePathHistory( diff --git a/lib/widgets/repeater_login_dialog.dart b/lib/widgets/repeater_login_dialog.dart index 9402a719..169e853b 100644 --- a/lib/widgets/repeater_login_dialog.dart +++ b/lib/widgets/repeater_login_dialog.dart @@ -198,10 +198,13 @@ class _RepeaterLoginDialogState extends State { await _storage.removeRepeaterPassword(widget.repeater.publicKeyHex); } - final autoClockSync = await _storage - .getRepeaterAutoClockSyncAfterLoginEnabled( - widget.repeater.publicKeyHex, - ); + final globalClockSync = mounted + ? context.read().settings.clockSyncAfterLogin + : false; + final autoClockSync = await _storage.repeaterClockSyncAfterLogin( + widget.repeater.publicKeyHex, + globalDefault: globalClockSync, + ); if (autoClockSync) { try { final timestampSeconds = @@ -393,7 +396,12 @@ class _RepeaterLoginDialogState extends State { } }, onSubmitted: (_) => _handleLogin(), - autofocus: _passwordController.text.isEmpty, + autofocus: + context + .watch() + .settings + .loginPasswordAutofocus && + _passwordController.text.isEmpty, ), const SizedBox(height: 12), CheckboxListTile( diff --git a/lib/widgets/room_login_dialog.dart b/lib/widgets/room_login_dialog.dart index 5ea47a06..1a408759 100644 --- a/lib/widgets/room_login_dialog.dart +++ b/lib/widgets/room_login_dialog.dart @@ -324,6 +324,10 @@ class _RoomLoginDialogState extends State { ), onSubmitted: (_) => _handleLogin(), autofocus: + context + .watch() + .settings + .loginPasswordAutofocus && !PlatformInfo.isMobile && _passwordController.text.isEmpty, ), diff --git a/test/models/send_attempt_plan_test.dart b/test/models/send_attempt_plan_test.dart index 13ad8ec0..0b80e969 100644 --- a/test/models/send_attempt_plan_test.dart +++ b/test/models/send_attempt_plan_test.dart @@ -133,7 +133,7 @@ void main() { expect(settings.autoRouteRotationEnabled, isTrue); expect(settings.directRetries, SendAttemptPlan.defaultDirectRetries); expect(settings.floodRetries, SendAttemptPlan.defaultFloodRetries); - expect(settings.loginAttempts, SendAttemptPlan.defaultLoginAttempts); + expect(settings.loginAttempts, 9); expect(settings.channelMinHopsEnabled, isFalse); expect(settings.channelMinHops, 2); expect(settings.channelMinHopsRetries, 1); @@ -147,5 +147,30 @@ void main() { SendAttemptPlan.defaultDirectRetries, ); expect(reloaded.settings.floodRetries, SendAttemptPlan.defaultFloodRetries); + expect(reloaded.settings.loginAttempts, 9); + }); + + test('reset repeater and room settings restores that section', () async { + SharedPreferences.setMockInitialValues({}); + await PrefsManager.initialize(); + final service = AppSettingsService(); + await service.loadSettings(); + await service.updateSettings( + service.settings.copyWith( + clockSyncAfterLogin: true, + loginPasswordAutofocus: true, + autoFetchRepeaterSettings: true, + loginAttempts: 8, + directRetries: 12, + ), + ); + + await service.resetRepeaterRoomSettingsToDefault(); + final settings = service.settings; + expect(settings.clockSyncAfterLogin, isFalse); + expect(settings.loginPasswordAutofocus, isFalse); + expect(settings.autoFetchRepeaterSettings, isFalse); + expect(settings.loginAttempts, SendAttemptPlan.defaultLoginAttempts); + expect(settings.directRetries, 12); }); } diff --git a/test/screens/routing_settings_screen_test.dart b/test/screens/routing_settings_screen_test.dart index 402d95cb..7a142781 100644 --- a/test/screens/routing_settings_screen_test.dart +++ b/test/screens/routing_settings_screen_test.dart @@ -83,6 +83,19 @@ void main() { expect(find.text(l10n.appSettings_autoRouteRotation), findsOneWidget); expect(find.text(l10n.appSettings_channelMinHopsCount(2)), findsNothing); expect(find.text(l10n.appSettings_resetRoutingToDefault), findsOneWidget); + expect( + find.text(l10n.appSettings_repeatersAndRooms.toUpperCase()), + findsOneWidget, + ); + expect(find.text(l10n.appSettings_clockSyncAfterLogin), findsOneWidget); + expect( + find.text(l10n.appSettings_loginPasswordAutofocus), + findsOneWidget, + ); + expect( + find.text(l10n.appSettings_autoFetchRepeaterSettings), + findsOneWidget, + ); final channelSwitch = find.text(l10n.appSettings_channelMinHops); await tester.tap(channelSwitch); diff --git a/test/services/repeater_clock_sync_test.dart b/test/services/repeater_clock_sync_test.dart new file mode 100644 index 00000000..9b730f6f --- /dev/null +++ b/test/services/repeater_clock_sync_test.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('a saved on or off overrides the global clock-sync default', () async { + SharedPreferences.setMockInitialValues({ + 'repeater_auto_clock_sync_after_login': jsonEncode({ + 'on-node': true, + 'off-node': false, + }), + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + final storage = StorageService(); + + expect( + await storage.repeaterClockSyncAfterLogin( + 'on-node', + globalDefault: false, + ), + isTrue, + ); + expect( + await storage.repeaterClockSyncAfterLogin( + 'off-node', + globalDefault: true, + ), + isFalse, + ); + expect( + await storage.repeaterClockSyncAfterLogin( + 'new-node', + globalDefault: true, + ), + isTrue, + ); + expect( + await storage.repeaterClockSyncAfterLogin( + 'new-node', + globalDefault: false, + ), + isFalse, + ); + }); + + test('choosing default removes the per-repeater override', () async { + final storage = StorageService(); + await storage.setRepeaterClockSyncOverride( + 'node', + RepeaterClockSyncOverride.on, + ); + expect( + await storage.getRepeaterClockSyncOverride('node'), + RepeaterClockSyncOverride.on, + ); + + await storage.setRepeaterClockSyncOverride( + 'node', + RepeaterClockSyncOverride.followDefault, + ); + expect( + await storage.getRepeaterClockSyncOverride('node'), + RepeaterClockSyncOverride.followDefault, + ); + expect( + PrefsManager.instance.containsKey('repeater_auto_clock_sync_after_login'), + isFalse, + ); + }); +} From 1656486d77a84f80f5c5c6c91f0b3db82e58ad20 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 01:10:11 +0000 Subject: [PATCH 18/50] Flood when the direct-attempt budget is already spent A flood-only send was keeping the contact's direct path whenever route history had not loaded yet. Co-authored-by: zjs81 --- lib/connector/meshcore_connector.dart | 53 +++++++++++---- test/connector/flood_only_attempt_test.dart | 73 +++++++++++++++++++++ 2 files changed, 113 insertions(+), 13 deletions(-) create mode 100644 test/connector/flood_only_attempt_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 9d59570e..9bcf9075 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -2868,6 +2868,18 @@ class MeshCoreConnector extends ChangeNotifier { required int directRetries, List recentSelections = const [], }) { + // Flood attempts do not need a saved route. History loads asynchronously + // and is empty on the first read after startup, so checking it first + // would keep the contact's direct path and spend a flood-only budget + // without flooding. + if (directRetries <= 0 || attemptIndex >= directRetries) { + return _recordAutoPath( + contactPubKeyHex, + const PathSelection(pathBytes: [], hopCount: -1, useFlood: true), + attemptIndex: attemptIndex, + ); + } + final hasKnownPaths = _pathHistoryService?.getRecentPaths(contactPubKeyHex).isNotEmpty ?? false; @@ -2884,19 +2896,34 @@ class MeshCoreConnector extends ChangeNotifier { recentSelections: recentSelections, context: routeContext, ); - if (selection != null) { - _pathHistoryService?.recordPathAttempt(contactPubKeyHex, selection); - // Logged so route choices and their outcomes can be compared from the - // app debug log on a live mesh. - _appDebugLogService?.info( - 'Route pick for ${contact?.name ?? contactPubKeyHex.substring(0, 8)}: ' - 'attempt ${attemptIndex + 1} ' - '→ ${_describeRoute(selection)} ' - '(heard nearby: ${routeContext.hasNeighbourInfo}, ' - 'contact heard direct: ${routeContext.contactHeardDirectly})', - tag: 'Routing', - ); - } + if (selection == null) return null; + return _recordAutoPath( + contactPubKeyHex, + selection, + attemptIndex: attemptIndex, + routeContext: routeContext, + ); + } + + PathSelection _recordAutoPath( + String contactPubKeyHex, + PathSelection selection, { + required int attemptIndex, + RouteContext? routeContext, + }) { + _pathHistoryService?.recordPathAttempt(contactPubKeyHex, selection); + final contact = getContactByPubKeyHex(contactPubKeyHex); + final context = routeContext ?? routeContextFor(contact); + // Logged so route choices and their outcomes can be compared from the + // app debug log on a live mesh. + _appDebugLogService?.info( + 'Route pick for ${contact?.name ?? contactPubKeyHex.substring(0, 8)}: ' + 'attempt ${attemptIndex + 1} ' + '→ ${_describeRoute(selection)} ' + '(heard nearby: ${context.hasNeighbourInfo}, ' + 'contact heard direct: ${context.contactHeardDirectly})', + tag: 'Routing', + ); return selection; } diff --git a/test/connector/flood_only_attempt_test.dart b/test/connector/flood_only_attempt_test.dart new file mode 100644 index 00000000..f436c53b --- /dev/null +++ b/test/connector/flood_only_attempt_test.dart @@ -0,0 +1,73 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; + +Contact _directContact() { + return Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), + name: 'Hill', + type: 1, + pathLength: 1, + path: Uint8List.fromList(const [0x11]), + lastSeen: DateTime.now(), + ); +} + +void main() { + late MeshCoreConnector connector; + late PathHistoryService history; + late MessageRetryService retries; + late AppSettingsService settings; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + settings = AppSettingsService(); + await settings.loadSettings(); + connector = MeshCoreConnector(); + history = PathHistoryService(StorageService()); + retries = MessageRetryService(); + connector.initialize( + retryService: retries, + pathHistoryService: history, + appSettingsService: settings, + ); + }); + + tearDown(() { + connector.dispose(); + history.dispose(); + retries.dispose(); + }); + + test('flood attempts do not wait for route history', () async { + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: true, + directRetries: 0, + floodRetries: 1, + ), + ); + + final flooded = await connector.preparePathForContactSend(_directContact()); + expect(flooded.useFlood, isTrue); + + await settings.updateSettings( + settings.settings.copyWith(directRetries: 2, floodRetries: 1), + ); + final direct = await connector.preparePathForContactSend(_directContact()); + expect(direct.useFlood, isFalse); + expect(direct.hopCount, 1); + expect(direct.pathBytes, [0x11]); + }); +} From df7c3efa4aef1a58e632da731848867bb33d0ebf Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 18:13:51 -0700 Subject: [PATCH 19/50] Show the saved Cyr2Lat profile again after a failed save --- lib/widgets/chat_compression_selector.dart | 12 +++++++++-- .../chat_compression_selector_test.dart | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/widgets/chat_compression_selector.dart b/lib/widgets/chat_compression_selector.dart index 5bddf0cd..864a7f1e 100644 --- a/lib/widgets/chat_compression_selector.dart +++ b/lib/widgets/chat_compression_selector.dart @@ -81,6 +81,9 @@ class _SelectorView { final bool busy; final bool failed; + /// Counts failed saves, so the profile picker drops an unsaved choice. + final int failures; + const _SelectorView({ required this.mode, required this.enabled, @@ -88,6 +91,7 @@ class _SelectorView { required this.profileId, required this.busy, required this.failed, + required this.failures, }); } @@ -95,6 +99,7 @@ class _ChatCompressionSelectorState extends State { late final ValueNotifier<_SelectorView> _view = ValueNotifier(_snapshot()); bool _busy = false; bool _failed = false; + int _failures = 0; _SelectorView _snapshot() => _SelectorView( mode: widget.mode, @@ -103,6 +108,7 @@ class _ChatCompressionSelectorState extends State { profileId: widget.effectiveProfileId, busy: _busy, failed: _failed, + failures: _failures, ); @override @@ -125,6 +131,7 @@ class _ChatCompressionSelectorState extends State { setState(() { _busy = busy; _failed = failed; + if (failed) _failures++; }); _view.value = _snapshot(); } @@ -252,8 +259,9 @@ class _ChatCompressionSelectorState extends State { Padding( padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), child: DropdownButtonFormField( - // Rebuild with the saved value after a change or failure. - key: ValueKey(profileValue), + // The field keeps a picked value internally, so rebuild + // it with the saved value after a change or a failure. + key: ValueKey('$profileValue#${view.failures}'), isExpanded: true, initialValue: profileValue, decoration: InputDecoration( diff --git a/test/widgets/chat_compression_selector_test.dart b/test/widgets/chat_compression_selector_test.dart index a3ad6633..ec32ff8d 100644 --- a/test/widgets/chat_compression_selector_test.dart +++ b/test/widgets/chat_compression_selector_test.dart @@ -260,6 +260,27 @@ void main() { expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget); }); + testWidgets('a failed profile save shows the saved profile again', ( + tester, + ) async { + await pumpHost(tester, mode: ChatCompressionMode.cyr2lat, profileId: 'ru'); + await openSheet(tester); + + await tester.ensureVisible(find.text('Russian')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Russian')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Serbian').last); + await tester.pump(); + expect(profileCalls, ['sr']); + pending.single.completeError(StateError('disk full')); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget); + expect(find.text('Russian'), findsOneWidget); + expect(find.text('Serbian'), findsNothing); + }); + testWidgets('disabled shows the saved mode, and the sheet says why and ' 'allows no change', (tester) async { final semantics = tester.ensureSemantics(); From 3f4215a95575cd14cea526b54e564b5f03e12cee Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 18:13:53 -0700 Subject: [PATCH 20/50] Keep a long reply region chip inside the composer quote --- lib/screens/channel_chat_screen.dart | 2 + lib/widgets/chat_composer.dart | 63 ++++++++++++++++------------ test/widgets/chat_composer_test.dart | 8 ++++ 3 files changed, 47 insertions(+), 26 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 99a214c7..02aedafa 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -2670,6 +2670,8 @@ class _ChannelChatScreenState extends State { ), child: Text( context.l10n.channels_regionSetTo(replyRegion!), + maxLines: 1, + overflow: TextOverflow.ellipsis, style: MeshTheme.mono( fontSize: 12 * textScale, diff --git a/lib/widgets/chat_composer.dart b/lib/widgets/chat_composer.dart index 8141e676..4f59efaa 100644 --- a/lib/widgets/chat_composer.dart +++ b/lib/widgets/chat_composer.dart @@ -468,34 +468,45 @@ class ChatComposerQuote extends StatelessWidget { ), child: Padding( padding: const EdgeInsetsDirectional.fromSTEB(10, 6, 0, 6), - child: Row( - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w700, - color: accent, + child: LayoutBuilder( + builder: (context, constraints) => Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w700, + color: accent, + ), ), - ), - content, - ], + content, + ], + ), ), - ), - ?trailing, - IconButton( - icon: const Icon(Icons.close), - tooltip: dismissTooltip, - color: scheme.onSurfaceVariant, - onPressed: onDismiss, - ), - ], + // The quote shares its row with Send, so a long trailing + // control (a region chip) must not squeeze out the message + // or the dismiss button. + if (trailing != null) + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: constraints.maxWidth * 0.4, + ), + child: trailing, + ), + IconButton( + icon: const Icon(Icons.close), + tooltip: dismissTooltip, + color: scheme.onSurfaceVariant, + onPressed: onDismiss, + ), + ], + ), ), ), ), diff --git a/test/widgets/chat_composer_test.dart b/test/widgets/chat_composer_test.dart index e75a590c..dd56e995 100644 --- a/test/widgets/chat_composer_test.dart +++ b/test/widgets/chat_composer_test.dart @@ -479,10 +479,18 @@ void main() { ), onDismiss: () {}, dismissTooltip: _l10n.chat_cancelReply, + // A long region chip, as a channel reply shows. + trailing: Text( + _l10n.channels_regionSetTo('north-west-valley'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), ), ); await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.byTooltip(_l10n.chat_cancelReply), findsOneWidget); await _type(tester, 'a' * 19); expect(tester.takeException(), isNull); From 27cc332383a6a12ddee7fe09893d82fa9683334e Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 20:59:56 -0700 Subject: [PATCH 21/50] Add leading icons to every settings row --- documentation/design.md | 7 +- lib/screens/app_settings_screen.dart | 20 +- lib/screens/repeater_settings_screen.dart | 36 +- lib/widgets/settings_reveal.dart | 6 +- lib/widgets/translation_settings_section.dart | 2 +- .../screens/routing_settings_screen_test.dart | 335 ++++++++++++++++++ 6 files changed, 382 insertions(+), 24 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index 7047e0c6..dd163efa 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -97,6 +97,7 @@ Minimum sizes: no hard-coded `fontSize` below 12 exists in `lib/screens` or `lib | Section header | padding 16, 20, 16, 8 (LTRB) | `SectionHeader` | | Settings row | padding 16 / 12, 24px icon, 16 gap, chevron 24 | `MeshNavTile` | | Switch row | `SwitchListTile`, `contentPadding` 16 / 4, `secondary` icon size 24 | `app_settings_screen.dart` | +| Slider row | `SettingsValueSlider` (`ListTile`), `contentPadding` 16 / 4, `leading` icon size 24, 16 gap | `settings_reveal.dart` | | Popup menu row | 20px icon, 12 gap | `MeshMenuItemRow` | | Banner | padding 16 / 12, 24px icon, 12 gap | `RadioDisconnectedBanner` | | Sheet header | padding 20, 8, 8, 4 (LTRB), 36×4 drag handle | `BottomSheetHeader` | @@ -105,6 +106,8 @@ Minimum sizes: no hard-coded `fontSize` below 12 exists in `lib/screens` or `lib | Avatar | 40 | `AvatarCircle` | | List bottom padding under a FAB | 88 | `channels_screen.dart` | +Every settings row — including sliders, selectors, and child rows revealed inside `SettingsReveal` — has a leading 24px icon with a 16px gap (`MeshNavTile`, `SwitchListTile.secondary`, or `ListTile.leading`) so titles align vertically across a card. + Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small action buttons, 18 for inline refresh icons and spinners. Keep tappable icons at 20 or more. **Tap targets.** Keep Flutter's 48×48 minimum (the default `materialTapTargetSize` and `IconButton` size). Don't shrink with `VisualDensity.compact`, `MaterialTapTargetSize.shrinkWrap` or small `BoxConstraints` unless the control sits inside a larger tappable row. @@ -118,7 +121,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Settings navigation row | `MeshNavTile` | `onTap: null` dims it to 50 % and reports it as disabled; use `subtitle` to say why | | Settings switch | `SwitchListTile` inside `MeshSettingsTileTheme` | Wrap the settings screen body once in `MeshSettingsTileTheme` | | Switch that reveals more controls | `SettingsReveal` | 200ms height ease, `surfaceContainerHighest`, 16px start indent. See [Reveal on enable](#reveal-on-enable) | -| Settings slider | `SettingsValueSlider` | The title includes the selected number, so it stays visible. The drag bubble repeats it | +| Settings slider | `SettingsValueSlider` | Requires a 24px `icon` (`ListTile.leading`). The title includes the selected number, so it stays visible. The drag bubble repeats it | | Radio-style choice in a sheet | `MeshSheetOption` | Used by the language picker and map time filter | | Choosing between images | Selectable thumbnail tiles in a centred `Wrap` | Image send versions (`_versionTile` in `image_send_preview_sheet.dart`). `InkWell` with `MeshRadii.sm`; selected tile gets a 3px `primary` border **and** a `primary` check badge (never colour alone); caption under the tile in `bodySmall`, w600 when selected; figures such as packet counts in `MeshTheme.mono` 12; wrap the tile in `Semantics(button: true, selected:, label:)` | | Popup menu row | **always** `PopupMenuItem(child: MeshMenuItemRow(icon:, label:))` | Label wraps to 2 lines then ellipsizes; `leading:` for `ThemedIcon`; no icon keeps the 20px slot | @@ -157,7 +160,7 @@ The same animation without the tint is `RevealOnEnable`. Use it when the reveale Do not add a second duration, and do not reveal the controls with a plain `if` that pops them in. A block that swaps between two bodies, such as the filtered-message preview, keeps `AnimatedSize` but uses `RevealOnEnable.duration` and `RevealOnEnable.curve`. -Sliders that belong to a setting use `SettingsValueSlider`. Put the selected number in the title (a localized string with the count). The slider's drag label repeats that number; it is not the only place the value appears. +Sliders that belong to a setting use `SettingsValueSlider` with a 24px `icon` (`ListTile.leading`) so the title and slider line up with adjacent rows. Put the selected number in the title (a localized string with the count). The slider's drag label repeats that number; it is not the only place the value appears. ## 6. Sheets, dialogs and pages diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index c7c79f1c..85fb9920 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -496,6 +496,7 @@ class AppSettingsScreen extends StatelessWidget { ), const Divider(height: 1, indent: 16), SettingsValueSlider( + icon: Icons.route, title: l10n.appSettings_directRetries(settings.directRetries), subtitle: l10n.appSettings_directRetriesSubtitle, value: settings.directRetries, @@ -505,6 +506,7 @@ class AppSettingsScreen extends StatelessWidget { ), const Divider(height: 1, indent: 16), SettingsValueSlider( + icon: Icons.waves, title: l10n.appSettings_floodRetries(settings.floodRetries), subtitle: l10n.appSettings_floodRetriesSubtitle, value: settings.floodRetries, @@ -551,6 +553,7 @@ class AppSettingsScreen extends StatelessWidget { visible: settings.channelMinHopsEnabled, children: [ SettingsValueSlider( + icon: Icons.linear_scale, title: l10n.appSettings_channelMinHopsCount( settings.channelMinHops, ), @@ -560,6 +563,7 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setChannelMinHops, ), SettingsValueSlider( + icon: Icons.repeat, title: l10n.appSettings_channelMinHopsRetries( settings.channelMinHopsRetries, ), @@ -643,6 +647,7 @@ class AppSettingsScreen extends StatelessWidget { ), const Divider(height: 1, indent: 16), SettingsValueSlider( + icon: Icons.login, title: l10n.appSettings_loginAttempts(settings.loginAttempts), subtitle: l10n.appSettings_loginAttemptsSubtitle, value: settings.loginAttempts, @@ -721,15 +726,10 @@ class AppSettingsScreen extends StatelessWidget { : null, ), const Divider(height: 1, indent: 16), - ListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - leading: const Icon(Icons.link_outlined, size: 20), - title: Text(context.l10n.appSettings_ipfsImageLinks), - subtitle: Text(context.l10n.appSettings_ipfsImageLinksSubtitle), - trailing: const Icon(Icons.chevron_right, size: 18), + MeshNavTile( + icon: Icons.link_outlined, + title: context.l10n.appSettings_ipfsImageLinks, + subtitle: context.l10n.appSettings_ipfsImageLinksSubtitle, onTap: () => _showIpfsImageLinksDialog(context, settingsService), ), const Divider(height: 1, indent: 16), @@ -983,7 +983,7 @@ class AppSettingsScreen extends StatelessWidget { size: 24, color: scheme.onSurfaceVariant, ), - const SizedBox(width: 12), + const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index 8ae5e5f4..9b0fbb84 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -1368,6 +1368,7 @@ class _RepeaterSettingsScreenState extends State { Widget _buildClockSyncChoice() { final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; ButtonSegment segment( RepeaterClockSyncOverride value, @@ -1378,16 +1379,31 @@ class _RepeaterSettingsScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - l10n.repeater_clockSyncAfterLogin, - style: textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.w600), - ), - const SizedBox(height: 2), - Text( - l10n.repeater_clockSyncAfterLoginSubtitle, - style: textTheme.bodyMedium?.copyWith( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), + Row( + children: [ + Icon(Icons.schedule, size: 24, color: scheme.onSurfaceVariant), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.repeater_clockSyncAfterLogin, + style: textTheme.bodyLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Text( + l10n.repeater_clockSyncAfterLoginSubtitle, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], ), const SizedBox(height: 8), SegmentedButton( diff --git a/lib/widgets/settings_reveal.dart b/lib/widgets/settings_reveal.dart index 7e84951c..b818f112 100644 --- a/lib/widgets/settings_reveal.dart +++ b/lib/widgets/settings_reveal.dart @@ -67,8 +67,10 @@ class SettingsReveal extends StatelessWidget { /// A settings slider whose selected value stays visible in the title. /// /// The drag bubble repeats the same number. Pass a [title] that already -/// includes [value], the way the channel-hop titles do. +/// includes [value], the way the channel-hop titles do, and an [icon] so the +/// row aligns with neighbouring [SwitchListTile] and [MeshNavTile] rows. class SettingsValueSlider extends StatelessWidget { + final IconData icon; final String title; final String? subtitle; final int value; @@ -78,6 +80,7 @@ class SettingsValueSlider extends StatelessWidget { const SettingsValueSlider({ super.key, + required this.icon, required this.title, this.subtitle, required this.value, @@ -91,6 +94,7 @@ class SettingsValueSlider extends StatelessWidget { final clamped = value.clamp(min, max); return ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + leading: Icon(icon, size: 24), title: Text(title), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart index dd8c6ac5..eda14c60 100644 --- a/lib/widgets/translation_settings_section.dart +++ b/lib/widgets/translation_settings_section.dart @@ -233,7 +233,7 @@ class TranslationSettingsSection extends StatelessWidget { ? scheme.primary : scheme.onSurfaceVariant, ), - const SizedBox(width: 12), + const SizedBox(width: 16), Expanded( child: InkWell( borderRadius: BorderRadius.circular(MeshRadii.xs), diff --git a/test/screens/routing_settings_screen_test.dart b/test/screens/routing_settings_screen_test.dart index 7a142781..7ba8b33d 100644 --- a/test/screens/routing_settings_screen_test.dart +++ b/test/screens/routing_settings_screen_test.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; @@ -5,12 +7,17 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; import 'package:meshcore_open/models/send_attempt_plan.dart'; import 'package:meshcore_open/screens/app_settings_screen.dart'; +import 'package:meshcore_open/screens/repeater_settings_screen.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; import 'package:meshcore_open/services/translation_service.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/mesh_ui.dart'; import 'package:meshcore_open/widgets/settings_reveal.dart'; void main() { @@ -117,4 +124,332 @@ void main() { expect(find.text(l10n.appSettings_channelMinHopsCount(2)), findsNothing); }, ); + + testWidgets( + 'routing and repeaters/rooms rows and clock-sync selector have leading 24px icons with aligned titles', + (tester) async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith(channelMinHopsEnabled: true), + ); + + tester.view.physicalSize = const Size(800, 8000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + final connector = MeshCoreConnector(); + final translation = TranslationService(settings); + final uploads = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + addTearDown(connector.dispose); + addTearDown(translation.dispose); + addTearDown(uploads.dispose); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: uploads), + ], + child: MaterialApp( + theme: MeshTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const AppSettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + final context = tester.element(find.byType(AppSettingsScreen)); + final l10n = AppLocalizations.of(context); + + final topLevelTitles = [ + l10n.appSettings_clearPathOnMaxRetry, + l10n.appSettings_directRetries(settings.settings.directRetries), + l10n.appSettings_floodRetries(settings.settings.floodRetries), + l10n.appSettings_autoRouteRotation, + l10n.appSettings_channelMinHops, + l10n.appSettings_resetRoutingToDefault, + l10n.appSettings_clockSyncAfterLogin, + l10n.appSettings_loginPasswordAutofocus, + l10n.appSettings_loginAttempts(settings.settings.loginAttempts), + l10n.appSettings_autoFetchRepeaterSettings, + l10n.appSettings_resetRepeaterRoomSettings, + ]; + final revealedTitles = [ + l10n.appSettings_channelMinHopsCount(settings.settings.channelMinHops), + l10n.appSettings_channelMinHopsRetries( + settings.settings.channelMinHopsRetries, + ), + l10n.appSettings_channelMinHopsCountRepeaters, + ]; + + double expectRowLeadingIcon(String title) { + final titleFinder = find.text(title); + expect(titleFinder, findsOneWidget, reason: 'Missing row "$title"'); + final tileFinder = find.ancestor( + of: titleFinder, + matching: find.byType(ListTile), + ); + expect(tileFinder, findsOneWidget, reason: 'No ListTile for "$title"'); + final iconFinder = find.descendant( + of: tileFinder, + matching: find.byType(Icon), + ); + final icons = tester.widgetList(iconFinder).toList(); + final titleRect = tester.getRect(titleFinder); + final leadingIcons = [ + for (var i = 0; i < icons.length; i++) + if (tester.getRect(iconFinder.at(i)).right < titleRect.left) + (icon: icons[i], rect: tester.getRect(iconFinder.at(i))), + ]; + expect( + leadingIcons, + hasLength(1), + reason: 'Expected 1 leading icon for "$title"', + ); + expect( + leadingIcons.single.icon.size, + 24, + reason: 'Leading icon for "$title" must be 24px', + ); + expect( + leadingIcons.single.rect.size, + const Size(24, 24), + reason: 'Rendered leading icon for "$title" must be 24x24', + ); + return titleRect.left; + } + + final topTitleLefts = [ + for (final title in topLevelTitles) expectRowLeadingIcon(title), + ]; + for (final left in topTitleLefts) { + expect(left, closeTo(topTitleLefts.first, 0.5)); + } + + final revealedTitleLefts = [ + for (final title in revealedTitles) expectRowLeadingIcon(title), + ]; + for (final left in revealedTitleLefts) { + expect(left, closeTo(topTitleLefts.first + 16, 0.5)); + } + + // Check the Default / On / Off clock-sync selector on RepeaterSettingsScreen. + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ], + child: MaterialApp( + theme: MeshTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: RepeaterSettingsScreen( + repeater: Contact( + publicKey: Uint8List(32), + name: 'Repeater', + type: 2, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime(2026), + ), + password: 'x', + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 500)); + + final rContext = tester.element(find.byType(RepeaterSettingsScreen)); + final rL10n = AppLocalizations.of(rContext); + final selectorTitle = find.text(rL10n.repeater_clockSyncAfterLogin); + await tester.ensureVisible(selectorTitle); + await tester.pump(); + + expect( + find.byType(SegmentedButton), + findsOneWidget, + ); + for (final label in [ + rL10n.repeater_clockSyncDefault, + rL10n.repeater_clockSyncOn, + rL10n.repeater_clockSyncOff, + ]) { + expect( + find.byWidgetPredicate( + (w) => w is MeshSegmentLabel && w.text == label, + ), + findsOneWidget, + ); + } + + final clockIconFinder = find.byIcon(Icons.schedule); + expect(clockIconFinder, findsOneWidget); + final clockIcon = tester.widget(clockIconFinder); + expect(clockIcon.size, 24); + final clockIconRect = tester.getRect(clockIconFinder); + final selectorTitleRect = tester.getRect(selectorTitle); + expect(clockIconRect.size, const Size(24, 24)); + expect(selectorTitleRect.left - clockIconRect.right, closeTo(16, 0.5)); + }, + ); + + for (final scale in [1.3, 2.0]) { + testWidgets( + 'routing, repeaters/rooms, and clock-sync selector fit 320dp at ${scale}x', + (tester) async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith(channelMinHopsEnabled: true), + ); + + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (text.contains('overflowed')) { + overflows.add(text.split('\n').first); + } else { + previous?.call(details); + } + }; + addTearDown(() => FlutterError.onError = previous); + + final connector = MeshCoreConnector(); + final translation = TranslationService(settings); + final uploads = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + addTearDown(connector.dispose); + addTearDown(translation.dispose); + addTearDown(uploads.dispose); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: uploads), + ], + child: MaterialApp( + theme: MeshTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: const AppSettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + final context = tester.element(find.byType(AppSettingsScreen)); + final l10n = AppLocalizations.of(context); + for (final label in [ + l10n.appSettings_clearPathOnMaxRetry, + l10n.appSettings_directRetries(settings.settings.directRetries), + l10n.appSettings_floodRetries(settings.settings.floodRetries), + l10n.appSettings_channelMinHopsCount( + settings.settings.channelMinHops, + ), + l10n.appSettings_channelMinHopsRetries( + settings.settings.channelMinHopsRetries, + ), + l10n.appSettings_channelMinHopsCountRepeaters, + l10n.appSettings_resetRoutingToDefault, + l10n.appSettings_clockSyncAfterLogin, + l10n.appSettings_loginPasswordAutofocus, + l10n.appSettings_loginAttempts(settings.settings.loginAttempts), + l10n.appSettings_autoFetchRepeaterSettings, + l10n.appSettings_resetRepeaterRoomSettings, + ]) { + await tester.scrollUntilVisible( + find.text(label), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.pump(); + expect(find.text(label), findsOneWidget); + } + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ], + child: MaterialApp( + theme: MeshTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: RepeaterSettingsScreen( + repeater: Contact( + publicKey: Uint8List(32), + name: 'Repeater', + type: 2, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime(2026), + ), + password: 'x', + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 500)); + + final rContext = tester.element(find.byType(RepeaterSettingsScreen)); + final rL10n = AppLocalizations.of(rContext); + await tester.scrollUntilVisible( + find.text(rL10n.repeater_clockSyncAfterLogin), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.pump(); + expect(find.text(rL10n.repeater_clockSyncAfterLogin), findsOneWidget); + expect( + find.byWidgetPredicate( + (w) => + w is MeshSegmentLabel && + w.text == rL10n.repeater_clockSyncDefault, + ), + findsOneWidget, + ); + + FlutterError.onError = previous; + expect(overflows, isEmpty, reason: overflows.join('\n')); + }, + ); + } } From 723fa18b68fe793f301d5ff7e62f83635895a3e8 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:51:35 -0700 Subject: [PATCH 22/50] Enforce flood threshold in retry and path-prep selection Ensure MessageRetryService forces flood once the attempt reaches floodFromAttempt even if a selector returns null, and pass SendAttemptPlan.floodFromAttempt from preparePathForContactSend so zero-budget plans keep the saved path. --- lib/connector/meshcore_connector.dart | 19 +- lib/services/message_retry_service.dart | 11 +- test/connector/flood_only_attempt_test.dart | 173 +++++++++++++++++- .../message_retry_split_limits_test.dart | 118 ++++++++++++ 4 files changed, 308 insertions(+), 13 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 9bcf9075..c92af3fc 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5466,16 +5466,21 @@ class MeshCoreConnector extends ChangeNotifier { Future preparePathForContactSend(Contact contact) async { PathSelection? autoSelection; - final autoRotationEnabled = - _appSettingsService?.settings.autoRouteRotationEnabled == true; - if (autoRotationEnabled && contact.pathOverride == null) { - final directRetries = - _appSettingsService?.settings.directRetries ?? - SendAttemptPlan.defaultDirectRetries; + final settings = _appSettingsService?.settings; + final plan = SendAttemptPlan( + directRetries: + settings?.directRetries ?? SendAttemptPlan.defaultDirectRetries, + floodRetries: + settings?.floodRetries ?? SendAttemptPlan.defaultFloodRetries, + rotateRoutes: + settings?.autoRouteRotationEnabled == true && + contact.pathOverride == null, + ); + if (plan.rotateRoutes) { autoSelection = _selectAutoPathForAttempt( contact.publicKeyHex, attemptIndex: 0, - directRetries: directRetries, + directRetries: plan.floodFromAttempt ?? (1 << 30), ); } diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 835facdb..8a1c2085 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -330,15 +330,22 @@ class MessageRetryService extends ChangeNotifier { return null; } + final floodFrom = plan.floodFromAttempt; final recentSelections = List.from( _attemptPathHistory[message.messageId] ?? const [], ); - return config.selectRetryPath!( + final selection = config.selectRetryPath!( contact.publicKeyHex, message.retryCount, - plan.floodFromAttempt ?? (1 << 30), + floodFrom ?? (1 << 30), recentSelections, ); + if (floodFrom != null && message.retryCount >= floodFrom) { + return selection != null && selection.useFlood + ? selection + : const PathSelection(pathBytes: [], hopCount: -1, useFlood: true); + } + return selection; } void _recordAttemptPathHistory(String messageId, PathSelection selection) { diff --git a/test/connector/flood_only_attempt_test.dart b/test/connector/flood_only_attempt_test.dart index f436c53b..57924e0b 100644 --- a/test/connector/flood_only_attempt_test.dart +++ b/test/connector/flood_only_attempt_test.dart @@ -1,10 +1,15 @@ +import 'dart:async'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/path_history.dart'; +import 'package:meshcore_open/models/path_selection.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/services/message_retry_service.dart'; import 'package:meshcore_open/services/path_history_service.dart'; @@ -22,21 +27,68 @@ Contact _directContact() { ); } +class _ControllablePathStorage extends StorageService { + Completer? loadGate; + + @override + Future loadPathHistory(String contactPubKeyHex) { + final gate = loadGate; + if (gate != null && !gate.isCompleted) { + return gate.future; + } + return Future.value(null); + } +} + +class _RecordingReviewRadio extends ReviewRadio { + final List sent = []; + + _RecordingReviewRadio() + : super( + scheduledMessageInterval: const Duration(hours: 1), + // Long ACK delay so retry attempts run on timeout in tests. + ackDelay: const Duration(hours: 1), + ); + + @override + void handle(Uint8List frame) { + sent.add(frame); + super.handle(frame); + } +} + +Future _waitFor(bool Function() condition, {int seconds = 8}) async { + final end = DateTime.now().add(Duration(seconds: seconds)); + while (!condition()) { + if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); + await Future.delayed(const Duration(milliseconds: 25)); + } +} + +// NotificationService is a process-wide singleton whose reply stream can be +// listened to once, so every test shares one connector and reconnects it to a +// fresh radio. void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late MeshCoreConnector connector; + late _ControllablePathStorage storage; late PathHistoryService history; late MessageRetryService retries; late AppSettingsService settings; - setUp(() async { + setUpAll(() async { SharedPreferences.setMockInitialValues({}); PrefsManager.reset(); await PrefsManager.initialize(); settings = AppSettingsService(); await settings.loadSettings(); connector = MeshCoreConnector(); - history = PathHistoryService(StorageService()); - retries = MessageRetryService(); + storage = _ControllablePathStorage(); + history = PathHistoryService(storage); + retries = MessageRetryService( + sentWatchdogGrace: const Duration(milliseconds: 5), + ); connector.initialize( retryService: retries, pathHistoryService: history, @@ -44,12 +96,17 @@ void main() { ); }); - tearDown(() { + tearDownAll(() { connector.dispose(); history.dispose(); retries.dispose(); }); + setUp(() async { + storage.loadGate = null; + await settings.resetRoutingSettingsToDefault(); + }); + test('flood attempts do not wait for route history', () async { await settings.updateSettings( settings.settings.copyWith( @@ -69,5 +126,113 @@ void main() { expect(direct.useFlood, isFalse); expect(direct.hopCount, 1); expect(direct.pathBytes, [0x11]); + + await settings.updateSettings( + settings.settings.copyWith(directRetries: 0, floodRetries: 0), + ); + final zeroBudget = await connector.preparePathForContactSend( + _directContact(), + ); + expect(zeroBudget.useFlood, isFalse); + expect(zeroBudget.hopCount, 1); + expect(zeroBudget.pathBytes, [0x11]); }); + + test( + 'sendMessage with directRetries 0 and floodRetries 1 floods even when route history is loading', + () async { + final gate = Completer(); + storage.loadGate = gate; + + final radio = _RecordingReviewRadio(); + connector.reviewRadioFactoryForTest = () => radio; + await connector.connectReview(); + addTearDown(connector.disconnect); + await _waitFor(() => connector.contacts.isNotEmpty); + + final directContact = connector.contacts.firstWhere( + (c) => c.pathLength > 0, + ); + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: true, + directRetries: 0, + floodRetries: 1, + ), + ); + + radio.sent.clear(); + await connector.sendMessage(directContact, 'flood only'); + await _waitFor( + () => radio.sent.any((frame) => frame[0] == cmdSendTxtMsg), + ); + + final opCodes = radio.sent + .map((frame) => frame[0]) + .where( + (code) => + code == cmdResetPath || + code == cmdAddUpdateContact || + code == cmdSendTxtMsg, + ) + .toList(); + expect(opCodes, [cmdResetPath, cmdSendTxtMsg]); + + gate.complete(null); + storage.loadGate = null; + }, + ); + + test( + 'sendMessage with directRetries > 0 rotates through cached paths before flooding', + () async { + final radio = _RecordingReviewRadio(); + connector.reviewRadioFactoryForTest = () => radio; + await connector.connectReview(); + addTearDown(connector.disconnect); + await _waitFor(() => connector.contacts.isNotEmpty); + + final directContact = connector.contacts.firstWhere( + (c) => c.pathLength > 0, + ); + history.recordPathResult( + directContact.publicKeyHex, + const PathSelection(pathBytes: [0x22], hopCount: 1, useFlood: false), + success: true, + ); + await pumpEventQueue(); + history.recordPathResult( + directContact.publicKeyHex, + const PathSelection(pathBytes: [0x33], hopCount: 1, useFlood: false), + success: true, + ); + await pumpEventQueue(); + + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: true, + directRetries: 2, + floodRetries: 1, + ), + ); + + radio.sent.clear(); + await connector.sendMessage(directContact, 'rotate then flood'); + await _waitFor( + () => + radio.sent.where((frame) => frame[0] == cmdSendTxtMsg).length == 3, + seconds: 25, + ); + + final pathOps = radio.sent + .where( + (frame) => + frame[0] == cmdResetPath || frame[0] == cmdAddUpdateContact, + ) + .map((frame) => frame[0]) + .toList(); + expect(pathOps, [cmdAddUpdateContact, cmdAddUpdateContact, cmdResetPath]); + }, + timeout: const Timeout(Duration(seconds: 45)), + ); } diff --git a/test/services/message_retry_split_limits_test.dart b/test/services/message_retry_split_limits_test.dart index f2fdcc4d..3165e3c2 100644 --- a/test/services/message_retry_split_limits_test.dart +++ b/test/services/message_retry_split_limits_test.dart @@ -165,4 +165,122 @@ void main() { expect(sends, [0]); expect(latest.last.status, MessageStatus.failed); }); + + test( + 'flood-only rotation floods saved direct contact even if selector returns null', + () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: true, + directRetries: 0, + floodRetries: 1, + ), + ); + + final service = MessageRetryService( + sentWatchdogGrace: const Duration(milliseconds: 5), + ); + addTearDown(service.dispose); + final latest = []; + final sends = []; + var clearedCount = 0; + var setPathCount = 0; + service.initialize( + RetryServiceConfig( + sendMessage: (_, _, attempt, _) async { + sends.add(attempt); + }, + addMessage: (_, message) => latest.add(message), + updateMessage: (message) => latest.add(message), + clearContactPath: (_) async { + clearedCount++; + }, + setContactPath: (_, _, _) async { + setPathCount++; + }, + calculateTimeout: + (_, _, {String? contactKey, int? deviceTimeoutMs}) => 15, + appSettingsService: settings, + selectRetryPath: (_, _, _, _) => null, + ), + ); + + await service.sendMessageWithRetry( + contact: _contact(pathLength: 1, path: const [0x11]), + text: 'hello', + ); + await pumpEventQueue(); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(sends, [0]); + expect(clearedCount, 1); + expect(setPathCount, 0); + expect(latest.last.pathLength, -1); + expect(latest.last.pathBytes, isEmpty); + expect(latest.last.status, MessageStatus.failed); + }, + ); + + test( + 'rotation with direct attempts > 0 tries direct paths before flooding', + () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith( + autoRouteRotationEnabled: true, + directRetries: 2, + floodRetries: 1, + ), + ); + + final service = MessageRetryService( + sentWatchdogGrace: const Duration(milliseconds: 5), + ); + addTearDown(service.dispose); + final actions = []; + final sends = []; + service.initialize( + RetryServiceConfig( + sendMessage: (_, _, attempt, _) async { + sends.add(attempt); + }, + addMessage: (_, _) {}, + updateMessage: (_) {}, + clearContactPath: (_) async => actions.add('flood'), + setContactPath: (_, bytes, _) async => + actions.add('direct:${bytes.join(',')}'), + calculateTimeout: + (_, _, {String? contactKey, int? deviceTimeoutMs}) => 15, + appSettingsService: settings, + selectRetryPath: (_, attemptIndex, directRetries, _) { + if (attemptIndex >= directRetries) return null; + return attemptIndex == 0 + ? const PathSelection( + pathBytes: [0x22], + hopCount: 1, + useFlood: false, + ) + : const PathSelection( + pathBytes: [0x33], + hopCount: 1, + useFlood: false, + ); + }, + ), + ); + + await service.sendMessageWithRetry( + contact: _contact(pathLength: 1, path: const [0x11]), + text: 'hello', + ); + await pumpEventQueue(); + await Future.delayed(const Duration(milliseconds: 3500)); + + expect(sends, [0, 1, 2]); + expect(actions, ['direct:34', 'direct:51', 'flood']); + }, + ); } From aa621526ecbfc9bd1aa5f7e11e748f48a1a7c565 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:09:48 -0700 Subject: [PATCH 23/50] Keep composer focus-intent tracking local to chat screens --- lib/helpers/composer_focus_intent.dart | 52 -------- lib/screens/channel_chat_screen.dart | 35 +++-- lib/screens/chat_screen.dart | 34 +++-- test/helpers/composer_focus_intent_test.dart | 78 ----------- .../channel_chat_selection_scroll_test.dart | 8 ++ .../chat_app_switch_keyboard_test.dart | 126 +++++++++++++++++- 6 files changed, 181 insertions(+), 152 deletions(-) delete mode 100644 lib/helpers/composer_focus_intent.dart delete mode 100644 test/helpers/composer_focus_intent_test.dart diff --git a/lib/helpers/composer_focus_intent.dart b/lib/helpers/composer_focus_intent.dart deleted file mode 100644 index baa698db..00000000 --- a/lib/helpers/composer_focus_intent.dart +++ /dev/null @@ -1,52 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/widgets.dart'; - -/// Tells the user focusing the chat composer apart from Flutter handing focus -/// back after an app switch or after a sheet, dialog or menu closes. -/// -/// On desktop and web the focus manager takes focus off the composer when the -/// window goes inactive and puts it back on resume. That is not the user -/// starting to type, so the chat must not jump to the newest message and lose -/// the reading position. Mobile keeps focus across an app switch. On every -/// platform a sheet, dialog or menu opened over the chat takes focus and the -/// composer gets it back when that closes, which is not a tap either. -class ComposerFocusIntent with WidgetsBindingObserver { - ComposerFocusIntent() { - WidgetsBinding.instance.addObserver(this); - } - - bool _lostWhileAway = false; - bool _lostToRoute = false; - - /// Call from the composer focus node's listener. Returns true when focus - /// was just gained by a tap or by app code, false for a loss of focus or a - /// focus restored on resume or when a route on top closes. - /// - /// [coveredByRoute] is whether the chat's route is no longer the current - /// one (a sheet, dialog or menu is open on top). - bool isUserFocusGain(bool hasFocus, {bool coveredByRoute = false}) { - if (!hasFocus) { - final state = WidgetsBinding.instance.lifecycleState; - _lostWhileAway = state != null && state != AppLifecycleState.resumed; - _lostToRoute = coveredByRoute; - return false; - } - final restored = _lostWhileAway || _lostToRoute; - _lostWhileAway = false; - _lostToRoute = false; - return !restored; - } - - @override - void didChangeAppLifecycleState(AppLifecycleState state) { - if (state != AppLifecycleState.resumed) return; - // The focus manager observes the lifecycle from app start, so its restore - // is already queued and runs first. Clearing afterwards keeps a focus - // that was not restored (the user clicked elsewhere) from swallowing the - // next real tap on the composer. - scheduleMicrotask(() => _lostWhileAway = false); - } - - void dispose() => WidgetsBinding.instance.removeObserver(this); -} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 4255146e..0702f3a1 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -16,7 +16,6 @@ import '../storage/community_store.dart'; import '../utils/platform_info.dart'; import '../helpers/chat_jump.dart'; import '../helpers/chat_scroll_controller.dart'; -import '../helpers/composer_focus_intent.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/gif_helper.dart'; @@ -100,13 +99,15 @@ class ChannelChatScreen extends StatefulWidget { State createState() => _ChannelChatScreenState(); } -class _ChannelChatScreenState extends State { +class _ChannelChatScreenState extends State + with WidgetsBindingObserver { final _holidayWatcher = HolidayTriggerWatcher(); final _messageAreaKey = GlobalKey(); final TextEditingController _textController = TextEditingController(); final ChatScrollController _scrollController = ChatScrollController(); final FocusNode _textFieldFocusNode = FocusNode(); - final _composerFocusIntent = ComposerFocusIntent(); + bool _focusLostWhileAway = false; + bool _focusLostToRoute = false; ChannelMessage? _replyingToMessage; bool _useReplyRegion = false; final CommunityStore _communityStore = CommunityStore(); @@ -182,6 +183,7 @@ class _ChannelChatScreenState extends State { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); _textFieldFocusNode.addListener(_onTextFieldFocusChange); _scrollController.onScrollNearTop = _loadOlderMessages; _scrollController.showJumpToBottom.addListener(_clearDividerAtBottom); @@ -272,13 +274,28 @@ class _ChannelChatScreenState extends State { } } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) return; + // The focus manager observes the lifecycle from app start, so its restore + // is already queued and runs first. Clearing afterwards keeps a focus + // that was not restored (the user clicked elsewhere) from swallowing the + // next real tap on the composer. + scheduleMicrotask(() => _focusLostWhileAway = false); + } + void _onTextFieldFocusChange() { if (!mounted) return; - final userFocus = _composerFocusIntent.isUserFocusGain( - _textFieldFocusNode.hasFocus, - coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true), - ); - if (userFocus) _scrollController.handleKeyboardOpen(); + if (!_textFieldFocusNode.hasFocus) { + final state = WidgetsBinding.instance.lifecycleState; + _focusLostWhileAway = state != null && state != AppLifecycleState.resumed; + _focusLostToRoute = !(ModalRoute.of(context)?.isCurrent ?? true); + return; + } + final restored = _focusLostWhileAway || _focusLostToRoute; + _focusLostWhileAway = false; + _focusLostToRoute = false; + if (!restored) _scrollController.handleKeyboardOpen(); } Future _loadOlderMessages() async { @@ -359,12 +376,12 @@ class _ChannelChatScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); _watchedImageStore?.removeListener(_onImageStoreChanged); _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); - _composerFocusIntent.dispose(); _textFieldFocusNode.dispose(); _textController.dispose(); _searchController.dispose(); diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 6e3c0d05..617b44c4 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -22,7 +22,6 @@ import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; import '../helpers/chat_scroll_anchor.dart'; import '../helpers/chat_scroll_controller.dart'; -import '../helpers/composer_focus_intent.dart'; import '../helpers/gif_helper.dart'; import '../helpers/ipfs_link_attach_flow.dart'; import '../helpers/contact_share_message.dart'; @@ -92,7 +91,7 @@ class ChatScreen extends StatefulWidget { State createState() => _ChatScreenState(); } -class _ChatScreenState extends State { +class _ChatScreenState extends State with WidgetsBindingObserver { final _holidayWatcher = HolidayTriggerWatcher(); final _messageAreaKey = GlobalKey(); final _textController = TextEditingController(); @@ -100,7 +99,8 @@ class _ChatScreenState extends State { final _scrollAnchor = ChatScrollAnchor(); ({String id, bool bookmarksOnly})? _newestRow; final _textFieldFocusNode = FocusNode(); - final _composerFocusIntent = ComposerFocusIntent(); + bool _focusLostWhileAway = false; + bool _focusLostToRoute = false; final GlobalKey _unreadScrollKey = GlobalKey(); bool _isLoadingOlder = false; bool _showBookmarkedOnly = false; @@ -156,6 +156,7 @@ class _ChatScreenState extends State { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); _textFieldFocusNode.addListener(_onTextFieldFocusChange); _scrollController.onScrollNearTop = _loadOlderMessages; _scrollController.showJumpToBottom.addListener(_clearDividerAtBottom); @@ -223,13 +224,28 @@ class _ChatScreenState extends State { } } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) return; + // The focus manager observes the lifecycle from app start, so its restore + // is already queued and runs first. Clearing afterwards keeps a focus + // that was not restored (the user clicked elsewhere) from swallowing the + // next real tap on the composer. + scheduleMicrotask(() => _focusLostWhileAway = false); + } + void _onTextFieldFocusChange() { if (!mounted) return; - final userFocus = _composerFocusIntent.isUserFocusGain( - _textFieldFocusNode.hasFocus, - coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true), - ); - if (userFocus) _scrollController.handleKeyboardOpen(); + if (!_textFieldFocusNode.hasFocus) { + final state = WidgetsBinding.instance.lifecycleState; + _focusLostWhileAway = state != null && state != AppLifecycleState.resumed; + _focusLostToRoute = !(ModalRoute.of(context)?.isCurrent ?? true); + return; + } + final restored = _focusLostWhileAway || _focusLostToRoute; + _focusLostWhileAway = false; + _focusLostToRoute = false; + if (!restored) _scrollController.handleKeyboardOpen(); } Future _loadOlderMessages() async { @@ -246,11 +262,11 @@ class _ChatScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); - _composerFocusIntent.dispose(); _textFieldFocusNode.dispose(); _textController.dispose(); _searchController.dispose(); diff --git a/test/helpers/composer_focus_intent_test.dart b/test/helpers/composer_focus_intent_test.dart deleted file mode 100644 index e1705d42..00000000 --- a/test/helpers/composer_focus_intent_test.dart +++ /dev/null @@ -1,78 +0,0 @@ -import 'package:flutter/widgets.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:meshcore_open/helpers/composer_focus_intent.dart'; - -void _setLifecycle(WidgetTester tester, List states) { - for (final state in states) { - tester.binding.handleAppLifecycleStateChanged(state); - } -} - -const _away = [ - AppLifecycleState.inactive, - AppLifecycleState.hidden, - AppLifecycleState.paused, -]; -const _back = [ - AppLifecycleState.hidden, - AppLifecycleState.inactive, - AppLifecycleState.resumed, -]; - -void main() { - testWidgets('focus gained while in the foreground is user focus', ( - tester, - ) async { - final intent = ComposerFocusIntent(); - addTearDown(intent.dispose); - - expect(intent.isUserFocusGain(true), isTrue); - expect(intent.isUserFocusGain(false), isFalse); - expect(intent.isUserFocusGain(true), isTrue); - }); - - testWidgets('focus lost while away and given back on resume is not', ( - tester, - ) async { - final intent = ComposerFocusIntent(); - addTearDown(intent.dispose); - - expect(intent.isUserFocusGain(true), isTrue); - _setLifecycle(tester, _away.sublist(0, 1)); - expect(intent.isUserFocusGain(false), isFalse); - _setLifecycle(tester, [..._away.sublist(1), ..._back]); - // The restore lands before the resume microtask clears the flag. - expect(intent.isUserFocusGain(true), isFalse); - // The next tap counts again. - expect(intent.isUserFocusGain(false), isFalse); - expect(intent.isUserFocusGain(true), isTrue); - }); - - testWidgets('focus not restored on resume does not swallow the next tap', ( - tester, - ) async { - final intent = ComposerFocusIntent(); - addTearDown(intent.dispose); - - _setLifecycle(tester, _away.sublist(0, 1)); - expect(intent.isUserFocusGain(false), isFalse); - _setLifecycle(tester, [..._away.sublist(1), ..._back]); - await tester.pump(); // Resume microtasks run; nothing restored focus. - - expect(intent.isUserFocusGain(true), isTrue); - }); - - testWidgets('focus given back when a sheet or dialog closes is not', ( - tester, - ) async { - final intent = ComposerFocusIntent(); - addTearDown(intent.dispose); - - expect(intent.isUserFocusGain(true), isTrue); - expect(intent.isUserFocusGain(false, coveredByRoute: true), isFalse); - expect(intent.isUserFocusGain(true), isFalse); - // Losing focus with nothing on top, then tapping, counts again. - expect(intent.isUserFocusGain(false), isFalse); - expect(intent.isUserFocusGain(true), isTrue); - }); -} diff --git a/test/screens/channel_chat_selection_scroll_test.dart b/test/screens/channel_chat_selection_scroll_test.dart index 39c12447..0aaa4143 100644 --- a/test/screens/channel_chat_selection_scroll_test.dart +++ b/test/screens/channel_chat_selection_scroll_test.dart @@ -85,6 +85,14 @@ void main() { expect(find.byTooltip('Clear selection'), findsNothing); expect(_position(tester).pixels, 600); + // Losing focus with nothing on top, then tapping the composer, still jumps + // to the newest message. + FocusManager.instance.primaryFocus?.unfocus(); + await _settle(tester); + await tester.tap(find.byType(TextField).last); + await _settle(tester); + expect(_position(tester).pixels, 0); + await _tearDown(tester); }); diff --git a/test/screens/chat_app_switch_keyboard_test.dart b/test/screens/chat_app_switch_keyboard_test.dart index f586ad68..e6061787 100644 --- a/test/screens/chat_app_switch_keyboard_test.dart +++ b/test/screens/chat_app_switch_keyboard_test.dart @@ -9,10 +9,12 @@ import 'package:provider/single_child_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/review_mode/review_frames.dart'; import 'package:meshcore_open/review_mode/review_radio.dart'; import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; import 'package:meshcore_open/services/app_debug_log_service.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/services/ble_debug_log_service.dart'; @@ -140,6 +142,90 @@ void main() { await _tearDown(tester); }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); + + testWidgets( + 'desktop app switch when focus is not restored does not swallow the next tap', + (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpChannelChat(tester); + await tester.tap(_composerField); + await _settle(tester); + _list(tester).jumpTo(300); + await _settle(tester); + + _goBackground(tester); + await tester.pump(); + expect(_composer(tester).focusNode.hasFocus, isFalse); + // User returns and interacts elsewhere (e.g. opens search) so focus is + // not restored to the composer on resume. + await tester.tap(find.byIcon(Icons.search)); + await tester.pump(); + _goForeground(tester); + await _settle(tester); + await tester.tap(find.byIcon(Icons.arrow_back)); + await _settle(tester); + + expect(_composer(tester).focusNode.hasFocus, isFalse); + expect(_list(tester).position.pixels, closeTo(300, 1)); + + await tester.tap(_composerField); + await _settle(tester); + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_list(tester).position.pixels, 0); + + await _tearDown(tester); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets( + 'DM chat: desktop app switch and dialog close keep reading position', + (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpDirectChat(tester); + await tester.tap(_composerField); + await _settle(tester); + _list(tester).jumpTo(300); + await _settle(tester); + + // App switch away and back restores focus without jumping to bottom. + _goBackground(tester); + await tester.pump(); + expect(_composer(tester).focusNode.hasFocus, isFalse); + _goForeground(tester); + await _settle(tester); + + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_list(tester).position.pixels, closeTo(300, 1)); + + // Opening and closing a dialog over the chat returns focus without jumping. + await tester.tap(find.byIcon(Icons.more_vert)); + await _settle(tester); + await tester.tap(find.byIcon(Icons.info_outline)); + await _settle(tester); + expect(find.byType(AlertDialog), findsOneWidget); + Navigator.of(tester.element(find.byType(AlertDialog))).pop(); + await _settle(tester); + + expect(_list(tester).position.pixels, closeTo(300, 1)); + + // Losing focus in the foreground and tapping again still jumps to bottom. + _composer(tester).focusNode.unfocus(); + await _settle(tester); + await tester.tap(_composerField); + await _settle(tester); + expect(_list(tester).position.pixels, 0); + + await _tearDown(tester); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); } final _composerField = find.descendant( @@ -170,8 +256,9 @@ void _goForeground(WidgetTester tester) { } } -ScrollController _list(WidgetTester tester) => - tester.widget(find.byType(ListView).first).controller!; +ScrollController _list(WidgetTester tester) => tester + .widget(find.byWidgetPredicate((w) => w is ListView).first) + .controller!; double _composerBottom(WidgetTester tester) => tester.getBottomLeft(find.byType(ChatComposer)).dy; @@ -191,6 +278,38 @@ Future _tearDown(WidgetTester tester) async { Future _pumpChannelChat(WidgetTester tester) async { final (connector, providers) = _shared ??= await _connect(tester); + await _pumpScreen( + tester, + providers, + ChannelChatScreen(channel: connector.channels[0]), + ); + return connector; +} + +Future _pumpDirectChat(WidgetTester tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat); + if (connector.getMessages(contact).length < 40) { + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Direct history line $i about the weather on the hill', + timestampSecs: now - 4000 + i, + ), + ); + } + } + await _pumpScreen(tester, providers, ChatScreen(contact: contact)); + return connector; +} + +Future _pumpScreen( + WidgetTester tester, + List providers, + Widget screen, +) async { await tester.pumpWidget( MultiProvider( providers: providers, @@ -204,12 +323,11 @@ Future _pumpChannelChat(WidgetTester tester) async { GlobalCupertinoLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, - home: ChannelChatScreen(channel: connector.channels[0]), + home: screen, ), ), ); await _settle(tester); - return connector; } Future<(MeshCoreConnector, List)> _connect( From f85dbee51e3480b0a0086a5dc8739be47eae41e0 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:31:55 -0700 Subject: [PATCH 24/50] Scroll path editor sheet whenever pinned fields cannot fit --- lib/widgets/path_editor_sheet.dart | 234 ++++++++++++----------- test/widgets/path_editor_sheet_test.dart | 199 +++++++++++++++++-- 2 files changed, 300 insertions(+), 133 deletions(-) diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 6cc623df..443e2dc4 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -72,6 +72,8 @@ class _PathEditorSheetState extends State { final List<_Hop> _hops = []; final _hexController = TextEditingController(); + final _hexFocus = FocusNode(); + final _searchFocus = FocusNode(); final _hopScroll = ScrollController(); String? _hexError; bool _syncingHex = false; @@ -96,6 +98,8 @@ class _PathEditorSheetState extends State { void dispose() { _highlightTimer?.cancel(); _hopScroll.dispose(); + _hexFocus.dispose(); + _searchFocus.dispose(); _hexController.dispose(); super.dispose(); } @@ -353,13 +357,10 @@ class _PathEditorSheetState extends State { /// measured band between the title and the action buttons. /// /// An invalid hex path grows the error text. That growth comes out of the - /// hop viewport first, keeping one row when it fits, and the error itself - /// scrolls inside its own box instead of overflowing the sheet. - /// - /// [scroll] is set when that band is shorter than the search field, which - /// happens when a landscape keyboard leaves only the header and the action - /// buttons. The pinned column would overflow, so the caller lays the same - /// blocks out in one scroll view instead. + /// hop viewport first, keeping one row when it fits. When even one hop row, + /// the hex field with any active error, and the search field cannot fit, + /// [scroll] switches the middle band to a single scroll view so nothing is + /// crushed or overflows and all controls stay reachable. ({double hop, double hex, double search, bool scroll}) _middleBudget( double space, bool compact, @@ -368,53 +369,31 @@ class _PathEditorSheetState extends State { final row = compact ? scaler.scale(56).clamp(56.0, 96.0) : scaler.scale(76).clamp(72.0, 140.0); - final gaps = compact ? 16.0 : 40.0; + final minRepeater = compact ? 56.0 : 80.0; final searchH = scaler.scale(compact ? 48 : 56) + 20; final baseHex = scaler.scale(compact ? 48 : 64) + (compact ? 16 : 44); final errorExtra = _hexError == null ? 0.0 - : scaler.scale(compact ? 36 : 48); + : scaler.scale(compact ? 56 : 52); final wantedHop = _hops.isEmpty ? math.min(scaler.scale(compact ? 64 : 80), 140.0) : math.min(_hops.length, compact ? 2 : 3) * row + 4; final wantedHex = baseHex + errorExtra; - final minHop = _hops.isEmpty - ? 0.0 - : math.min(row, math.max(0.0, space - gaps)); + final minHop = _hops.isEmpty ? 0.0 : row; + final scroll = minHop + wantedHex + searchH > space; var hopH = wantedHop; - var hexH = wantedHex; - final used = hopH + hexH + searchH + gaps; - if (used > space) { - var overflow = used - space; - final hopCut = math.min(overflow, math.max(0.0, hopH - minHop)); - hopH -= hopCut; - overflow -= hopCut; - if (overflow > 0) { - final hexFloor = math.min( - baseHex, - math.max(0.0, space - searchH - gaps - hopH), - ); - final hexCut = math.min(overflow, math.max(0.0, hexH - hexFloor)); - hexH -= hexCut; - overflow -= hexCut; - } - if (overflow > 0) { - hopH = math.max(0.0, hopH - overflow); + if (!scroll) { + final targetMax = math.max( + minHop + wantedHex + searchH, + space - minRepeater, + ); + final used = hopH + wantedHex + searchH; + if (used > targetMax) { + hopH -= math.min(used - targetMax, math.max(0.0, hopH - minHop)); } } - hopH = math.max(0.0, hopH); - hexH = math.max(0.0, hexH); - // The search field stays at its full height in the pinned column. When - // the band cannot hold it, scrolling is the only way to reach it and the - // repeater list. - final scroll = hopH + hexH + searchH > space; - return ( - hop: scroll ? wantedHop : hopH, - hex: scroll ? wantedHex : hexH, - search: searchH, - scroll: scroll, - ); + return (hop: hopH, hex: wantedHex, search: searchH, scroll: scroll); } Widget _hopViewport(bool compact, double height) { @@ -479,6 +458,7 @@ class _PathEditorSheetState extends State { TextField( key: const Key('path-editor-hex-field'), controller: _hexController, + focusNode: _hexFocus, onChanged: _onHexChanged, textCapitalization: TextCapitalization.characters, style: MeshTheme.mono(fontSize: 14), @@ -509,6 +489,7 @@ class _PathEditorSheetState extends State { padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0), child: TextField( key: const Key('path-editor-search-field'), + focusNode: _searchFocus, onChanged: (value) => setState(() => _search = value), scrollPadding: EdgeInsets.zero, decoration: InputDecoration( @@ -549,6 +530,42 @@ class _PathEditorSheetState extends State { ); } + List _middleSlivers({ + required bool compact, + required List repeaters, + }) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return [ + SliverToBoxAdapter(child: _scrollHopBlock(compact)), + SliverToBoxAdapter(child: _scrollHexBlock(compact)), + SliverToBoxAdapter(child: _scrollSearchBlock(compact)), + if (repeaters.isEmpty) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Text( + l10n.path_noRepeatersFound, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ) + else + SliverPadding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + sliver: SliverList.builder( + key: const Key('path-editor-repeater-list'), + itemCount: repeaters.length, + itemBuilder: (context, index) => + _repeaterTile(context, repeaters[index]), + ), + ), + ]; + } + /// One scrollable for the hop list, hex field, search field, and repeaters. /// /// The blocks are intrinsic height with no nested scrolling, so a drag @@ -558,39 +575,10 @@ class _PathEditorSheetState extends State { required bool compact, required List repeaters, }) { - final l10n = context.l10n; - final theme = Theme.of(context); - final scheme = theme.colorScheme; return CustomScrollView( key: const Key('path-editor-scroll-fallback'), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - slivers: [ - SliverToBoxAdapter(child: _scrollHopBlock(compact)), - SliverToBoxAdapter(child: _scrollHexBlock(compact)), - SliverToBoxAdapter(child: _scrollSearchBlock(compact)), - if (repeaters.isEmpty) - SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), - child: Text( - l10n.path_noRepeatersFound, - style: theme.textTheme.bodyMedium?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ), - ) - else - SliverPadding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), - sliver: SliverList.builder( - key: const Key('path-editor-repeater-list'), - itemCount: repeaters.length, - itemBuilder: (context, index) => - _repeaterTile(context, repeaters[index]), - ), - ), - ], + slivers: _middleSlivers(compact: compact, repeaters: repeaters), ); } @@ -649,6 +637,7 @@ class _PathEditorSheetState extends State { TextField( key: const Key('path-editor-hex-field'), controller: _hexController, + focusNode: _hexFocus, onChanged: _onHexChanged, textCapitalization: TextCapitalization.characters, style: MeshTheme.mono(fontSize: 14), @@ -676,6 +665,7 @@ class _PathEditorSheetState extends State { padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0), child: TextField( key: const Key('path-editor-search-field'), + focusNode: _searchFocus, onChanged: (value) => setState(() => _search = value), scrollPadding: EdgeInsets.zero, decoration: InputDecoration( @@ -701,16 +691,67 @@ class _PathEditorSheetState extends State { // Phone sheets and a keyboard-shrunk window use the shorter hop rows // so the action buttons stay below the repeater list. final compact = maxHeight < 680; + final scaler = MediaQuery.textScalerOf(context); + final header = Semantics( + liveRegion: true, + child: BottomSheetHeader( + title: l10n.pathEditor_title, + subtitle: l10n.pathEditor_hopCounter(_hops.length), + ), + ); + final actions = SafeArea( + top: false, + child: Padding( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 4 : 8, + 16, + compact ? 4 : 16, + ), + child: Row( + children: [ + Expanded( + child: TextButton( + style: TextButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: _hexError != null ? null : _save, + child: Text(l10n.pathEditor_usePath), + ), + ), + ], + ), + ), + ); + + // When scaled header and action buttons leave less than one row for + // the middle band, scroll the whole sheet so nothing clips or crowds + // the viewport. + if (maxHeight < scaler.scale(150) + 28) { + return CustomScrollView( + key: const Key('path-editor-scroll-fallback'), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + slivers: [ + SliverToBoxAdapter(child: header), + ..._middleSlivers(compact: compact, repeaters: repeaters), + SliverToBoxAdapter(child: actions), + ], + ); + } return Column( children: [ - Semantics( - liveRegion: true, - child: BottomSheetHeader( - title: l10n.pathEditor_title, - subtitle: l10n.pathEditor_hopCounter(_hops.length), - ), - ), + header, Expanded( child: LayoutBuilder( builder: (context, inner) { @@ -732,40 +773,7 @@ class _PathEditorSheetState extends State { }, ), ), - SafeArea( - top: false, - child: Padding( - padding: EdgeInsets.fromLTRB( - 16, - compact ? 4 : 8, - 16, - compact ? 4 : 16, - ), - child: Row( - children: [ - Expanded( - child: TextButton( - style: TextButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_cancel), - ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - style: FilledButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: _hexError != null ? null : _save, - child: Text(l10n.pathEditor_usePath), - ), - ), - ], - ), - ), - ), + actions, ], ); }, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index 29aa1ee8..d94e90b1 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -35,6 +35,7 @@ Future _pumpSheet( WidgetTester tester, { Size size = const Size(400, 700), double keyboard = 0, + double textScale = 1.0, List initialPath = const [], }) async { tester.view.physicalSize = size; @@ -49,12 +50,14 @@ Future _pumpSheet( data: MediaQueryData( size: size, viewInsets: EdgeInsets.only(bottom: keyboard), + textScaler: TextScaler.linear(textScale), ), child: Scaffold( body: SizedBox( width: size.width, height: size.height - keyboard, child: PathEditorSheet( + key: UniqueKey(), availableContacts: _contacts, initialPath: initialPath, pathHashByteWidth: 2, @@ -67,6 +70,24 @@ Future _pumpSheet( await tester.pumpAndSettle(); } +Finder _fallbackScrollable() { + return find.byElementPredicate((element) { + if (element.widget is! Scrollable) return false; + var hasHex = false; + void visit(Element node) { + node.visitChildren((child) { + if (child.widget.key == const Key('path-editor-hex-field')) { + hasHex = true; + } + visit(child); + }); + } + + visit(element); + return hasHex; + }); +} + Future _revealInFallback( WidgetTester tester, Finder scrollable, @@ -76,10 +97,11 @@ Future _revealInFallback( final view = tester.getRect( find.byKey(const Key('path-editor-scroll-fallback')), ); - for (var i = 0; i < 40; i++) { + final step = (view.height / 2).clamp(2.0, 24.0); + for (var i = 0; i < 400; i++) { final rect = tester.getRect(target); if (rect.center.dy >= view.top && rect.center.dy <= view.bottom) return; - final next = (state.position.pixels + 48).clamp( + final next = (state.position.pixels + step).clamp( 0.0, state.position.maxScrollExtent, ); @@ -87,7 +109,9 @@ Future _revealInFallback( state.position.jumpTo(next); await tester.pump(); } - fail('Could not scroll $target into the path sheet'); + fail( + 'Could not scroll $target into $view (last rect=${tester.getRect(target)}, pixels=${state.position.pixels})', + ); } List _repeaterNames(WidgetTester tester) { @@ -215,6 +239,61 @@ void main() { expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); }); + testWidgets( + '3-line hex error on a 320px keyboard sheet keeps controls scrollable', + (tester) async { + await _pumpSheet( + tester, + size: const Size(390, 640), + keyboard: 320, + initialPath: [0x60, 0x60, 0x11, 0x22], + ); + await tester.enterText( + find.byKey(const Key('path-editor-hex-field')), + 'AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK', + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect( + find.byKey(const Key('path-editor-scroll-fallback')), + findsOneWidget, + ); + expect( + tester + .widget(find.byKey(const Key('path-editor-hex-field'))) + .focusNode + ?.hasFocus, + isTrue, + ); + final scrollable = _fallbackScrollable(); + await _revealInFallback( + tester, + scrollable, + find.textContaining('Invalid', skipOffstage: false), + ); + expect(find.textContaining('Invalid').hitTestable(), findsOneWidget); + await _revealInFallback( + tester, + scrollable, + find.byKey(const Key('path-editor-search-field'), skipOffstage: false), + ); + expect( + find.byKey(const Key('path-editor-search-field')).hitTestable(), + findsOneWidget, + ); + await _revealInFallback( + tester, + scrollable, + find.text('Acreage North', skipOffstage: false), + ); + expect(find.text('Acreage North').hitTestable(), findsOneWidget); + final button = tester.getRect(find.text('Use this path')); + final sheet = tester.getRect(find.byType(PathEditorSheet)); + expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); + }, + ); + testWidgets('a landscape keyboard sheet scrolls instead of overflowing', ( tester, ) async { @@ -229,23 +308,7 @@ void main() { find.byKey(const Key('path-editor-scroll-fallback')), findsOneWidget, ); - // The hop list has its own scrollable. The fallback is the scrollable - // that also contains the hex field. - final scrollable = find.byElementPredicate((element) { - if (element.widget is! Scrollable) return false; - var hasHex = false; - void visit(Element node) { - node.visitChildren((child) { - if (child.widget.key == const Key('path-editor-hex-field')) { - hasHex = true; - } - visit(child); - }); - } - - visit(element); - return hasHex; - }); + final scrollable = _fallbackScrollable(); await tester.scrollUntilVisible( find.byKey(const Key('path-editor-hex-field')), 40, @@ -279,6 +342,102 @@ void main() { expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); }); + testWidgets('an empty landscape keyboard sheet scrolls cleanly at 180px', ( + tester, + ) async { + for (final size in [const Size(800, 180), const Size(640, 220)]) { + await _pumpSheet(tester, size: size); + + expect(tester.takeException(), isNull); + expect( + find.byKey(const Key('path-editor-scroll-fallback')), + findsOneWidget, + ); + final scrollable = _fallbackScrollable(); + await _revealInFallback( + tester, + scrollable, + find.byKey(const Key('path-editor-hex-field'), skipOffstage: false), + ); + expect( + find.byKey(const Key('path-editor-hex-field')).hitTestable(), + findsOneWidget, + ); + await _revealInFallback( + tester, + scrollable, + find.byKey(const Key('path-editor-search-field'), skipOffstage: false), + ); + expect( + find.byKey(const Key('path-editor-search-field')).hitTestable(), + findsOneWidget, + ); + await _revealInFallback( + tester, + scrollable, + find.text('Acreage North', skipOffstage: false), + ); + expect(find.text('Acreage North').hitTestable(), findsOneWidget); + final button = tester.getRect(find.text('Use this path')); + final sheet = tester.getRect(find.byType(PathEditorSheet)); + expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); + } + }); + + testWidgets('320dp width fits at 1.3x and 2.0x text scale without overflow', ( + tester, + ) async { + for (final scale in [1.3, 2.0]) { + for (final keyboard in [0.0, 320.0]) { + await _pumpSheet( + tester, + size: const Size(320, 640), + keyboard: keyboard, + textScale: scale, + initialPath: [0x60, 0x60, 0x11, 0x22], + ); + expect(tester.takeException(), isNull); + + if (find + .byKey(const Key('path-editor-scroll-fallback')) + .evaluate() + .isNotEmpty) { + await _revealInFallback( + tester, + _fallbackScrollable(), + find.byKey(const Key('path-editor-hex-field'), skipOffstage: false), + ); + } + await tester.enterText( + find.byKey(const Key('path-editor-hex-field')), + 'AA, BB, CC, DD, EE, FF, GG, HH, II, JJ', + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + if (find + .byKey(const Key('path-editor-scroll-fallback')) + .evaluate() + .isNotEmpty) { + await _revealInFallback( + tester, + _fallbackScrollable(), + find.textContaining('Invalid', skipOffstage: false), + ); + } + expect(find.textContaining('Invalid').hitTestable(), findsOneWidget); + + if (find.text('Use this path').evaluate().isEmpty) { + final state = tester.state(_fallbackScrollable()); + state.position.jumpTo(state.position.maxScrollExtent); + await tester.pumpAndSettle(); + } + final button = tester.getRect(find.text('Use this path')); + final sheet = tester.getRect(find.byType(PathEditorSheet)); + expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1)); + } + } + }); + testWidgets('action buttons stay below the repeater list on a short sheet', ( tester, ) async { From bd91fb1ff9ccc8a3e9b98452dd5ae3ca1a8bb252 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:22:07 -0700 Subject: [PATCH 25/50] Keep failed translation downloads visible after leaving settings Record download failure metadata on TranslationService so reopening App Settings still surfaces the failed row and retry action instead of losing the error when the previous page state was disposed. --- lib/services/translation_service.dart | 51 ++++- lib/widgets/translation_settings_section.dart | 69 ++++++- test/widgets/model_download_list_test.dart | 189 ++++++++++++++++++ 3 files changed, 303 insertions(+), 6 deletions(-) diff --git a/lib/services/translation_service.dart b/lib/services/translation_service.dart index 1688203b..cb8b0958 100644 --- a/lib/services/translation_service.dart +++ b/lib/services/translation_service.dart @@ -39,11 +39,14 @@ class TranslationDownloadCancelled implements Exception { class TranslationService extends ChangeNotifier { final AppSettingsService _appSettingsService; final TranslationFileStore _fileStore; + final http.Client Function() _newClient; TranslationService( this._appSettingsService, { TranslationFileStore? fileStore, - }) : _fileStore = fileStore ?? TranslationFileStore() { + http.Client Function()? clientFactory, + }) : _fileStore = fileStore ?? TranslationFileStore(), + _newClient = clientFactory ?? http.Client.new { // Initialize langdetect once at service construction. _langDetectInit = initLangDetect(); } @@ -64,6 +67,10 @@ class TranslationService extends ChangeNotifier { String? _downloadTargetFileName; String? _downloadSourceUrl; String? _downloadModelId; + String? _failedDownloadError; + String? _failedDownloadSourceUrl; + String? _failedDownloadFileName; + String? _failedDownloadModelId; bool get isBusy => _isBusy; bool get isDownloading => _isDownloading; @@ -82,6 +89,18 @@ class TranslationService extends ChangeNotifier { /// Preset id when the download was started as a preset, otherwise null. String? get downloadModelId => _downloadModelId; + + /// Error message from the most recent failed download, if any. + String? get failedDownloadError => _failedDownloadError; + + /// URL of the most recent failed download, if any. + String? get failedDownloadSourceUrl => _failedDownloadSourceUrl; + + /// Resolved filename of the most recent failed download, if any. + String? get failedDownloadFileName => _failedDownloadFileName; + + /// Preset id of the most recent failed download, if it was a preset. + String? get failedDownloadModelId => _failedDownloadModelId; double? get downloadProgress { final total = _downloadTotalBytes; if (!_isDownloading || total == null || total <= 0) { @@ -210,6 +229,7 @@ class TranslationService extends ChangeNotifier { return _runExclusive(() async { _setBusy(true); _lastError = null; + _clearFailedDownload(); final resolvedFileName = fileName ?? _sanitizeFileName( @@ -227,7 +247,7 @@ class TranslationService extends ChangeNotifier { _setDownloading(true); try { // HEAD request to check size and range support. - final headClient = http.Client(); + final headClient = _newClient(); int? totalSize; bool supportsRange = false; try { @@ -240,6 +260,10 @@ class TranslationService extends ChangeNotifier { headClient.close(); } + if (_cancelDownloadRequested) { + throw const TranslationDownloadCancelled(); + } + _downloadTotalBytes = totalSize; _notify(); @@ -277,6 +301,15 @@ class TranslationService extends ChangeNotifier { await _appSettingsService.setTranslationModelSourceUrl(sourceUrl); _failedModelPath = null; return record; + } on TranslationDownloadCancelled { + rethrow; + } catch (error) { + _lastError = '$error'; + _failedDownloadError = '$error'; + _failedDownloadSourceUrl = sourceUrl; + _failedDownloadFileName = resolvedFileName; + _failedDownloadModelId = id; + rethrow; } finally { _setDownloading(false); } @@ -287,7 +320,7 @@ class TranslationService extends ChangeNotifier { required Uri uri, required String fileName, }) async { - final client = http.Client(); + final client = _newClient(); try { final response = await client.send(http.Request('GET', uri)); if (response.statusCode < 200 || response.statusCode >= 300) { @@ -331,7 +364,7 @@ class TranslationService extends ChangeNotifier { if (start >= totalSize) break; final chunkPath = await _fileStore.chunkFilePath(fileName, i); chunkPaths.add(chunkPath); - final client = http.Client(); + final client = _newClient(); clients.add(client); futures.add( _downloadRange( @@ -718,6 +751,13 @@ class TranslationService extends ChangeNotifier { _notify(); } + void _clearFailedDownload() { + _failedDownloadError = null; + _failedDownloadSourceUrl = null; + _failedDownloadFileName = null; + _failedDownloadModelId = null; + } + /// Puts the service in the same state [downloadModel] publishes while a /// fetch is running, so settings can be rebuilt without a network call. @visibleForTesting @@ -729,12 +769,15 @@ class TranslationService extends ChangeNotifier { int downloadedBytes = 0, int? totalBytes, }) { + _lastError = null; + _clearFailedDownload(); _downloadSourceUrl = sourceUrl; _downloadModelId = modelId; _downloadTargetFileName = fileName; _downloadFileName = displayedFileName ?? fileName; _downloadedBytes = downloadedBytes; _downloadTotalBytes = totalBytes; + _isBusy = true; _isDownloading = true; _notify(); } diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart index fc0ac2cb..8f2de947 100644 --- a/lib/widgets/translation_settings_section.dart +++ b/lib/widgets/translation_settings_section.dart @@ -171,6 +171,7 @@ class _TranslationModelsState extends State<_TranslationModels> { lastError != null && lastError.isNotEmpty && lastError != 'Download stopped.' && + lastError != translationService.failedDownloadError && lastError != _failedDetail; return Column( @@ -219,6 +220,8 @@ class _TranslationModelsState extends State<_TranslationModels> { final items = []; var pendingShown = false; + final serviceFailedError = service.failedDownloadError; + bool targets(String id, String sourceUrl, String name) { if (pending == null) return false; if (pending.id == id || pending.modelId == id) return true; @@ -227,6 +230,27 @@ class _TranslationModelsState extends State<_TranslationModels> { return false; } + bool matchesServiceFailure( + String id, + String sourceUrl, + String? fileName, + String? installedName, + ) { + if (serviceFailedError == null) return false; + if (service.failedDownloadModelId == id) return true; + if (sourceUrl.isNotEmpty && + service.failedDownloadSourceUrl == sourceUrl) { + return true; + } + final failedFile = service.failedDownloadFileName; + if (failedFile != null && + failedFile.isNotEmpty && + (failedFile == fileName || failedFile == installedName)) { + return true; + } + return false; + } + ModelDownloadItem buildItem({ required String id, required String name, @@ -240,11 +264,25 @@ class _TranslationModelsState extends State<_TranslationModels> { service.isDownloading && (targets(id, sourceUrl, name) || _fileNamesThisDownload(service, fileName, installed?.name)); - final failed = !downloading && _failedId == id; + final failed = + !downloading && + (_failedId == id || + (_failedId == null && + matchesServiceFailure( + id, + sourceUrl, + fileName, + installed?.name, + ))); if (downloading || failed) pendingShown = true; final merging = downloading && _isMerging(service); final busy = service.isBusy; final installedModel = installed; + final failureDetail = _failedId == id + ? _failedDetail + : (serviceFailedError != null + ? l10n.translation_downloadFailed(serviceFailedError) + : null); return ModelDownloadItem( id: id, @@ -266,7 +304,7 @@ class _TranslationModelsState extends State<_TranslationModels> { detail: merging ? l10n.translation_mergingChunks : failed - ? _failedDetail + ? failureDetail : null, progress: downloading && !merging ? service.downloadProgress : null, downloadedBytes: downloading ? service.downloadedBytes : 0, @@ -349,6 +387,33 @@ class _TranslationModelsState extends State<_TranslationModels> { ), ), ); + } else if (!pendingShown && + !service.isDownloading && + serviceFailedError != null && + service.failedDownloadSourceUrl != null) { + final failedUrl = service.failedDownloadSourceUrl!; + final failedFile = service.failedDownloadFileName; + final failedModelId = service.failedDownloadModelId; + final id = (failedModelId != null && failedModelId.isNotEmpty) + ? failedModelId + : failedUrl.isNotEmpty + ? failedUrl + : (failedFile ?? 'download'); + items.add( + ModelDownloadItem( + id: id, + name: _displayName(failedUrl, failedFile, failedModelId), + status: ModelDownloadStatus.error, + detail: l10n.translation_downloadFailed(serviceFailedError), + onDownload: service.isBusy + ? null + : () => _download( + sourceUrl: failedUrl, + fileName: failedFile, + id: failedModelId, + ), + ), + ); } return items; diff --git a/test/widgets/model_download_list_test.dart b/test/widgets/model_download_list_test.dart index 4734bcad..d5653aa8 100644 --- a/test/widgets/model_download_list_test.dart +++ b/test/widgets/model_download_list_test.dart @@ -1,11 +1,16 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/models/image_codec_support.dart'; import 'package:meshcore_open/models/translation_support.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/services/image_codec_service.dart'; import 'package:meshcore_open/services/image_codec_settings_store.dart'; +import 'package:meshcore_open/services/translation_file_store.dart'; import 'package:meshcore_open/services/translation_service.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:meshcore_open/theme/mesh_theme.dart'; @@ -16,6 +21,40 @@ import 'package:provider/provider.dart'; import 'package:provider/single_child_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; +class _MemoryTranslationFileStore extends TranslationFileStore { + final Map _files = {}; + + @override + Future modelDirectoryPath() async => '/memory/translation_models'; + + @override + Future> scanDownloadedModels() async => const []; + + @override + Future deleteModel(TranslationModelRecord model) async { + _files.remove(model.localPath); + } + + @override + Future deleteFile(String path) async { + _files.remove(path); + } + + @override + Future writeModelBytes({ + required String fileName, + required Stream> chunks, + }) async { + var total = 0; + await for (final chunk in chunks) { + total += chunk.length; + } + final path = '/memory/translation_models/$fileName'; + _files[path] = total; + return DownloadedModelFile(localPath: path, fileSizeBytes: total); + } +} + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -274,6 +313,156 @@ void main() { expect(find.byTooltip('Cancel'), findsOneWidget); }); + testWidgets( + 'reopening settings during a custom download supports cancel, completion, and failure', + (tester) async { + StreamController>? getStream; + final settings = AppSettingsService(); + await settings.loadSettings(); + final translation = TranslationService( + settings, + fileStore: _MemoryTranslationFileStore(), + clientFactory: () => MockClient.streaming((request, _) async { + if (request.method == 'HEAD') { + return http.StreamedResponse( + const Stream>.empty(), + 200, + contentLength: 1024, + ); + } + final controller = StreamController>(); + getStream = controller; + return http.StreamedResponse( + controller.stream, + 200, + contentLength: 1024, + ); + }), + ); + addTearDown(translation.dispose); + + final providers = [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: translation), + ]; + + Future startCustomDownload(String url) async { + await pump( + tester, + const TranslationSettingsSection(), + providers: providers, + ); + await tester.ensureVisible(find.byType(TextField)); + await tester.enterText(find.byType(TextField), url); + await tester.pump(); + final urlFieldDownload = find.descendant( + of: find.byType(TextField), + matching: find.byTooltip('Download'), + ); + await tester.ensureVisible(urlFieldDownload); + await tester.tap(urlFieldDownload); + await tester.pump(); + await tester.pump(); + } + + Future leaveAndReopen() async { + await pump(tester, const SizedBox.shrink(), providers: providers); + await pump( + tester, + const TranslationSettingsSection(), + providers: providers, + ); + } + + // 1. Cancel after reopen. + await startCustomDownload('https://example.com/Custom-Cancel.gguf'); + await tester.pump(Duration.zero); + getStream!.add(List.filled(512, 1)); + await tester.pump(Duration.zero); + expect(translation.downloadedBytes, 512); + await leaveAndReopen(); + expect(find.text('Custom-Cancel'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + expect(find.byTooltip('Cancel'), findsOneWidget); + expect( + find.byKey( + ValueKey('model-download-${translationPresetModels.first.id}'), + ), + findsNothing, + ); + expect( + tester + .widget( + find.descendant( + of: find.byType(TextField), + matching: find.byType(IconButton), + ), + ) + .onPressed, + isNull, + ); + + await tester.ensureVisible(find.byTooltip('Cancel')); + await tester.tap(find.byTooltip('Cancel')); + await tester.pump(); + expect(translation.lastError, 'Download stopped.'); + getStream!.add(List.filled(16, 1)); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + expect(translation.isDownloading, isFalse); + expect(find.text('Custom-Cancel'), findsNothing); + expect(find.text('Download stopped.'), findsNothing); + + // 2. Complete after reopen. + await startCustomDownload('https://example.com/Custom-Complete.gguf'); + await tester.pump(Duration.zero); + getStream!.add(List.filled(512, 2)); + await tester.pump(Duration.zero); + await leaveAndReopen(); + expect(find.text('Custom-Complete'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + + getStream!.add(List.filled(512, 2)); + unawaited(getStream!.close()); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + expect(find.text('Custom-Complete'), findsOneWidget); + expect(find.textContaining('Ready'), findsOneWidget); + expect(find.textContaining('Active'), findsOneWidget); + + // 3. Failure after reopen. + await startCustomDownload('https://example.com/Custom-Fail.gguf'); + await tester.pump(Duration.zero); + getStream!.add(List.filled(256, 3)); + await tester.pump(Duration.zero); + await leaveAndReopen(); + expect(find.text('Custom-Fail'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + + getStream!.addError(http.ClientException('Connection reset')); + unawaited(getStream!.close()); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + expect(find.text('Custom-Fail'), findsOneWidget); + expect(find.textContaining("Couldn't download"), findsOneWidget); + expect(find.textContaining('Connection reset'), findsOneWidget); + // Error is shown in the model row detail, not duplicated below the URL field. + expect(find.text('ClientException: Connection reset'), findsNothing); + expect( + find.byKey( + const ValueKey('model-download-https://example.com/Custom-Fail.gguf'), + ), + findsOneWidget, + ); + }, + ); + testWidgets('an installed image bundle is one ready row', (tester) async { final spec = imageCodecPresetModels.single; final settings = AppSettingsService(); From b649d8373d2808ff2d318ab15f0335d560199e32 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:41:05 -0700 Subject: [PATCH 26/50] Wrap channel bubble metadata row on narrow screens --- lib/screens/channel_chat_screen.dart | 47 ++++++++++++------------ test/screens/chat_bubble_width_test.dart | 5 ++- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index f552dd3d..2fac04d9 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1423,8 +1423,10 @@ class _ChannelChatScreenState extends State { bottom: 4, ) : EdgeInsets.zero, - child: Row( - mainAxisSize: MainAxisSize.min, + child: Wrap( + spacing: 4, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( formatChatTime(context, message.timestamp), @@ -1433,30 +1435,30 @@ class _ChannelChatScreenState extends State { color: metaColor, ), ), - if (message.hasFutureTimestamp) ...[ - const SizedBox(width: 4), + if (message.hasFutureTimestamp) FutureTimestampIndicator(size: 16 * textScale), - ], if (enableTracing && !isOutgoing && - message.repeatCount > 0) ...[ - const SizedBox(width: 6), - Icon( - Icons.repeat, - size: 14 * textScale, - color: metaColor, + message.repeatCount > 0) + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.repeat, + size: 14 * textScale, + color: metaColor, + ), + const SizedBox(width: 2), + Text( + '${message.repeatCount}', + style: MeshTheme.mono( + fontSize: 12 * textScale, + color: metaColor, + ), + ), + ], ), - const SizedBox(width: 2), - Text( - '${message.repeatCount}', - style: MeshTheme.mono( - fontSize: 12 * textScale, - color: metaColor, - ), - ), - ], - if (isOutgoing) ...[ - const SizedBox(width: 4), + if (isOutgoing) MessageStatusIcon( size: 16 * textScale, isAcked: false, @@ -1476,7 +1478,6 @@ class _ChannelChatScreenState extends State { ChannelMessageStatus.failed, onColor: metaColor, ), - ], ], ), ), diff --git a/test/screens/chat_bubble_width_test.dart b/test/screens/chat_bubble_width_test.dart index e8e6cfc3..5f17945a 100644 --- a/test/screens/chat_bubble_width_test.dart +++ b/test/screens/chat_bubble_width_test.dart @@ -58,8 +58,9 @@ class _ToggleConnector extends MeshCoreConnector { bool get isConnected => connected; } -DateTime _at(int seconds) => - DateTime.fromMillisecondsSinceEpoch(1700000000000 + seconds * 1000); +// Two-digit local hour (10:13 PM / 22:13) so narrow 2.0x text checks the wide +// timestamp layout regardless of host timezone. +DateTime _at(int seconds) => DateTime(2023, 11, 14, 22, 13, seconds); Future _seedRadio() async { final alice = Contact( From 816dc92f2b3ce6b8a176b82a2268922c276b9b20 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:10:43 -0700 Subject: [PATCH 27/50] Improve slider inactive track contrast inside SettingsReveal panels --- documentation/design.md | 2 +- lib/screens/app_settings_screen.dart | 3 +- lib/theme/mesh_theme.dart | 30 +++- .../screens/routing_settings_screen_test.dart | 145 ++++++++++++++++++ 4 files changed, 175 insertions(+), 5 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index 27f112a7..550ec0ed 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -164,7 +164,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act ### Reveal on enable -A switch that uncovers more controls uses `SettingsReveal` (`lib/widgets/settings_reveal.dart`). The block's height eases over 200ms (`RevealOnEnable.duration`, `Curves.easeInOut`, aligned to the top). While the switch is off the extra controls are not in the tree, so they are not announced. The panel uses `surfaceContainerHighest` and a 16px start indent. +A switch that uncovers more controls uses `SettingsReveal` (`lib/widgets/settings_reveal.dart`). The block's height eases over 200ms (`RevealOnEnable.duration`, `Curves.easeInOut`, aligned to the top). While the switch is off the extra controls are not in the tree, so they are not announced. The panel uses `surfaceContainerHighest` and a 16px start indent. Because the panel already sits on `surfaceContainerHighest`, controls and inset notices inside it must contrast against `surfaceContainerHighest` as well as `surfaceContainerLow` (`MeshTheme`'s slider inactive track and value indicator step away from `surfaceContainerHighest`, and inset notice boxes inside `SettingsReveal` use `surfaceContainerLow` with an `outlineVariant` border). The same animation without the tint is `RevealOnEnable`. Use it when the revealed control is not a settings sub-panel: the Bluetooth-off banner on the scanner and the device-info rows on the Settings screen. diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 85fb9920..ad55dda6 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -823,8 +823,9 @@ class AppSettingsScreen extends StatelessWidget { Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: scheme.surfaceContainerHighest, + color: scheme.surfaceContainerLow, borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: scheme.outlineVariant), ), child: Text( reason, diff --git a/lib/theme/mesh_theme.dart b/lib/theme/mesh_theme.dart index 9dc6ada4..24644a26 100644 --- a/lib/theme/mesh_theme.dart +++ b/lib/theme/mesh_theme.dart @@ -403,6 +403,25 @@ class MeshTheme { fontFamilyFallback: MeshFonts.sansFallback, ); + // SettingsReveal uses surfaceContainerHighest, so inactive slider tracks and + // drag bubbles need a distinct step toward onSurfaceVariant / inverseSurface + // to stay legible inside both MeshCard and SettingsReveal. + final sliderInactiveTrack = Color.lerp( + scheme.surfaceContainerHighest, + scheme.onSurfaceVariant, + brightness == Brightness.dark ? 0.42 : 0.54, + )!; + final sliderInactiveTick = Color.lerp( + sliderInactiveTrack, + scheme.onSurface, + 0.7, + )!; + final sliderActiveTick = Color.lerp( + scheme.primary, + scheme.onPrimary, + 0.65, + )!; + return ThemeData( useMaterial3: true, extensions: [bubble, icons, map], @@ -649,14 +668,19 @@ class MeshTheme { ), sliderTheme: SliderThemeData( activeTrackColor: scheme.primary, - inactiveTrackColor: scheme.surfaceContainerHighest, + inactiveTrackColor: sliderInactiveTrack, + disabledActiveTrackColor: scheme.onSurface.withValues(alpha: 0.38), + disabledInactiveTrackColor: sliderInactiveTrack.withValues(alpha: 0.38), + activeTickMarkColor: sliderActiveTick, + inactiveTickMarkColor: sliderInactiveTick, thumbColor: scheme.primary, + disabledThumbColor: scheme.onSurface.withValues(alpha: 0.38), overlayColor: scheme.primary.withValues(alpha: 0.12), - valueIndicatorColor: scheme.surfaceContainerHighest, + valueIndicatorColor: scheme.inverseSurface, valueIndicatorTextStyle: TextStyle( fontFamily: MeshFonts.mono, fontFamilyFallback: MeshFonts.monoFallback, - color: scheme.onSurface, + color: scheme.onInverseSurface, fontSize: 12, ), trackHeight: 3, diff --git a/test/screens/routing_settings_screen_test.dart b/test/screens/routing_settings_screen_test.dart index 7ba8b33d..b4885d18 100644 --- a/test/screens/routing_settings_screen_test.dart +++ b/test/screens/routing_settings_screen_test.dart @@ -8,6 +8,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; import 'package:meshcore_open/models/send_attempt_plan.dart'; import 'package:meshcore_open/screens/app_settings_screen.dart'; import 'package:meshcore_open/screens/repeater_settings_screen.dart'; @@ -452,4 +453,148 @@ void main() { }, ); } + + for (final entry in <(String, ThemeData)>[ + ('light', MeshTheme.light()), + ('dark', MeshTheme.dark()), + for (final preset in [ + ...CustomTheme.presets, + ...CustomTheme.holidayPresets, + ]) + ('custom:${preset.name}', MeshTheme.fromCustom(preset)), + ]) { + testWidgets( + 'slider inactive track, tick marks, and drag bubble contrast inside SettingsReveal and MeshCard (${entry.$1})', + (tester) async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.updateSettings( + settings.settings.copyWith(channelMinHopsEnabled: true), + ); + + tester.view.physicalSize = const Size(800, 8000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + final connector = MeshCoreConnector(); + final translation = TranslationService(settings); + final uploads = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + addTearDown(connector.dispose); + addTearDown(translation.dispose); + addTearDown(uploads.dispose); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: uploads), + ], + child: MaterialApp( + theme: entry.$2, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const AppSettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + final screenContext = tester.element(find.byType(AppSettingsScreen)); + final l10n = AppLocalizations.of(screenContext); + final scheme = entry.$2.colorScheme; + + final revealFinder = find.byType(SettingsReveal).first; + final revealMaterial = tester.widget( + find + .descendant(of: revealFinder, matching: find.byType(Material)) + .first, + ); + final revealBg = revealMaterial.color!; + expect(revealBg, scheme.surfaceContainerHighest); + + final directRowFinder = find.ancestor( + of: find.text( + l10n.appSettings_directRetries(settings.settings.directRetries), + ), + matching: find.byType(SettingsValueSlider), + ); + final directCardMaterial = tester.widget( + find + .ancestor(of: directRowFinder, matching: find.byType(Material)) + .first, + ); + final cardBg = directCardMaterial.color!; + expect(cardBg, scheme.surfaceContainerLow); + + final hopsRowFinder = find.ancestor( + of: find.text( + l10n.appSettings_channelMinHopsCount( + settings.settings.channelMinHops, + ), + ), + matching: find.byType(SettingsValueSlider), + ); + final revealedSliderFinder = find.descendant( + of: hopsRowFinder, + matching: find.byType(Slider), + ); + final directSliderFinder = find.descendant( + of: directRowFinder, + matching: find.byType(Slider), + ); + + for (final sliderFinder in [revealedSliderFinder, directSliderFinder]) { + final sliderContext = tester.element(sliderFinder); + final sliderTheme = SliderTheme.of(sliderContext); + final inactiveTrack = sliderTheme.inactiveTrackColor!; + final inactiveTick = sliderTheme.inactiveTickMarkColor!; + final activeTick = sliderTheme.activeTickMarkColor!; + final valueIndicator = sliderTheme.valueIndicatorColor!; + + expect(inactiveTrack.a, 1.0); + expect(inactiveTrack, isNot(revealBg)); + expect(inactiveTrack, isNot(cardBg)); + + expect( + meshContrastRatio(inactiveTrack, revealBg), + greaterThanOrEqualTo(2.1), + reason: 'Inactive track must stand out on SettingsReveal', + ); + expect( + meshContrastRatio(inactiveTrack, cardBg), + greaterThanOrEqualTo(2.5), + reason: 'Inactive track must stand out on MeshCard', + ); + expect( + meshContrastRatio(inactiveTick, inactiveTrack), + greaterThanOrEqualTo(2.5), + reason: 'Inactive tick marks must stand out on inactive track', + ); + expect( + meshContrastRatio(activeTick, sliderTheme.activeTrackColor!), + greaterThanOrEqualTo(1.8), + reason: 'Active tick marks must stand out on active track', + ); + expect( + meshContrastRatio(valueIndicator, revealBg), + greaterThanOrEqualTo(3.0), + reason: 'Drag bubble must stand out on SettingsReveal', + ); + expect( + meshContrastRatio(valueIndicator, cardBg), + greaterThanOrEqualTo(3.0), + reason: 'Drag bubble must stand out on MeshCard', + ); + } + }, + ); + } } From e65b3982e2bdec4e256f6e60c52ff11f9933942b Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:39:13 -0700 Subject: [PATCH 28/50] Reveal model settings on enable and align model row icons --- documentation/design.md | 19 +- documentation/settings.md | 5 +- lib/screens/app_settings_screen.dart | 36 ++- lib/widgets/image_codec_models_section.dart | 3 +- lib/widgets/model_download_list.dart | 15 +- lib/widgets/settings_reveal.dart | 115 +++++++ lib/widgets/translation_settings_section.dart | 112 ++++--- test/widgets/model_download_list_test.dart | 285 ++++++++++++++++++ test/widgets/settings_reveal_test.dart | 256 ++++++++++++++++ 9 files changed, 763 insertions(+), 83 deletions(-) create mode 100644 lib/widgets/settings_reveal.dart create mode 100644 test/widgets/settings_reveal_test.dart diff --git a/documentation/design.md b/documentation/design.md index 93bedf95..9858e75b 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -2,7 +2,7 @@ How MeshCore Open's interface is built today, and the rules to follow when adding or changing UI. Every value below comes from the code it cites. If you change one of those sources, or settle on a new pattern, update this page in the same change. -The source of truth is `lib/theme/mesh_theme.dart` (theme), `lib/widgets/mesh_ui.dart` (shared widgets) and `lib/widgets/mesh_nav_tile.dart` (settings rows). Where the code disagrees with this page, fix one of them; do not copy the inconsistency. +The source of truth is `lib/theme/mesh_theme.dart` (theme), `lib/widgets/mesh_ui.dart` (shared widgets), `lib/widgets/settings_reveal.dart` (reveal-on-enable) and `lib/widgets/mesh_nav_tile.dart` (settings rows). Where the code disagrees with this page, fix one of them; do not copy the inconsistency. ## 1. Principles @@ -105,6 +105,8 @@ Minimum sizes: no hard-coded `fontSize` below 12 exists in `lib/screens` or `lib | Avatar | 40 | `AvatarCircle` | | List bottom padding under a FAB | 88 | `channels_screen.dart` | +Every settings row — including child rows revealed inside `SettingsReveal` and model rows in `ModelDownloadList` — uses a vertically centred 24px leading icon with a 16px gap (`MeshNavTile`, `SwitchListTile.secondary`, or `ListTile.leading`) so titles align vertically across a card. + Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small action buttons, 18 for inline refresh icons and spinners. Keep tappable icons at 20 or more. **Tap targets.** Keep Flutter's 48×48 minimum (the default `materialTapTargetSize` and `IconButton` size). Don't shrink with `VisualDensity.compact`, `MaterialTapTargetSize.shrinkWrap` or small `BoxConstraints` unless the control sits inside a larger tappable row. @@ -117,6 +119,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act | Label above a group | `SectionHeader(label, trailing:)` | Upper-cases for you; pass the normal-case l10n string | | Settings navigation row | `MeshNavTile` | `onTap: null` dims it to 50 % and reports it as disabled; use `subtitle` to say why | | Settings switch | `SwitchListTile` inside `MeshSettingsTileTheme` | Wrap the settings screen body once in `MeshSettingsTileTheme` | +| Switch that reveals more controls | `SettingsReveal` | 200ms height ease, `surfaceContainerHighest`, 16px start indent. See [Reveal on enable](#reveal-on-enable) | | Radio-style choice in a sheet | `MeshSheetOption` | Used by the language picker, map time filter and compression sheet. Optional `subtitle` explains the option; `onTap: null` disables it. Selected rows show a filled radio icon **and** a bold title, with `selected` semantics | | Per-chat setting at the top of a chat | Full-width strip under the app bar, above the transcript (`ChatCompressionSelector` in `widgets/chat_compression_selector.dart`) | `surfaceContainerLow` fill, `outlineVariant` bottom border, 48dp minimum height, `bodyLarge` w600 "Label: value ▾"; tap opens one `showMeshSheet` with `MeshSheetOption`s. Shows the saved value only; a spinner replaces ▾ while saving; a disabled strip shows why below the label. One shared widget for DM and channel chats; parents pass state and async callbacks | | Choosing between images | Selectable thumbnail tiles in a centred `Wrap` | Image send versions (`_versionTile` in `image_send_preview_sheet.dart`). `InkWell` with `MeshRadii.sm`; selected tile gets a 3px `primary` border **and** a `primary` check badge (never colour alone); caption under the tile in `bodySmall`, w600 when selected; figures such as packet counts in `MeshTheme.mono` 12; wrap the tile in `Semantics(button: true, selected:, label:)` | @@ -158,18 +161,25 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act - Offline, `OfflineComposerBar` uses the same panel, bubble and height, with Connect in place of the round button (below the bubble on narrow or large-text layouts). - Full-width strips that are not part of the draft (image send progress) go in `header`, above the bubble. +### Reveal on enable + +A switch that uncovers more controls (such as **Enable image messages** and **Enable translation**) uses `SettingsReveal` (`lib/widgets/settings_reveal.dart`). The block's height eases over 200ms (`RevealOnEnable.duration`, `Curves.easeInOut`, aligned to the top). While the switch is off the extra controls are not in the tree, so they are not announced. The panel uses `surfaceContainerHighest` and a 16px start indent. Because the panel already sits on `surfaceContainerHighest`, inset notice boxes inside `SettingsReveal` (such as `ImageCodecModelsSection`'s unavailable-platform notice) use `surfaceContainerLow` with an `outlineVariant` border. + +The same animation without the tint is `RevealOnEnable`. Do not add a second duration, and do not reveal the controls with a plain `if` that pops them in. + ### Model downloads Image models, translation models, and the restore prompt that fetches missing models all use `ModelDownloadList` (`lib/widgets/model_download_list.dart`). Do not add a second download form (a dropdown of presets, a separate filename row, or a one-off progress bar). -One model is one row inside the existing `MeshCard`, rows separated by `Divider(height: 1, indent: 16)`: +One model is one row inside the existing `MeshCard` (or `SettingsReveal`), rows separated by `Divider(height: 1, indent: 16)`, with leading icon, text column, and trailing action(s) vertically centred (`padding: 16, 12, 4, 12` when an action is present so the icon aligns with `MeshNavTile`'s 16px trailing inset): | Part | What it shows | |---|---| +| Leading icon | 24px icon, 16px gap: `Icons.memory_outlined` (`onSurfaceVariant`) when not downloaded, 24px `CircularProgressIndicator` (`primary`) while downloading, `Icons.check_circle` (`primary`) when active, `Icons.check_circle_outline` (`onSurfaceVariant`) when ready, `Icons.error_outline` (`error`) on failure. Never repeat the trailing download icon on the left. | | Title | Friendly name, `meshTileTitleStyle` (`bodyLarge` w600). It wraps. Never a raw filename or URL. | -| Subtitle | Size via the `mapCache_size*` strings when known, then the status: Not downloaded, Downloading, Ready, or Couldn't download. The model in use also says Active. An install that stopped part-way says Incomplete. The words stay `onSurfaceVariant` (Active is w600). The leading icon carries the colour: `primary` when that model is active or downloading, `error` on failure, `onSurfaceVariant` otherwise. | +| Subtitle | Size via the `mapCache_size*` strings when known, then the status: Not downloaded, Downloading, Ready, or Couldn't download. The model in use also says Active. An install that stopped part-way says Incomplete. The words stay `onSurfaceVariant` (Active is w600). | | Progress | While downloading, a `LinearProgressIndicator` (indeterminate when the total is unknown, or while chunks are merged or the file is verified) and a mono 12 caption of bytes and percent. | -| Action | One `IconButton` with a localized tooltip: Download, Cancel, or Remove model. An install that already has files but is not ready shows both Download and Remove. Tap a Ready row to select it when more than one model can be active. A row the user cannot use is dimmed to 50 %, same as a disabled `MeshNavTile`. | +| Action | One `IconButton` (48×48 touch target) with a localized tooltip: Download, Cancel, or Remove model. An install that already has files but is not ready shows both Download and Remove. Tap a Ready row to select it when more than one model can be active. A row the user cannot use is dimmed to 50 %, same as a disabled `MeshNavTile`. | | Manual URL | When the feature accepts one (translation), put a single text field under the list. Its download control is the same Download icon. The file joins this list. | A dialog that offers several missing models (backup restore) uses the same rows for name, size, status and progress, and keeps its own confirm button. @@ -243,6 +253,7 @@ Follow the same pattern for any new remote-value screen. - [ ] Colours from `colorScheme` or theme extensions; no raw `Colors.*` or `MeshPalette.ink/bg/line` in chrome. - [ ] Text styles from `textTheme` or `MeshTheme.mono`; nothing below 12. - [ ] Settings rows use `MeshNavTile` / `SwitchListTile` inside `MeshSettingsTileTheme`; cards are `MeshCard` with a `SectionHeader`. +- [ ] A switch that reveals more controls uses `SettingsReveal`. - [ ] Popup menu rows use `MeshMenuItemRow`; segmented buttons use `MeshSegmentLabel`; destructive menu items last, in `scheme.error`. - [ ] Every `IconButton` and FAB has a localized `tooltip`. - [ ] Tap targets at least 48×48. diff --git a/documentation/settings.md b/documentation/settings.md index e3e76078..73b4b67b 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -148,15 +148,12 @@ Individual channels can be muted from the channel chat bell icon, the channel li - **Offline Map Cache**: Navigate to tile download screen ### Translation -Not shown on web. Controls on-device message translation powered by a locally-downloaded ML model: -- **Enable translation**: Enables message translation controls +Not shown on web. Controls on-device message translation powered by a locally-downloaded ML model. Turn on **Enable translation** first; the translation options and model rows then appear: - **Auto-translate incoming messages**: Automatically translates incoming messages for chat/channel display and notifications - **Translate before sending**: Sets the default state of the composer's translate icon (on means messages are translated before sending) - **Target language**: Language to translate into (searchable list; defaults to the app language) - **Models**: The same model rows used for the image codec. Each preset is one row with its name, size once known, and status (not downloaded, downloading with progress, ready, or couldn't download). The model in use is marked Active; tap another ready row to switch. Download, cancel, and remove are the row's action. A manual model URL under the list downloads a custom GGUF file into the same list. -The auto-translate and composer toggles are disabled until **Enable translation** is on. - ### IPFS Provider Configuration Open **App Settings → IPFS provider configuration** to configure IPFS uploads and previews: diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index f1e822c8..4cd69957 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -18,6 +18,7 @@ import '../widgets/language_picker_sheet.dart'; import '../widgets/mesh_nav_tile.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/network_map_settings_section.dart'; +import '../widgets/settings_reveal.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/translation_settings_section.dart'; import '../helpers/snack_bar_builder.dart'; @@ -725,24 +726,27 @@ class AppSettingsScreen extends StatelessWidget { }, ), ), - if (settingsService.settings.imageMessagesEnabled) ...[ - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, + SettingsReveal( + visible: settingsService.settings.imageMessagesEnabled, + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.auto_awesome_outlined, size: 24), + title: Text(context.l10n.imageMessages_autoProcessTitle), + subtitle: Text(context.l10n.imageMessages_autoProcessSubtitle), + value: settingsService.settings.imageProcessAutomatically, + onChanged: (value) => + settingsService.setImageProcessAutomatically(value), ), - secondary: const Icon(Icons.auto_awesome_outlined, size: 24), - title: Text(context.l10n.imageMessages_autoProcessTitle), - subtitle: Text(context.l10n.imageMessages_autoProcessSubtitle), - value: settingsService.settings.imageProcessAutomatically, - onChanged: (value) => - settingsService.setImageProcessAutomatically(value), - ), - if (_imageCodecService(context) != null) ...[ - const Divider(height: 1, indent: 16), - const ImageCodecModelsSection(), + if (_imageCodecService(context) != null) ...[ + const Divider(height: 1, indent: 16), + const ImageCodecModelsSection(), + ], ], - ], + ), ], ); } diff --git a/lib/widgets/image_codec_models_section.dart b/lib/widgets/image_codec_models_section.dart index 66770288..bf220e43 100644 --- a/lib/widgets/image_codec_models_section.dart +++ b/lib/widgets/image_codec_models_section.dart @@ -53,8 +53,9 @@ class _ImageCodecModelsSectionState extends State { padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), child: DecoratedBox( decoration: BoxDecoration( - color: scheme.surfaceContainerHighest, + color: scheme.surfaceContainerLow, borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: scheme.outlineVariant), ), child: Padding( padding: const EdgeInsets.all(12), diff --git a/lib/widgets/model_download_list.dart b/lib/widgets/model_download_list.dart index 847c2fd3..a3224aed 100644 --- a/lib/widgets/model_download_list.dart +++ b/lib/widgets/model_download_list.dart @@ -114,15 +114,11 @@ class _ModelDownloadRow extends StatelessWidget { padding: padding ?? (actions.isEmpty - ? const EdgeInsets.fromLTRB(16, 8, 16, 8) - : const EdgeInsets.fromLTRB(16, 8, 0, 8)), + ? const EdgeInsets.symmetric(horizontal: 16, vertical: 12) + : const EdgeInsets.fromLTRB(16, 12, 4, 12)), child: Row( - crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding( - padding: const EdgeInsets.only(top: 2), - child: _leading(scheme), - ), + _leading(scheme), const SizedBox(width: 16), Expanded( child: Column( @@ -240,7 +236,7 @@ class _ModelDownloadRow extends StatelessWidget { ); case ModelDownloadStatus.notDownloaded: return Icon( - Icons.download_outlined, + Icons.memory_outlined, size: 24, color: scheme.onSurfaceVariant, ); @@ -256,6 +252,7 @@ class _ModelDownloadRow extends StatelessWidget { key: ValueKey('model-cancel-${item.id}'), tooltip: l10n.imageMessages_cancelDownload, onPressed: item.onCancel, + iconSize: 24, icon: const Icon(Icons.close), ), ]; @@ -267,6 +264,7 @@ class _ModelDownloadRow extends StatelessWidget { key: ValueKey('model-download-${item.id}'), tooltip: l10n.imageMessages_downloadModel, onPressed: item.onDownload, + iconSize: 24, icon: const Icon(Icons.download_outlined), ), ); @@ -277,6 +275,7 @@ class _ModelDownloadRow extends StatelessWidget { key: ValueKey('model-remove-${item.id}'), tooltip: l10n.imageMessages_removeModel, onPressed: item.onDelete, + iconSize: 24, icon: const Icon(Icons.delete_outline), ), ); diff --git a/lib/widgets/settings_reveal.dart b/lib/widgets/settings_reveal.dart new file mode 100644 index 00000000..b818f112 --- /dev/null +++ b/lib/widgets/settings_reveal.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; + +/// Shows or hides [child] by animating its height. +/// +/// Use this wherever turning something on reveals more controls, and for any +/// other block that grows or collapses in place. Hidden controls are not in +/// the tree, so they are not announced. The duration and curve are fixed so +/// every reveal moves the same way. See documentation/design.md. +class RevealOnEnable extends StatelessWidget { + static const Duration duration = Duration(milliseconds: 200); + static const Curve curve = Curves.easeInOut; + + final bool visible; + final Widget child; + final AlignmentGeometry alignment; + + const RevealOnEnable({ + super.key, + required this.visible, + required this.child, + this.alignment = Alignment.topCenter, + }); + + @override + Widget build(BuildContext context) { + return AnimatedSize( + duration: duration, + curve: curve, + alignment: alignment, + child: visible + ? child + : const SizedBox(width: double.infinity, height: 0), + ); + } +} + +/// Nested controls under a settings switch: the shared reveal animation on a +/// tinted, indented panel. +class SettingsReveal extends StatelessWidget { + final bool visible; + final List children; + + const SettingsReveal({ + super.key, + required this.visible, + required this.children, + }); + + @override + Widget build(BuildContext context) { + return RevealOnEnable( + visible: visible, + child: Material( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Padding( + padding: const EdgeInsets.only(left: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), + ), + ), + ); + } +} + +/// A settings slider whose selected value stays visible in the title. +/// +/// The drag bubble repeats the same number. Pass a [title] that already +/// includes [value], the way the channel-hop titles do, and an [icon] so the +/// row aligns with neighbouring [SwitchListTile] and [MeshNavTile] rows. +class SettingsValueSlider extends StatelessWidget { + final IconData icon; + final String title; + final String? subtitle; + final int value; + final int min; + final int max; + final ValueChanged onChanged; + + const SettingsValueSlider({ + super.key, + required this.icon, + required this.title, + this.subtitle, + required this.value, + required this.min, + required this.max, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + final clamped = value.clamp(min, max); + return ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + leading: Icon(icon, size: 24), + title: Text(title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (subtitle != null) Text(subtitle!), + Slider( + value: clamped.toDouble(), + min: min.toDouble(), + max: max.toDouble(), + divisions: max > min ? max - min : null, + label: '$clamped', + onChanged: (next) => onChanged(next.round()), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart index 8f2de947..9add6a5c 100644 --- a/lib/widgets/translation_settings_section.dart +++ b/lib/widgets/translation_settings_section.dart @@ -10,6 +10,7 @@ import '../services/app_settings_service.dart'; import '../services/translation_service.dart'; import 'mesh_nav_tile.dart'; import 'model_download_list.dart'; +import 'settings_reveal.dart'; /// [TranslationService] publishes this as `downloadFileName` while it merges /// downloaded chunks (see translation_service.dart). The service owns the @@ -43,59 +44,70 @@ class TranslationSettingsSection extends StatelessWidget { secondary: const Icon(Icons.translate, size: 24), title: Text(l10n.translation_enableTitle), subtitle: Text(l10n.translation_enableSubtitle), - value: settings.translationEnabled, + value: translationEnabled, onChanged: settingsService.setTranslationEnabled, ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: tilePadding, - secondary: Icon( - Icons.auto_awesome_outlined, - size: 24, - color: disabledColor, - ), - title: Text( - l10n.translation_autoIncomingTitle, - style: TextStyle(color: disabledColor), - ), - subtitle: Text( - l10n.translation_autoIncomingSubtitle, - style: TextStyle(color: disabledColor), - ), - value: settings.autoTranslateIncomingMessages, - onChanged: translationEnabled - ? settingsService.setAutoTranslateIncomingMessages - : null, + SettingsReveal( + visible: translationEnabled, + children: [ + SwitchListTile( + contentPadding: tilePadding, + secondary: Icon( + Icons.auto_awesome_outlined, + size: 24, + color: disabledColor, + ), + title: Text( + l10n.translation_autoIncomingTitle, + style: TextStyle(color: disabledColor), + ), + subtitle: Text( + l10n.translation_autoIncomingSubtitle, + style: TextStyle(color: disabledColor), + ), + value: settings.autoTranslateIncomingMessages, + onChanged: translationEnabled + ? settingsService.setAutoTranslateIncomingMessages + : null, + ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: tilePadding, + secondary: Icon( + Icons.outgoing_mail, + size: 24, + color: disabledColor, + ), + title: Text( + l10n.translation_composerTitle, + style: TextStyle(color: disabledColor), + ), + subtitle: Text( + l10n.translation_composerSubtitle, + style: TextStyle(color: disabledColor), + ), + value: settings.composerTranslationEnabled, + onChanged: translationEnabled + ? settingsService.setComposerTranslationEnabled + : null, + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.language, + title: l10n.translation_targetLanguage, + subtitle: _translationLanguageLabel( + context, + settings.translationTargetLanguageCode, + ), + onTap: translationEnabled + ? () => + _showTranslationLanguageDialog(context, settingsService) + : null, + ), + const Divider(height: 1, indent: 16), + const _TranslationModels(), + ], ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: tilePadding, - secondary: Icon(Icons.outgoing_mail, size: 24, color: disabledColor), - title: Text( - l10n.translation_composerTitle, - style: TextStyle(color: disabledColor), - ), - subtitle: Text( - l10n.translation_composerSubtitle, - style: TextStyle(color: disabledColor), - ), - value: settings.composerTranslationEnabled, - onChanged: translationEnabled - ? settingsService.setComposerTranslationEnabled - : null, - ), - const Divider(height: 1, indent: 16), - MeshNavTile( - icon: Icons.language, - title: l10n.translation_targetLanguage, - subtitle: _translationLanguageLabel( - context, - settings.translationTargetLanguageCode, - ), - onTap: () => _showTranslationLanguageDialog(context, settingsService), - ), - const Divider(height: 1, indent: 16), - const _TranslationModels(), ], ); } diff --git a/test/widgets/model_download_list_test.dart b/test/widgets/model_download_list_test.dart index d5653aa8..db59c7db 100644 --- a/test/widgets/model_download_list_test.dart +++ b/test/widgets/model_download_list_test.dart @@ -15,7 +15,9 @@ import 'package:meshcore_open/services/translation_service.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:meshcore_open/theme/mesh_theme.dart'; import 'package:meshcore_open/widgets/image_codec_models_section.dart'; +import 'package:meshcore_open/widgets/mesh_nav_tile.dart'; import 'package:meshcore_open/widgets/model_download_list.dart'; +import 'package:meshcore_open/widgets/settings_reveal.dart'; import 'package:meshcore_open/widgets/translation_settings_section.dart'; import 'package:provider/provider.dart'; import 'package:provider/single_child_widget.dart'; @@ -201,6 +203,7 @@ void main() { ) async { final settings = AppSettingsService(); await settings.loadSettings(); + await settings.setTranslationEnabled(true); final preset = translationPresetModels.first; final other = translationPresetModels[1]; await settings.setTranslationDownloadedModels([ @@ -263,6 +266,7 @@ void main() { ) async { final settings = AppSettingsService(); await settings.loadSettings(); + await settings.setTranslationEnabled(true); final translation = TranslationService(settings); addTearDown(translation.dispose); // The page that started the download is gone. Only the service still @@ -319,6 +323,7 @@ void main() { StreamController>? getStream; final settings = AppSettingsService(); await settings.loadSettings(); + await settings.setTranslationEnabled(true); final translation = TranslationService( settings, fileStore: _MemoryTranslationFileStore(), @@ -543,4 +548,284 @@ void main() { expect(find.byTooltip('Download'), findsOneWidget); expect(find.byTooltip('Remove model'), findsOneWidget); }); + + testWidgets( + 'notDownloaded uses non-download leading icon and aligns icons cleanly', + (tester) async { + await pump( + tester, + ModelDownloadList( + items: [ + ModelDownloadItem( + id: 'new', + name: 'Uninstalled model', + sizeBytes: 958 * 1024 * 1024, + status: ModelDownloadStatus.notDownloaded, + onDownload: () {}, + ), + ModelDownloadItem( + id: 'incomplete', + name: 'Partial model', + sizeBytes: 500 * 1024 * 1024, + status: ModelDownloadStatus.notDownloaded, + statusLabel: 'Incomplete', + onDownload: () {}, + onDelete: () {}, + ), + ModelDownloadItem( + id: 'busy', + name: 'Downloading model', + sizeBytes: 958 * 1024 * 1024, + status: ModelDownloadStatus.downloading, + progress: 0.4, + downloadedBytes: 400 * 1024 * 1024, + totalBytes: 958 * 1024 * 1024, + onCancel: () {}, + ), + ModelDownloadItem( + id: 'active', + name: 'Active model', + sizeBytes: 1100 * 1024 * 1024, + status: ModelDownloadStatus.ready, + selected: true, + onDelete: () {}, + ), + ModelDownloadItem( + id: 'bad', + name: 'Failed model', + status: ModelDownloadStatus.error, + detail: + 'Download failed because the server closed the connection unexpectedly.', + onDownload: () {}, + ), + ], + ), + ); + + final newRow = find.byKey(const ValueKey('model-row-new')); + final newLeading = find.descendant( + of: newRow, + matching: find.byIcon(Icons.memory_outlined), + ); + expect(newLeading, findsOneWidget); + final newTrailingButton = find.byKey( + const ValueKey('model-download-new'), + ); + final newTrailingIcon = find.descendant( + of: newTrailingButton, + matching: find.byIcon(Icons.download_outlined), + ); + expect(newTrailingIcon, findsOneWidget); + // Leading icon must differ from trailing download icon. + expect( + tester.widget(newLeading).icon, + isNot(tester.widget(newTrailingIcon).icon), + ); + expect(tester.getSize(newLeading), const Size(24, 24)); + expect( + tester.getCenter(newLeading).dy, + closeTo(tester.getCenter(newTrailingIcon).dy, 1.0), + ); + + for (final (rowKey, buttonKey) in [ + ('model-row-incomplete', 'model-download-incomplete'), + ('model-row-busy', 'model-cancel-busy'), + ('model-row-active', 'model-remove-active'), + ('model-row-bad', 'model-download-bad'), + ]) { + final row = find.byKey(ValueKey(rowKey)); + final button = find.byKey(ValueKey(buttonKey)); + final title = find + .descendant(of: row, matching: find.byType(Text)) + .first; + final leading = find + .descendant(of: row, matching: find.byType(Icon)) + .first; + final spinner = find.descendant( + of: row, + matching: find.byType(CircularProgressIndicator), + ); + final leadingFinder = spinner.evaluate().isNotEmpty ? spinner : leading; + expect( + tester.getRect(leadingFinder).right, + lessThan(tester.getRect(title).left), + ); + expect( + tester.getCenter(leadingFinder).dy, + closeTo(tester.getCenter(button).dy, 1.0), + reason: '$rowKey leading indicator and trailing button must center', + ); + } + }, + ); + + testWidgets( + 'TranslationSettingsSection hides sub-options when off, reveals on enable, and aligns rows', + (tester) async { + final settings = AppSettingsService(); + await settings.loadSettings(); + final translation = TranslationService(settings); + addTearDown(translation.dispose); + + await pump( + tester, + const TranslationSettingsSection(), + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: translation), + ], + ); + + final context = tester.element(find.byType(TranslationSettingsSection)); + final l10n = AppLocalizations.of(context); + + expect(find.text(l10n.translation_enableTitle), findsOneWidget); + expect(find.text(l10n.translation_autoIncomingTitle), findsNothing); + expect(find.text(l10n.translation_composerTitle), findsNothing); + expect(find.text(l10n.translation_targetLanguage), findsNothing); + expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsNothing); + expect(find.text(l10n.translation_manualUrlLabel), findsNothing); + + await tester.tap(find.text(l10n.translation_enableTitle)); + await tester.pump(); + await tester.pump(RevealOnEnable.duration); + await tester.pumpAndSettle(); + + expect(find.text(l10n.translation_autoIncomingTitle), findsOneWidget); + expect(find.text(l10n.translation_composerTitle), findsOneWidget); + expect(find.text(l10n.translation_targetLanguage), findsOneWidget); + expect(find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), findsOneWidget); + expect(find.text(l10n.translation_manualUrlLabel), findsOneWidget); + + final revealFinder = find.byType(SettingsReveal); + expect(revealFinder, findsOneWidget); + final revealMaterial = tester.widget( + find + .descendant(of: revealFinder, matching: find.byType(Material)) + .first, + ); + expect( + revealMaterial.color, + Theme.of(context).colorScheme.surfaceContainerHighest, + ); + + // Switches and Target language row are enabled when visible. + final autoIncomingSwitch = tester.widget( + find.ancestor( + of: find.text(l10n.translation_autoIncomingTitle), + matching: find.byType(SwitchListTile), + ), + ); + expect(autoIncomingSwitch.onChanged, isNotNull); + + // Leading icons, titles, and trailing icons align across Target language + // (MeshNavTile) and revealed ModelDownloadList rows. + final targetTile = find.ancestor( + of: find.text(l10n.translation_targetLanguage), + matching: find.byType(MeshNavTile), + ); + final targetIcon = find.descendant( + of: targetTile, + matching: find.byIcon(Icons.language), + ); + final targetChevron = find.descendant( + of: targetTile, + matching: find.byIcon(Icons.chevron_right), + ); + + final firstPreset = translationPresetModels.first; + final modelRow = find.byKey(ValueKey('model-row-${firstPreset.id}')); + final modelLeadingIcon = find.descendant( + of: modelRow, + matching: find.byIcon(Icons.memory_outlined), + ); + final modelTitle = find.descendant( + of: modelRow, + matching: find.text('Tencent HY-MT 1.5 1.8B Q4_K_M'), + ); + final modelDownloadIcon = find.descendant( + of: find.byKey(ValueKey('model-download-${firstPreset.id}')), + matching: find.byIcon(Icons.download_outlined), + ); + + expect(modelLeadingIcon, findsOneWidget); + expect( + tester.getRect(modelLeadingIcon).left, + closeTo(tester.getRect(targetIcon).left, 0.5), + ); + expect( + tester.getRect(modelTitle).left, + closeTo( + tester.getRect(find.text(l10n.translation_targetLanguage)).left, + 0.5, + ), + ); + expect( + tester.getRect(modelDownloadIcon).right, + closeTo(tester.getRect(targetChevron).right, 0.5), + ); + + // Toggling off hides sub-options again. + await tester.tap(find.text(l10n.translation_enableTitle)); + await tester.pumpAndSettle(); + expect(find.text(l10n.translation_autoIncomingTitle), findsNothing); + expect(find.text(l10n.translation_targetLanguage), findsNothing); + expect(find.text(l10n.translation_manualUrlLabel), findsNothing); + }, + ); + + for (final scale in [1.3, 2.0]) { + testWidgets( + 'translation section and two-action model rows fit 320dp at ${scale}x', + (tester) async { + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + if (details.exceptionAsString().contains('overflowed')) { + overflows.add(details.exceptionAsString().split('\n').first); + return; + } + previous?.call(details); + }; + addTearDown(() => FlutterError.onError = previous); + + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setTranslationEnabled(true); + final translation = TranslationService(settings); + addTearDown(translation.dispose); + + await pump( + tester, + Column( + children: [ + const TranslationSettingsSection(), + ModelDownloadList( + items: [ + ModelDownloadItem( + id: 'incomplete', + name: 'Tencent HY-MT 1.5 1.8B Q4_K_M', + sizeBytes: 958 * 1024 * 1024, + status: ModelDownloadStatus.notDownloaded, + statusLabel: 'Incomplete', + onDownload: () {}, + onDelete: () {}, + ), + ], + ), + ], + ), + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value( + value: translation, + ), + ], + textScale: scale, + size: const Size(320, 568), + ); + expect(overflows, isEmpty); + }, + ); + } } diff --git a/test/widgets/settings_reveal_test.dart b/test/widgets/settings_reveal_test.dart new file mode 100644 index 00000000..3fdfaf90 --- /dev/null +++ b/test/widgets/settings_reveal_test.dart @@ -0,0 +1,256 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/screens/app_settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/image_codec_settings_store.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/image_codec_models_section.dart'; +import 'package:meshcore_open/widgets/settings_reveal.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + testWidgets('SettingsReveal hides children when off and reveals with tint', ( + tester, + ) async { + var visible = false; + late StateSetter setHostState; + + await tester.pumpWidget( + MaterialApp( + theme: MeshTheme.dark(), + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + setHostState = setState; + return SettingsReveal( + visible: visible, + children: const [Text('Nested option')], + ); + }, + ), + ), + ), + ); + + expect(find.text('Nested option'), findsNothing); + + setHostState(() => visible = true); + await tester.pump(); + await tester.pump(RevealOnEnable.duration); + await tester.pumpAndSettle(); + + expect(find.text('Nested option'), findsOneWidget); + final context = tester.element(find.byType(SettingsReveal)); + final material = tester.widget( + find + .descendant( + of: find.byType(SettingsReveal), + matching: find.byType(Material), + ) + .first, + ); + expect( + material.color, + Theme.of(context).colorScheme.surfaceContainerHighest, + ); + + final padding = tester.widget( + find + .descendant( + of: find.byType(SettingsReveal), + matching: find.byType(Padding), + ) + .first, + ); + expect(padding.padding, const EdgeInsets.only(left: 16)); + + setHostState(() => visible = false); + await tester.pumpAndSettle(); + expect(find.text('Nested option'), findsNothing); + }); + + testWidgets( + 'AppSettingsScreen hides Image Messages sub-options until enabled and uses SettingsReveal', + (tester) async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setAutoRouteRotationEnabled(false); + final connector = MeshCoreConnector(); + final translation = TranslationService(settings); + final codec = ImageCodecService( + settings, + settingsStore: InMemoryImageCodecSettingsStore( + const ImageCodecPreferences(), + ), + ); + final uploads = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + addTearDown(connector.dispose); + addTearDown(translation.dispose); + addTearDown(codec.dispose); + addTearDown(uploads.dispose); + + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: codec), + ChangeNotifierProvider.value(value: uploads), + ], + child: MaterialApp( + theme: MeshTheme.dark(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const AppSettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + final context = tester.element(find.byType(AppSettingsScreen)); + final l10n = AppLocalizations.of(context); + final spec = imageCodecPresetModels.single; + + await tester.scrollUntilVisible( + find.text(l10n.imageMessages_enableTitle), + 300, + scrollable: find.byType(Scrollable).first, + ); + await tester.pumpAndSettle(); + + expect(find.text(l10n.imageMessages_enableTitle), findsOneWidget); + expect(find.text(l10n.imageMessages_autoProcessTitle), findsNothing); + expect(find.text(l10n.imageMessages_modelSectionTitle), findsNothing); + expect(find.text(spec.label), findsNothing); + + await tester.tap(find.text(l10n.imageMessages_enableTitle)); + await tester.pump(); + await tester.pump(RevealOnEnable.duration); + await tester.pumpAndSettle(); + + await tester.scrollUntilVisible( + find.text(spec.label), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.pumpAndSettle(); + + expect(find.text(l10n.imageMessages_autoProcessTitle), findsOneWidget); + expect(find.text(l10n.imageMessages_modelSectionTitle), findsOneWidget); + expect(find.text(spec.label), findsOneWidget); + expect( + find.descendant( + of: find.byType(ImageCodecModelsSection), + matching: find.byIcon(Icons.memory_outlined), + ), + findsOneWidget, + ); + + final imageReveal = find.ancestor( + of: find.byType(ImageCodecModelsSection), + matching: find.byType(SettingsReveal), + ); + expect(imageReveal, findsOneWidget); + + await tester.ensureVisible(find.text(l10n.imageMessages_enableTitle)); + await tester.pumpAndSettle(); + await tester.tap(find.text(l10n.imageMessages_enableTitle)); + await tester.pumpAndSettle(); + expect(find.text(l10n.imageMessages_autoProcessTitle), findsNothing); + expect(find.text(spec.label), findsNothing); + }, + ); + + for (final scale in [1.3, 2.0]) { + testWidgets( + 'AppSettingsScreen with Image Messages and Translation expanded fits 320dp at ${scale}x', + (tester) async { + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + if (details.exceptionAsString().contains('overflowed')) { + overflows.add(details.exceptionAsString().split('\n').first); + return; + } + previous?.call(details); + }; + addTearDown(() => FlutterError.onError = previous); + + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setImageMessagesEnabled(true); + await settings.setTranslationEnabled(true); + final connector = MeshCoreConnector(); + final translation = TranslationService(settings); + final codec = ImageCodecService( + settings, + settingsStore: InMemoryImageCodecSettingsStore( + const ImageCodecPreferences(enabled: true), + ), + ); + final uploads = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + addTearDown(connector.dispose); + addTearDown(translation.dispose); + addTearDown(codec.dispose); + addTearDown(uploads.dispose); + + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: codec), + ChangeNotifierProvider.value(value: uploads), + ], + child: MaterialApp( + theme: MeshTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: const AppSettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + expect(overflows, isEmpty); + }, + ); + } +} From d76d488e456dde7140d911f9f9de4a65298528d5 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:10:43 -0700 Subject: [PATCH 29/50] Add optional SMAZ compression indicator icon on messages --- documentation/settings.md | 1 + lib/connector/meshcore_connector.dart | 58 +- lib/l10n/app_en.arb | 5 +- lib/l10n/app_localizations.dart | 18 + lib/l10n/app_localizations_bg.dart | 11 + lib/l10n/app_localizations_cs.dart | 11 + lib/l10n/app_localizations_de.dart | 11 + lib/l10n/app_localizations_en.dart | 11 + lib/l10n/app_localizations_es.dart | 11 + lib/l10n/app_localizations_fr.dart | 11 + lib/l10n/app_localizations_hu.dart | 11 + lib/l10n/app_localizations_it.dart | 11 + lib/l10n/app_localizations_ja.dart | 11 + lib/l10n/app_localizations_ko.dart | 11 + lib/l10n/app_localizations_nl.dart | 11 + lib/l10n/app_localizations_pl.dart | 11 + lib/l10n/app_localizations_pt.dart | 11 + lib/l10n/app_localizations_ru.dart | 11 + lib/l10n/app_localizations_sk.dart | 11 + lib/l10n/app_localizations_sl.dart | 11 + lib/l10n/app_localizations_sv.dart | 11 + lib/l10n/app_localizations_uk.dart | 11 + lib/l10n/app_localizations_zh.dart | 11 + lib/models/app_settings.dart | 8 + lib/models/channel_message.dart | 11 +- lib/models/message.dart | 13 +- lib/screens/app_settings_screen.dart | 14 + lib/screens/channel_chat_screen.dart | 25 +- lib/screens/chat_screen.dart | 8 + lib/services/app_settings_service.dart | 6 + lib/services/message_retry_service.dart | 4 + lib/storage/channel_message_store.dart | 12 +- lib/storage/message_store.dart | 11 +- lib/widgets/message_bubble_frame.dart | 23 + test/models/compression_indicator_test.dart | 349 +++++++++++ test/widgets/compression_indicator_test.dart | 584 +++++++++++++++++++ 36 files changed, 1321 insertions(+), 38 deletions(-) create mode 100644 test/models/compression_indicator_test.dart create mode 100644 test/widgets/compression_indicator_test.dart diff --git a/documentation/settings.md b/documentation/settings.md index 91b2af5e..9600dd14 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -127,6 +127,7 @@ Individual channels can be muted from the channel chat bell icon, the channel li - **Reset Routing Algorithm to Default**: Restores the routing settings to their factory defaults - **Enable Message Tracing**: Shows path trace overlays and extra metadata on messages - **Region next to hop count** (default off): Shows a channel message's region chip on the same line as its hop count instead of below it +- **Compression indicator** (default off): Shows an icon on direct and channel messages that were compressed with SMAZ - **Resend channel messages until they travel far enough** (default off): If your channel message isn't heard coming back through enough repeaters, it's sent again. Uses more airtime. When on, it shows: - Required hops (1–8, default 2) - Resend up to (1–5 times, default 1) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 1b671f77..5df949aa 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5171,9 +5171,8 @@ class MeshCoreConnector extends ChangeNotifier { }) async { if (!isConnected || text.isEmpty) return; - final outboundBytes = utf8.encode( - prepareContactOutboundText(contact, text), - ); + final prepared = prepareContactOutbound(contact, text); + final outboundBytes = utf8.encode(prepared.text); if (outboundBytes.length > maxTextPayloadBytes) { debugPrint( 'sendMessage: dropping overlong message ' @@ -5222,6 +5221,7 @@ class MeshCoreConnector extends ChangeNotifier { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + isSmazCompressed: prepared.isSmazCompressed, ); } else { // Fallback to old behavior if retry service not initialized @@ -5234,11 +5234,11 @@ class MeshCoreConnector extends ChangeNotifier { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + isSmazCompressed: prepared.isSmazCompressed, ); _addMessage(contact.publicKeyHex, message); // recipient as "sender" notifyListeners(); - final outboundText = prepareContactOutboundText(contact, text); - await sendFrame(buildSendTextMsgFrame(contact.publicKey, outboundText)); + await sendFrame(buildSendTextMsgFrame(contact.publicKey, prepared.text)); } } @@ -5661,6 +5661,7 @@ class MeshCoreConnector extends ChangeNotifier { // we continue to process it normally. } + final prepared = prepareChannelOutbound(channel.index, text); final message = ChannelMessage.outgoing( text, _selfName ?? 'Me', @@ -5670,12 +5671,13 @@ class MeshCoreConnector extends ChangeNotifier { translationModelId: translationModelId, region: sendRegion, replyTo: replyTo, + isSmazCompressed: prepared.isSmazCompressed, ); _addChannelMessage(channel.index, message); _pendingChannelSentQueue.add(message.messageId); notifyListeners(); - final outboundText = prepareChannelOutboundText(channel.index, text); + final outboundText = prepared.text; // Resends reuse the timestamp, so they are the same packet: repeaters // that already forwarded it drop the copy and recipients see it once. Future transmit({bool isResend = false}) => @@ -8333,9 +8335,8 @@ class MeshCoreConnector extends ChangeNotifier { appLogger.warn('Received message with empty text, ignoring'); return null; } - final decodedText = isCli - ? msgText - : (Smaz.tryDecodePrefixed(msgText) ?? msgText); + final smazDecoded = isCli ? null : Smaz.tryDecodePrefixed(msgText); + final decodedText = smazDecoded ?? msgText; final contact = _contacts.cast().firstWhere( (c) => c != null && _matchesPrefix(c.publicKey, senderPrefix), @@ -8355,6 +8356,7 @@ class MeshCoreConnector extends ChangeNotifier { receivedAt: DateTime.now(), isOutgoing: false, isCli: isCli, + isSmazCompressed: smazDecoded != null, status: MessageStatus.delivered, pathLength: pathLength == 0xFF ? null : (pathLength & 0x3F), pathBytes: Uint8List(0), @@ -8484,7 +8486,13 @@ class MeshCoreConnector extends ChangeNotifier { /// Prepares contact outbound text by applying SMAZ encoding if enabled. /// This should be used to transform text before computing ACK hashes. - String prepareContactOutboundText(Contact contact, String text) { + String prepareContactOutboundText(Contact contact, String text) => + prepareContactOutbound(contact, text).text; + + ({String text, bool isSmazCompressed}) prepareContactOutbound( + Contact contact, + String text, + ) { final trimmed = text.trim(); final isStructuredPayload = trimmed.startsWith('g:') || @@ -8492,7 +8500,8 @@ class MeshCoreConnector extends ChangeNotifier { trimmed.startsWith('V1|'); if (!isStructuredPayload) { if (isContactSmazEnabled(contact.publicKeyHex)) { - return Smaz.encodeIfSmaller(text); + final encoded = Smaz.encodeIfSmaller(text); + return (text: encoded, isSmazCompressed: encoded != text); } else if (isContactCyr2LatEnabled(contact.publicKeyHex)) { final profileId = getContactCyr2LatProfileId(contact.publicKeyHex); final profile = profileId != null && _appSettingsService != null @@ -8508,19 +8517,26 @@ class MeshCoreConnector extends ChangeNotifier { Cyr2Lat.setCharMap(globalProfile.charMap); } } - return Cyr2Lat.encode(text); + return (text: Cyr2Lat.encode(text), isSmazCompressed: false); } } - return text; + return (text: text, isSmazCompressed: false); } - String prepareChannelOutboundText(int channelIndex, String text) { + String prepareChannelOutboundText(int channelIndex, String text) => + prepareChannelOutbound(channelIndex, text).text; + + ({String text, bool isSmazCompressed}) prepareChannelOutbound( + int channelIndex, + String text, + ) { final trimmed = text.trim(); final isStructuredPayload = trimmed.startsWith('g:') || trimmed.startsWith('m:'); if (!isStructuredPayload) { if (isChannelSmazEnabled(channelIndex)) { - return Smaz.encodeIfSmaller(text); + final encoded = Smaz.encodeIfSmaller(text); + return (text: encoded, isSmazCompressed: encoded != text); } else if (isChannelCyr2LatEnabled(channelIndex)) { final profileId = getChannelCyr2LatProfileId(channelIndex); final profile = profileId != null && _appSettingsService != null @@ -8536,10 +8552,10 @@ class MeshCoreConnector extends ChangeNotifier { Cyr2Lat.setCharMap(globalProfile.charMap); } } - return Cyr2Lat.encode(text); + return (text: Cyr2Lat.encode(text), isSmazCompressed: false); } } - return text; + return (text: text, isSmazCompressed: false); } // Falls back to the cached channel list, which stays populated while a @@ -8727,8 +8743,8 @@ class MeshCoreConnector extends ChangeNotifier { final text = decrypted.readCString(); final parsed = _splitSenderText(text); - final decodedText = - Smaz.tryDecodePrefixed(parsed.text) ?? parsed.text; + final smazDecoded = Smaz.tryDecodePrefixed(parsed.text); + final decodedText = smazDecoded ?? parsed.text; if (_shouldDropSelfChannelMessage( parsed.senderName, packet.pathBytes, @@ -8758,6 +8774,7 @@ class MeshCoreConnector extends ChangeNotifier { timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), receivedAt: DateTime.now(), isOutgoing: false, + isSmazCompressed: smazDecoded != null, status: ChannelMessageStatus.sent, pathLength: packet.isFlood ? packet.hopCount : 0, pathHashWidth: packet.pathHashWidth, @@ -9572,6 +9589,7 @@ class MeshCoreConnector extends ChangeNotifier { timestamp: message.timestamp, receivedAt: message.receivedAt, isOutgoing: message.isOutgoing, + isSmazCompressed: message.isSmazCompressed, status: message.status, repeats: message.repeats, repeatCount: message.repeatCount, @@ -9620,6 +9638,8 @@ class MeshCoreConnector extends ChangeNotifier { existing.status == ChannelMessageStatus.pending; messages[existingIndex] = existing.copyWith( repeatCount: newRepeatCount, + isSmazCompressed: + existing.isSmazCompressed || processedMessage.isSmazCompressed, pathLength: mergedPathLength, pathHashWidth: existing.pathHashWidth ?? processedMessage.pathHashWidth, pathBytes: mergedPathBytes, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 309e0f38..10861b8a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -601,6 +601,8 @@ "appSettings_enableMessageTracingSubtitle": "Also show repeat counts and trip times. Long-press a message and choose Path for full details.", "appSettings_regionOnHopsLine": "Region next to hop count", "appSettings_regionOnHopsLineSubtitle": "Show a channel message's region on the same line as its hop count instead of below it.", + "appSettings_showCompressionIndicator": "Compression indicator", + "appSettings_showCompressionIndicatorSubtitle": "Show an icon on messages compressed with SMAZ.", "appSettings_notifications": "Notifications", "appSettings_enableNotifications": "Enable Notifications", "appSettings_enableNotificationsSubtitle": "Receive notifications for messages and adverts", @@ -4359,5 +4361,6 @@ "chatCompression_cyr2latDescription": "Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.", "chatCompression_profile": "Cyr2Lat profile", "chatCompression_noStorageId": "Can't change compression until this channel has synced from the radio.", - "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting." + "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting.", + "messageMeta_smazCompressed": "SMAZ compressed" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index d8cd16a7..fece5be6 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2533,6 +2533,18 @@ abstract class AppLocalizations { /// **'Show a channel message\'s region on the same line as its hop count instead of below it.'** String get appSettings_regionOnHopsLineSubtitle; + /// No description provided for @appSettings_showCompressionIndicator. + /// + /// In en, this message translates to: + /// **'Compression indicator'** + String get appSettings_showCompressionIndicator; + + /// No description provided for @appSettings_showCompressionIndicatorSubtitle. + /// + /// In en, this message translates to: + /// **'Show an icon on messages compressed with SMAZ.'** + String get appSettings_showCompressionIndicatorSubtitle; + /// No description provided for @appSettings_notifications. /// /// In en, this message translates to: @@ -12693,6 +12705,12 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Couldn\'t save the compression setting. Showing the saved setting.'** String get chatCompression_saveFailed; + + /// No description provided for @messageMeta_smazCompressed. + /// + /// In en, this message translates to: + /// **'SMAZ compressed'** + String get messageMeta_smazCompressed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 9137083e..1a6d1a16 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1385,6 +1386,13 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Показвай региона на съобщението в канала на същия ред като броя хопове, а не под него.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Уведомления'; @@ -7618,4 +7626,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 7cdca68f..4dbc6eae 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1376,6 +1377,13 @@ class AppLocalizationsCs extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Zobrazit region zprávy kanálu na stejném řádku jako počet skoků místo pod ním.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Oznámení'; @@ -7589,4 +7597,7 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index e0a989f5..7c6d745a 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1384,6 +1385,13 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Die Region einer Kanalnachricht in derselben Zeile wie die Hop-Anzahl anzeigen statt darunter.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Benachrichtigungen'; @@ -7633,4 +7641,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index fcf4103f..3b1b58fb 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1359,6 +1360,13 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Show a channel message\'s region on the same line as its hop count instead of below it.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifications'; @@ -7505,4 +7513,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index bbb587a3..d48cca85 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1377,6 +1378,13 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Mostrar la región de un mensaje de canal en la misma línea que su número de saltos en lugar de debajo.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notificaciones'; @@ -7610,4 +7618,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index b5d3dd70..c6e838ba 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1383,6 +1384,13 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Afficher la région d\'un message de canal sur la même ligne que son nombre de sauts plutôt qu\'en dessous.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifications'; @@ -7638,4 +7646,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 2fa18998..9e7624f3 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1376,6 +1377,13 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'A csatornaüzenet régiója az ugrásszámmal azonos sorban jelenik meg, nem alatta.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Értesítések'; @@ -7602,4 +7610,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index d3d64ae8..c1ff0afa 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1381,6 +1382,13 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Mostra la regione di un messaggio di canale sulla stessa riga del numero di salti invece che sotto.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifiche'; @@ -7622,4 +7630,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index eab41908..8558cc9b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1316,6 +1317,13 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'チャンネルメッセージの地域を、ホップ数の下ではなく同じ行に表示します。'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => '通知'; @@ -7265,4 +7273,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 972fb14b..7f995d8f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1319,6 +1320,13 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => '채널 메시지의 지역을 홉 수 아래가 아닌 같은 줄에 표시합니다.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => '알림'; @@ -7278,4 +7286,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 63a93b81..e9990b6a 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1374,6 +1375,13 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Toon de regio van een kanaalbericht op dezelfde regel als het aantal hops in plaats van eronder.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notificaties'; @@ -7578,4 +7586,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index db206b72..50091540 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1387,6 +1388,13 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Pokaż region wiadomości kanału w tym samym wierszu co liczba hopów, zamiast pod nią.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Powiadomienia'; @@ -7656,4 +7664,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 8d001c90..6ed1cc4d 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1380,6 +1381,13 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Mostra a região de uma mensagem de canal na mesma linha da contagem de saltos, em vez de abaixo dela.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notificações'; @@ -7600,6 +7608,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index cd25ee72..f3b1fc1d 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1379,6 +1380,13 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Показывать регион сообщения канала в одной строке с числом хопов, а не под ней.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Уведомления'; @@ -7636,4 +7644,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index eec52038..b421b418 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1374,6 +1375,13 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Zobraziť región správy kanála v rovnakom riadku ako počet skokov namiesto pod ním.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Upozornenia'; @@ -7601,4 +7609,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 700c7bb3..fdfee515 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1373,6 +1374,13 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Regijo sporočila kanala prikaži v isti vrstici kot število skokov, ne pod njim.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Obvestila'; @@ -7595,4 +7603,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 80813df9..f2ea9363 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1364,6 +1365,13 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Visa ett kanalmeddelandes region på samma rad som dess hoppantal i stället för under det.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifieringar'; @@ -7555,4 +7563,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index eccf45ef..2073194f 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1375,6 +1376,13 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Показувати регіон повідомлення каналу в одному рядку з кількістю хопів, а не під ним.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Сповіщення'; @@ -7648,4 +7656,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 078822ce..b641b911 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1297,6 +1298,13 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => '将频道消息的地区与跳数显示在同一行,而不是在其下方。'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => '通知'; @@ -7108,4 +7116,7 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 9b2b80b6..3b27ae72 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -120,6 +120,7 @@ class AppSettings { final bool mapClusterNodes; final bool enableMessageTracing; final bool regionOnHopsLine; + final bool showCompressionIndicator; final Map? mapCacheBounds; final int mapCacheMinZoom; final int mapCacheMaxZoom; @@ -274,6 +275,7 @@ class AppSettings { this.mapClusterNodes = true, this.enableMessageTracing = false, this.regionOnHopsLine = false, + this.showCompressionIndicator = false, this.mapCacheBounds, this.mapCacheMinZoom = 10, this.mapCacheMaxZoom = 15, @@ -371,6 +373,7 @@ class AppSettings { 'map_cluster_nodes': mapClusterNodes, 'enable_message_tracing': enableMessageTracing, 'region_on_hops_line': regionOnHopsLine, + 'show_compression_indicator': showCompressionIndicator, 'map_cache_bounds': mapCacheBounds, 'map_cache_min_zoom': mapCacheMinZoom, 'map_cache_max_zoom': mapCacheMaxZoom, @@ -508,6 +511,8 @@ class AppSettings { mapClusterNodes: json['map_cluster_nodes'] as bool? ?? true, enableMessageTracing: json['enable_message_tracing'] as bool? ?? false, regionOnHopsLine: json['region_on_hops_line'] as bool? ?? false, + showCompressionIndicator: + json['show_compression_indicator'] as bool? ?? false, mapCacheBounds: (json['map_cache_bounds'] as Map?)?.map( (key, value) => MapEntry(key.toString(), (value as num).toDouble()), ), @@ -681,6 +686,7 @@ class AppSettings { bool? mapClusterNodes, bool? enableMessageTracing, bool? regionOnHopsLine, + bool? showCompressionIndicator, Object? mapCacheBounds = _unset, int? mapCacheMinZoom, int? mapCacheMaxZoom, @@ -764,6 +770,8 @@ class AppSettings { mapClusterNodes: mapClusterNodes ?? this.mapClusterNodes, enableMessageTracing: enableMessageTracing ?? this.enableMessageTracing, regionOnHopsLine: regionOnHopsLine ?? this.regionOnHopsLine, + showCompressionIndicator: + showCompressionIndicator ?? this.showCompressionIndicator, mapCacheBounds: mapCacheBounds == _unset ? this.mapCacheBounds : mapCacheBounds as Map?, diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index f3460138..861aa30a 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -1,4 +1,5 @@ import 'dart:typed_data'; + import '../connector/meshcore_protocol.dart'; import '../helpers/reaction_helper.dart'; import '../helpers/smaz.dart'; @@ -44,6 +45,7 @@ class ChannelMessage { final DateTime receivedAt; final bool isOutgoing; final bool isBookmarked; + final bool isSmazCompressed; final ChannelMessageStatus status; final List repeats; final int repeatCount; @@ -79,6 +81,7 @@ class ChannelMessage { DateTime? receivedAt, required this.isOutgoing, this.isBookmarked = false, + this.isSmazCompressed = false, this.status = ChannelMessageStatus.pending, this.repeats = const [], this.repeatCount = 0, @@ -120,6 +123,7 @@ class ChannelMessage { ChannelMessage copyWith({ ChannelMessageStatus? status, bool? isBookmarked, + bool? isSmazCompressed, List? repeats, int? repeatCount, int? pathLength, @@ -163,6 +167,7 @@ class ChannelMessage { receivedAt: receivedAt, isOutgoing: isOutgoing, isBookmarked: isBookmarked ?? this.isBookmarked, + isSmazCompressed: isSmazCompressed ?? this.isSmazCompressed, status: status ?? this.status, repeats: repeats ?? this.repeats, repeatCount: repeatCount ?? this.repeatCount, @@ -252,7 +257,8 @@ class ChannelMessage { } } - final decodedText = Smaz.tryDecodePrefixed(actualText) ?? actualText; + final smazDecoded = Smaz.tryDecodePrefixed(actualText); + final decodedText = smazDecoded ?? actualText; return ChannelMessage( senderKey: null, @@ -261,6 +267,7 @@ class ChannelMessage { timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), receivedAt: DateTime.now(), isOutgoing: false, + isSmazCompressed: smazDecoded != null, status: ChannelMessageStatus.sent, pathLength: pathLen, pathHashWidth: packetPathHashWidth, @@ -283,6 +290,7 @@ class ChannelMessage { String? translationModelId, String? region, ChannelMessage? replyTo, + bool isSmazCompressed = false, }) { return ChannelMessage( senderKey: null, @@ -296,6 +304,7 @@ class ChannelMessage { replyToText: replyTo?.text, timestamp: DateTime.now(), isOutgoing: true, + isSmazCompressed: isSmazCompressed, status: ChannelMessageStatus.pending, pathLength: null, pathBytes: Uint8List(0), diff --git a/lib/models/message.dart b/lib/models/message.dart index d180b33c..7aad608e 100644 --- a/lib/models/message.dart +++ b/lib/models/message.dart @@ -1,6 +1,8 @@ import 'dart:typed_data'; + import '../connector/meshcore_protocol.dart'; import '../helpers/reaction_helper.dart'; +import '../helpers/smaz.dart'; import 'translation_support.dart'; enum MessageStatus { pending, sent, delivered, failed } @@ -36,6 +38,7 @@ class Message { final bool isOutgoing; final bool isBookmarked; final bool isCli; + final bool isSmazCompressed; final MessageStatus status; final String? originalText; final String? translatedText; @@ -65,6 +68,7 @@ class Message { required this.isOutgoing, this.isBookmarked = false, this.isCli = false, + this.isSmazCompressed = false, this.status = MessageStatus.pending, String? messageId, this.originalText, @@ -110,6 +114,7 @@ class Message { int? pathLength, Uint8List? pathBytes, bool? isCli, + bool? isSmazCompressed, bool? isBookmarked, Object? originalText = _unset, Object? translatedText = _unset, @@ -128,6 +133,7 @@ class Message { isOutgoing: isOutgoing, isBookmarked: isBookmarked ?? this.isBookmarked, isCli: isCli ?? this.isCli, + isSmazCompressed: isSmazCompressed ?? this.isSmazCompressed, status: status ?? this.status, messageId: messageId, originalText: originalText == _unset @@ -173,7 +179,9 @@ class Message { if ((flags >> 2) != txtTypePlain) { return null; } - final text = reader.readCString(); + final rawText = reader.readCString(); + final smazDecoded = Smaz.tryDecodePrefixed(rawText); + final text = smazDecoded ?? rawText; return Message( senderKey: senderKey, @@ -182,6 +190,7 @@ class Message { receivedAt: DateTime.now(), isOutgoing: false, isCli: false, + isSmazCompressed: smazDecoded != null, status: MessageStatus.delivered, pathBytes: Uint8List(0), ); @@ -198,6 +207,7 @@ class Message { String? translationModelId, int? pathLength, Uint8List? pathBytes, + bool isSmazCompressed = false, }) { return Message( senderKey: recipientKey, @@ -208,6 +218,7 @@ class Message { timestamp: DateTime.now(), isOutgoing: true, isCli: false, + isSmazCompressed: isSmazCompressed, status: MessageStatus.pending, pathLength: pathLength, pathBytes: pathBytes, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 126216cb..aa749cd2 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -488,6 +488,20 @@ class AppSettingsScreen extends StatelessWidget { value: settingsService.settings.regionOnHopsLine, onChanged: settingsService.setRegionOnHopsLine, ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.compress, size: 24), + title: Text(context.l10n.appSettings_showCompressionIndicator), + subtitle: Text( + context.l10n.appSettings_showCompressionIndicatorSubtitle, + ), + value: settingsService.settings.showCompressionIndicator, + onChanged: settingsService.setShowCompressionIndicator, + ), ], ); } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 35bc8a71..acc29664 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1109,6 +1109,8 @@ class _ChannelChatScreenState extends State { final publicIpfsGateway = settingsService.settings.publicIpfsGateway; final enableTracing = settingsService.settings.enableMessageTracing; final regionOnHopsLine = settingsService.settings.regionOnHopsLine; + final showCompressionIndicator = + settingsService.settings.showCompressionIndicator; final isOutgoing = message.isOutgoing; final scheme = Theme.of(context).colorScheme; final gifId = GifHelper.parseGif(message.text); @@ -1423,8 +1425,10 @@ class _ChannelChatScreenState extends State { bottom: 4, ) : EdgeInsets.zero, - child: Row( - mainAxisSize: MainAxisSize.min, + child: Wrap( + spacing: 4, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( formatChatTime(context, message.timestamp), @@ -1433,20 +1437,23 @@ class _ChannelChatScreenState extends State { color: metaColor, ), ), - if (message.hasFutureTimestamp) ...[ - const SizedBox(width: 4), + if (message.hasFutureTimestamp) FutureTimestampIndicator(size: 16 * textScale), - ], + if (showCompressionIndicator && + message.isSmazCompressed) + CompressionIndicator( + size: 14 * textScale, + color: metaColor, + ), if (enableTracing && !isOutgoing && message.repeatCount > 0) ...[ - const SizedBox(width: 6), + const SizedBox(width: 2), Icon( Icons.repeat, size: 14 * textScale, color: metaColor, ), - const SizedBox(width: 2), Text( '${message.repeatCount}', style: MeshTheme.mono( @@ -1455,8 +1462,7 @@ class _ChannelChatScreenState extends State { ), ), ], - if (isOutgoing) ...[ - const SizedBox(width: 4), + if (isOutgoing) MessageStatusIcon( size: 16 * textScale, isAcked: false, @@ -1476,7 +1482,6 @@ class _ChannelChatScreenState extends State { ChannelMessageStatus.failed, onColor: metaColor, ), - ], ], ), ), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 45839b52..2136b488 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -1574,6 +1574,8 @@ class _MessageBubble extends StatelessWidget { Widget build(BuildContext context) { final settingsService = context.watch(); final enableTracing = settingsService.settings.enableMessageTracing; + final showCompressionIndicator = + settingsService.settings.showCompressionIndicator; final isOutgoing = message.isOutgoing; final scheme = Theme.of(context).colorScheme; final gifId = GifHelper.parseGif(message.text); @@ -1838,6 +1840,12 @@ class _MessageBubble extends StatelessWidget { FutureTimestampIndicator( size: 16 * textScale, ), + if (showCompressionIndicator && + message.isSmazCompressed) + CompressionIndicator( + size: 14 * textScale, + color: metaColor, + ), if (isOutgoing) ...[ const SizedBox(width: 2), MessageStatusIcon( diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index d0758681..d8e5c714 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'dart:convert'; + import 'package:flutter/foundation.dart'; + import '../models/app_settings.dart'; import '../models/custom_theme.dart'; import '../models/holiday_schedule.dart'; @@ -135,6 +137,10 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(regionOnHopsLine: value)); } + Future setShowCompressionIndicator(bool value) async { + await updateSettings(_settings.copyWith(showCompressionIndicator: value)); + } + Future setMapCacheBounds(Map? value) async { await updateSettings(_settings.copyWith(mapCacheBounds: value)); } diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 4495ce91..9b38b8c4 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -1,8 +1,10 @@ import 'dart:async'; import 'dart:convert'; + import 'package:flutter/foundation.dart'; import 'package:uuid/uuid.dart'; import 'package:crypto/crypto.dart'; + import '../connector/meshcore_protocol.dart'; import '../models/contact.dart'; import '../models/message.dart'; @@ -169,6 +171,7 @@ class MessageRetryService extends ChangeNotifier { String? translationModelId, Uint8List? pathBytes, int? pathLength, + bool isSmazCompressed = false, }) async { final messageId = const Uuid().v4(); final resolved = resolvePathSelection(contact); @@ -184,6 +187,7 @@ class MessageRetryService extends ChangeNotifier { translationModelId: translationModelId, timestamp: DateTime.now(), isOutgoing: true, + isSmazCompressed: isSmazCompressed, status: MessageStatus.pending, messageId: messageId, retryCount: 0, diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 5383b59a..7e6a7914 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:typed_data'; + import 'package:meshcore_open/utils/app_logger.dart'; import '../models/channel_message.dart'; @@ -160,6 +161,7 @@ class ChannelMessageStore { 'receivedAt': msg.receivedAt.millisecondsSinceEpoch, 'isOutgoing': msg.isOutgoing, 'isBookmarked': msg.isBookmarked, + 'isSmazCompressed': msg.isSmazCompressed, 'status': msg.status.index, 'channelIndex': msg.channelIndex, 'region': msg.region, @@ -186,9 +188,12 @@ class ChannelMessageStore { /// Convert JSON map to ChannelMessage ChannelMessage _messageFromJson(Map json) { final rawText = json['text'] as String; - final decodedText = json['plainText'] == true - ? rawText - : (Smaz.tryDecodePrefixed(rawText) ?? rawText); + final smazDecoded = json['plainText'] == true + ? null + : Smaz.tryDecodePrefixed(rawText); + final decodedText = smazDecoded ?? rawText; + final isSmazCompressed = + json['isSmazCompressed'] as bool? ?? (smazDecoded != null); final rawPathLength = json['pathLength'] as int?; final rawPathBytes = json['pathBytes'] != null @@ -238,6 +243,7 @@ class ChannelMessageStore { receivedAt: legacyAwareReceivedAt(json), isOutgoing: json['isOutgoing'] as bool? ?? false, isBookmarked: json['isBookmarked'] as bool? ?? false, + isSmazCompressed: isSmazCompressed, status: _statusAt(json['status']) ?? ChannelMessageStatus.failed, repeatCount: (json['repeatCount'] as int?) ?? 0, pathLength: decodedPathLength, diff --git a/lib/storage/message_store.dart b/lib/storage/message_store.dart index fec500d1..94ab883a 100644 --- a/lib/storage/message_store.dart +++ b/lib/storage/message_store.dart @@ -202,6 +202,7 @@ class MessageStore { 'isOutgoing': msg.isOutgoing, 'isBookmarked': msg.isBookmarked, 'isCli': msg.isCli, + 'isSmazCompressed': msg.isSmazCompressed, 'status': msg.status.index, 'messageId': msg.messageId, 'originalText': msg.originalText, @@ -233,9 +234,12 @@ class MessageStore { Message _messageFromJson(Map json) { final rawText = json['text'] as String; final isCli = json['isCli'] as bool? ?? false; - final decodedText = isCli || json['plainText'] == true - ? rawText - : (Smaz.tryDecodePrefixed(rawText) ?? rawText); + final smazDecoded = (isCli || json['plainText'] == true) + ? null + : Smaz.tryDecodePrefixed(rawText); + final decodedText = smazDecoded ?? rawText; + final isSmazCompressed = + json['isSmazCompressed'] as bool? ?? (smazDecoded != null); final rawPathLength = json['pathLength'] as int?; final rawPathBytes = json['pathBytes'] != null @@ -273,6 +277,7 @@ class MessageStore { isOutgoing: json['isOutgoing'] as bool? ?? false, isBookmarked: json['isBookmarked'] as bool? ?? false, isCli: isCli, + isSmazCompressed: isSmazCompressed, status: _statusAt(json['status']) ?? MessageStatus.failed, messageId: json['messageId'] as String?, originalText: json['originalText'] as String?, diff --git a/lib/widgets/message_bubble_frame.dart b/lib/widgets/message_bubble_frame.dart index 646eb344..976332c2 100644 --- a/lib/widgets/message_bubble_frame.dart +++ b/lib/widgets/message_bubble_frame.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; +import '../l10n/l10n.dart'; import '../theme/mesh_theme.dart'; /// Colours shared by the direct-message and channel chat bubbles. @@ -149,3 +150,25 @@ class MessageBubbleFrame extends StatelessWidget { ); } } + +/// Subtle indicator shown in a message bubble's metadata row when SMAZ +/// compression was applied to the message. +class CompressionIndicator extends StatelessWidget { + final double size; + final Color color; + + const CompressionIndicator({super.key, this.size = 14, required this.color}); + + @override + Widget build(BuildContext context) { + final label = context.l10n.messageMeta_smazCompressed; + return Tooltip( + message: label, + triggerMode: TooltipTriggerMode.tap, + child: Semantics( + label: label, + child: Icon(Icons.compress, size: size, color: color), + ), + ); + } +} diff --git a/test/models/compression_indicator_test.dart b/test/models/compression_indicator_test.dart new file mode 100644 index 00000000..173269d4 --- /dev/null +++ b/test/models/compression_indicator_test.dart @@ -0,0 +1,349 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/helpers/smaz.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/chat_compression_mode.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/history_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _deviceScope = 'abcdef012345'; +const _contactHex = + '1111111111111111111111111111111111111111111111111111111111111111'; +const _channelId = '0123456789abcdef'; +const _compressibleText = + 'This is a long enough English sentence that SMAZ compresses smaller.'; + +Uint8List _legacyDmFrame(Uint8List senderPubKey, String text, int timestamp) { + final writer = BufferWriter(); + writer.writeByte(respCodeContactMsgRecv); + writer.writeBytes(senderPubKey); + writer.writeInt32LE(timestamp); + writer.writeByte(txtTypePlain << 2); + writer.writeString(text); + writer.writeByte(0); + return writer.toBytes(); +} + +Future _waitFor(bool Function() condition) async { + final end = DateTime.now().add(const Duration(seconds: 8)); + while (!condition()) { + if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); + await Future.delayed(const Duration(milliseconds: 20)); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('AppSettings.showCompressionIndicator', () { + test('defaults to false, including for stored JSON without the key', () { + expect(AppSettings().showCompressionIndicator, isFalse); + final legacy = AppSettings().toJson() + ..remove('show_compression_indicator'); + expect(AppSettings.fromJson(legacy).showCompressionIndicator, isFalse); + }); + + test( + 'round-trips through JSON, copyWith, and AppSettingsService', + () async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + + final enabled = AppSettings().copyWith(showCompressionIndicator: true); + expect( + AppSettings.fromJson(enabled.toJson()).showCompressionIndicator, + isTrue, + ); + expect( + enabled.copyWith(enableMessageTracing: true).showCompressionIndicator, + isTrue, + ); + + final service = AppSettingsService(); + await service.loadSettings(); + expect(service.settings.showCompressionIndicator, isFalse); + + await service.setShowCompressionIndicator(true); + expect(service.settings.showCompressionIndicator, isTrue); + + final reloaded = AppSettingsService(); + await reloaded.loadSettings(); + expect(reloaded.settings.showCompressionIndicator, isTrue); + }, + ); + }); + + group('Message & MessageStore SMAZ flag', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + MessageStore().forgetArchive(); + }); + + test('Message.fromFrame decodes SMAZ and sets isSmazCompressed', () { + final sender = Uint8List.fromList(List.generate(32, (i) => i + 1)); + final encoded = Smaz.encodeIfSmaller(_compressibleText); + expect(encoded, startsWith('s:')); + + final compressedMsg = Message.fromFrame( + _legacyDmFrame(sender, encoded, 1700000000), + Uint8List(32), + )!; + expect(compressedMsg.text, _compressibleText); + expect(compressedMsg.isSmazCompressed, isTrue); + expect(compressedMsg.copyWith(retryCount: 1).isSmazCompressed, isTrue); + + final plainMsg = Message.fromFrame( + _legacyDmFrame(sender, 'plain hello', 1700000001), + Uint8List(32), + )!; + expect(plainMsg.text, 'plain hello'); + expect(plainMsg.isSmazCompressed, isFalse); + }); + + test( + 'MessageStore persists flag and defaults legacy rows to false', + () async { + final store = MessageStore()..setPublicKeyHex = _deviceScope; + final key = Uint8List.fromList(List.generate(32, (i) => i + 2)); + final compressed = Message.outgoing( + key, + _compressibleText, + isSmazCompressed: true, + ); + final plain = Message.outgoing(key, 'hi', isSmazCompressed: false); + + await store.saveMessages(_contactHex, [compressed, plain]); + final loaded = await store.loadMessages(_contactHex); + expect(loaded, hasLength(2)); + expect(loaded[0].isSmazCompressed, isTrue); + expect(loaded[1].isSmazCompressed, isFalse); + + // Legacy persisted message without `isSmazCompressed` key defaults to false. + await HistoryStore.instance.setString( + '${store.keyFor}$_contactHex', + jsonEncode([ + { + 'senderKey': base64Encode(key), + 'text': 'legacy plain', + 'timestamp': 1700000002000, + 'receivedAt': 1700000002000, + 'isOutgoing': false, + 'status': MessageStatus.delivered.index, + 'plainText': true, + }, + ]), + ); + final legacyLoaded = await store.loadMessages(_contactHex); + expect(legacyLoaded, hasLength(1)); + expect(legacyLoaded.first.isSmazCompressed, isFalse); + }, + ); + }); + + group('ChannelMessage & ChannelMessageStore SMAZ flag', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + ChannelMessageStore().forgetArchive(); + }); + + test('ChannelMessage.fromFrame decodes SMAZ and sets isSmazCompressed', () { + final encoded = Smaz.encodeIfSmaller(_compressibleText); + expect(encoded, startsWith('s:')); + + final compressed = ChannelMessage.fromFrame( + ReviewFrames.channelMessage( + channelIndex: 0, + sender: 'Maya', + message: encoded, + timestampSecs: 1700000000, + ), + )!; + expect(compressed.text, _compressibleText); + expect(compressed.isSmazCompressed, isTrue); + expect(compressed.copyWith(repeatCount: 2).isSmazCompressed, isTrue); + + final plain = ChannelMessage.fromFrame( + ReviewFrames.channelMessage( + channelIndex: 0, + sender: 'Maya', + message: 'hello camp', + timestampSecs: 1700000001, + ), + )!; + expect(plain.text, 'hello camp'); + expect(plain.isSmazCompressed, isFalse); + }); + + test( + 'ChannelMessageStore persists flag and defaults legacy rows to false', + () async { + final store = ChannelMessageStore()..setPublicKeyHex = _deviceScope; + final compressed = ChannelMessage.outgoing( + _compressibleText, + 'Me', + 0, + isSmazCompressed: true, + ); + final plain = ChannelMessage.outgoing( + 'short', + 'Me', + 0, + isSmazCompressed: false, + ); + + await store.saveChannelMessages(_channelId, [compressed, plain]); + final loaded = await store.loadChannelMessages(_channelId); + expect(loaded, hasLength(2)); + expect(loaded[0].isSmazCompressed, isTrue); + expect(loaded[1].isSmazCompressed, isFalse); + + await HistoryStore.instance.setString( + '${store.keyFor}_$_channelId', + jsonEncode([ + { + 'senderName': 'Maya', + 'text': 'legacy channel msg', + 'timestamp': 1700000002000, + 'receivedAt': 1700000002000, + 'isOutgoing': false, + 'status': ChannelMessageStatus.sent.index, + 'channelIndex': 0, + 'plainText': true, + }, + ]), + ); + final legacyLoaded = await store.loadChannelMessages(_channelId); + expect(legacyLoaded, hasLength(1)); + expect(legacyLoaded.first.isSmazCompressed, isFalse); + }, + ); + }); + + group('MeshCoreConnector SMAZ tracking', () { + late MeshCoreConnector connector; + late MessageRetryService retryService; + late ReviewRadio radio; + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + connector = MeshCoreConnector(); + retryService = MessageRetryService(); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + connector.reviewRadioFactoryForTest = () { + radio = ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + return radio; + }; + await connector.connectReview(); + await _waitFor( + () => + connector.channelMapConfirmed && + connector.contacts.isNotEmpty && + connector.channels.isNotEmpty, + ); + addTearDown(() async { + await connector.disconnect(); + connector.dispose(); + retryService.dispose(); + }); + }); + + test( + 'records isSmazCompressed on outgoing DM and channel messages', + () async { + final contact = connector.contacts.first; + final channel = connector.channels.first; + + // Mode off: not SMAZ compressed. + await connector.setContactCompressionMode( + contact.publicKeyHex, + ChatCompressionMode.off, + ); + await connector.sendMessage(contact, _compressibleText); + + // Mode SMAZ: compressible text sets flag, tiny uncompressible text does not. + await connector.setContactCompressionMode( + contact.publicKeyHex, + ChatCompressionMode.smaz, + ); + await connector.sendMessage(contact, _compressibleText); + await connector.sendMessage(contact, 'ok'); + + // Mode Cyr2Lat: not SMAZ compressed. + await connector.setContactCompressionMode( + contact.publicKeyHex, + ChatCompressionMode.cyr2lat, + ); + await connector.sendMessage(contact, 'Привет мир'); + + final dmMessages = connector.getMessages(contact); + final recentDms = dmMessages.sublist(dmMessages.length - 4); + expect(recentDms[0].isSmazCompressed, isFalse); + expect(recentDms[1].isSmazCompressed, isTrue); + expect(recentDms[2].isSmazCompressed, isFalse); + expect(recentDms[3].isSmazCompressed, isFalse); + + // Channel outgoing messages. + await connector.setChannelCompressionMode( + channel.index, + ChatCompressionMode.off, + ); + await connector.sendChannelMessage(channel, _compressibleText); + + await connector.setChannelCompressionMode( + channel.index, + ChatCompressionMode.smaz, + ); + await connector.sendChannelMessage(channel, _compressibleText); + await connector.sendChannelMessage(channel, 'ok'); + + await connector.setChannelCompressionMode( + channel.index, + ChatCompressionMode.cyr2lat, + ); + await connector.sendChannelMessage(channel, 'Привет мир'); + + final chMessages = connector.getChannelMessages(channel); + final recentCh = chMessages.sublist(chMessages.length - 4); + expect(recentCh[0].isSmazCompressed, isFalse); + expect(recentCh[1].isSmazCompressed, isTrue); + expect(recentCh[2].isSmazCompressed, isFalse); + expect(recentCh[3].isSmazCompressed, isFalse); + + // Ensure radio reference stays live without lint warnings. + expect(radio, isNotNull); + }, + ); + }); +} diff --git a/test/widgets/compression_indicator_test.dart b/test/widgets/compression_indicator_test.dart new file mode 100644 index 00000000..2765d24d --- /dev/null +++ b/test/widgets/compression_indicator_test.dart @@ -0,0 +1,584 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/screens/app_settings_screen.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/history_store.dart'; +import 'package:meshcore_open/storage/last_radio_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; +import 'package:meshcore_open/widgets/message_status_icon.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _radioKey = Uint8List.fromList(List.generate(32, (i) => 0xA0 + i)); +final _radioHex = pubKeyToHex(_radioKey); +final _aliceKey = Uint8List.fromList(List.generate(32, (i) => 0x10 + i)); +final _psk = Uint8List.fromList(List.generate(16, (i) => 0x40 + i)); +final _l10n = lookupAppLocalizations(const Locale('en')); + +Future _seedMessages() async { + final alice = Contact( + publicKey: _aliceKey, + name: 'Alice', + type: advTypeChat, + pathLength: 1, + path: Uint8List.fromList([0x22]), + lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ); + await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([alice]); + final channel = Channel(index: 0, name: 'Base Camp', psk: _psk); + final channelStore = ChannelStore()..setPublicKeyHex = _radioHex; + await channelStore.saveChannels([channel]); + await channelStore.saveSlotChannelIds({0: channel.storageId!}); + + await (MessageStore()..setPublicKeyHex = _radioHex) + .saveMessages(alice.publicKeyHex, [ + Message( + senderKey: _aliceKey, + text: 'DM incoming compressed', + timestamp: DateTime(2026, 11, 21, 10, 11), + receivedAt: DateTime(2026, 11, 21, 10, 11), + isOutgoing: false, + isSmazCompressed: true, + status: MessageStatus.delivered, + ), + Message( + senderKey: _aliceKey, + text: 'DM incoming plain', + timestamp: DateTime(2026, 11, 21, 10, 12), + receivedAt: DateTime(2026, 11, 21, 10, 12), + isOutgoing: false, + isSmazCompressed: false, + status: MessageStatus.delivered, + ), + Message( + senderKey: _aliceKey, + text: 'DM outgoing plain', + timestamp: DateTime(2026, 11, 21, 10, 13), + receivedAt: DateTime(2026, 11, 21, 10, 13), + isOutgoing: true, + isSmazCompressed: false, + status: MessageStatus.delivered, + ), + Message( + senderKey: _aliceKey, + text: 'DM outgoing compressed', + timestamp: DateTime(2026, 11, 21, 10, 14), + receivedAt: DateTime(2026, 11, 21, 10, 14), + isOutgoing: true, + isSmazCompressed: true, + status: MessageStatus.delivered, + ), + ]); + + await (ChannelMessageStore()..setPublicKeyHex = _radioHex) + .saveChannelMessages(channel.storageId!, [ + ChannelMessage( + senderName: 'Bob', + text: 'Channel incoming compressed', + timestamp: DateTime(2026, 11, 21, 11, 11), + receivedAt: DateTime(2026, 11, 21, 11, 11), + isOutgoing: false, + isSmazCompressed: true, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ChannelMessage( + senderName: 'Bob', + text: 'Channel incoming plain', + timestamp: DateTime(2026, 11, 21, 11, 12), + receivedAt: DateTime(2026, 11, 21, 11, 12), + isOutgoing: false, + isSmazCompressed: false, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ChannelMessage( + senderName: 'Me', + text: 'Channel outgoing plain', + timestamp: DateTime(2026, 11, 21, 11, 13), + receivedAt: DateTime(2026, 11, 21, 11, 13), + isOutgoing: true, + isSmazCompressed: false, + repeatCount: 1, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ChannelMessage( + senderName: 'Me', + text: 'Channel outgoing compressed', + timestamp: DateTime(2026, 11, 21, 11, 14), + receivedAt: DateTime(2026, 11, 21, 11, 14), + isOutgoing: true, + isSmazCompressed: true, + repeatCount: 2, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ]); + + await LastRadioStore().save( + LastRadio( + publicKeyHex: _radioHex, + name: 'Base', + transport: LastRadio.transportBle, + bleRemoteId: 'AA:BB:CC:DD:EE:FF', + savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ), + ); +} + +class _Harness { + final MeshCoreConnector connector; + final AppSettingsService settings; + final List disposables; + + _Harness(this.connector, this.settings, this.disposables); + + List> get _unused => const []; + + Widget wrap(Widget home, {ThemeData? theme, double textScale = 1.0}) { + final storage = StorageService(); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value( + value: disposables[0] as MessageRetryService, + ), + ChangeNotifierProvider.value( + value: disposables[1] as PathHistoryService, + ), + ChangeNotifierProvider.value( + value: disposables[2] as BleDebugLogService, + ), + ChangeNotifierProvider.value( + value: disposables[3] as AppDebugLogService, + ), + ChangeNotifierProvider.value( + value: disposables[4] as ChatTextScaleService, + ), + ChangeNotifierProvider.value( + value: disposables[5] as TranslationService, + ), + ChangeNotifierProvider.value( + value: disposables[6] as UiViewStateService, + ), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: disposables[7] as MapTileCacheService, + ), + ChangeNotifierProvider.value( + value: disposables[8] as TimeoutPredictionService, + ), + ChangeNotifierProvider.value( + value: disposables[9] as ImageCodecService, + ), + ChangeNotifierProvider.value( + value: disposables[10] as ReceivedImageStore, + ), + ChangeNotifierProvider.value( + value: disposables[11] as NetworkMapUploadService, + ), + ], + child: MaterialApp( + theme: theme ?? MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: TextScaler.linear(textScale), + alwaysUse24HourFormat: true, + ), + child: child!, + ), + home: home, + ), + ); + } + + void dispose() { + assert(_unused.isEmpty); + connector.dispose(); + settings.dispose(); + for (final d in disposables) { + if (d is ChangeNotifier) d.dispose(); + } + } +} + +Future<_Harness> _createHarness({bool showIndicator = false}) async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + MessageStore().forgetArchive(); + ChannelMessageStore().forgetArchive(); + await _seedMessages(); + + final storage = StorageService(); + final settings = AppSettingsService(); + await settings.loadSettings(); + if (showIndicator) { + await settings.setShowCompressionIndicator(true); + } + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final pathHistory = PathHistoryService(storage); + final bleLog = BleDebugLogService(); + final appLog = AppDebugLogService(); + final textScale = ChatTextScaleService(); + final translation = TranslationService(settings); + final uiView = UiViewStateService(); + final tileCache = MapTileCacheService(appSettingsService: settings); + final timeoutPred = TimeoutPredictionService(storage); + final imageCodec = ImageCodecService(settings); + final receivedImage = ReceivedImageStore(); + final networkMap = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + await connector.restoreLastRadio(); + return _Harness(connector, settings, [ + retry, + pathHistory, + bleLog, + appLog, + textScale, + translation, + uiView, + tileCache, + timeoutPred, + imageCodec, + receivedImage, + networkMap, + ]); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync( + 'compression_indicator_test', + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + testWidgets( + 'AppSettingsScreen shows Compression indicator switch and toggles', + (tester) async { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(); + await harness.settings.setAutoRouteRotationEnabled(false); + }); + addTearDown(harness.dispose); + + tester.view.physicalSize = const Size(390, 720); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await tester.pumpWidget(harness.wrap(const AppSettingsScreen())); + await tester.pumpAndSettle(); + + final tileFinder = find.widgetWithText( + SwitchListTile, + _l10n.appSettings_showCompressionIndicator, + ); + await tester.scrollUntilVisible( + tileFinder, + 60, + scrollable: find.byType(Scrollable).first, + ); + await tester.pumpAndSettle(); + + final tile = tester.widget(tileFinder); + expect(tile.value, isFalse); + expect( + find.descendant(of: tileFinder, matching: find.byIcon(Icons.compress)), + findsOneWidget, + ); + + await tester.tap(tileFinder); + await tester.pumpAndSettle(); + expect(harness.settings.settings.showCompressionIndicator, isTrue); + }, + ); + + testWidgets( + 'DM ChatScreen hides icon when off, shows only on compressed when on', + (tester) async { + final semantics = tester.ensureSemantics(); + try { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(showIndicator: false); + }); + addTearDown(harness.dispose); + + final contact = harness.connector.contacts.first; + await tester.pumpWidget(harness.wrap(ChatScreen(contact: contact))); + await tester.pumpAndSettle(); + + expect(find.byType(CompressionIndicator), findsNothing); + + await tester.runAsync( + () => harness.settings.setShowCompressionIndicator(true), + ); + await tester.pumpAndSettle(); + + // Two compressed messages (1 incoming, 1 outgoing); two plain have none. + expect(find.byType(CompressionIndicator), findsNWidgets(2)); + expect( + find.byTooltip(_l10n.messageMeta_smazCompressed), + findsNWidgets(2), + ); + expect( + find.bySemanticsLabel(RegExp(_l10n.messageMeta_smazCompressed)), + findsNWidgets(2), + ); + + // Incoming compressed message: CompressionIndicator sits after timestamp, no ticks. + final incomingBubble = find.ancestor( + of: find.text('DM incoming compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final incomingIndicator = find.descendant( + of: incomingBubble, + matching: find.byType(CompressionIndicator), + ); + final incomingTime = find.descendant( + of: incomingBubble, + matching: find.text('10:11'), + ); + expect(incomingIndicator, findsOneWidget); + expect( + tester.getTopLeft(incomingIndicator).dx, + greaterThan(tester.getTopRight(incomingTime).dx), + ); + expect( + find.descendant( + of: incomingBubble, + matching: find.byType(MessageStatusIcon), + ), + findsNothing, + ); + + // Outgoing compressed message: CompressionIndicator sits between timestamp and ticks. + final outgoingBubble = find.ancestor( + of: find.text('DM outgoing compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final outgoingIndicator = find.descendant( + of: outgoingBubble, + matching: find.byType(CompressionIndicator), + ); + final outgoingTime = find.descendant( + of: outgoingBubble, + matching: find.text('10:14'), + ); + final outgoingTicks = find.descendant( + of: outgoingBubble, + matching: find.byType(MessageStatusIcon), + ); + expect(outgoingIndicator, findsOneWidget); + expect( + tester.getTopLeft(outgoingIndicator).dx, + greaterThan(tester.getTopRight(outgoingTime).dx), + ); + expect( + tester.getTopRight(outgoingIndicator).dx, + lessThanOrEqualTo(tester.getTopLeft(outgoingTicks).dx), + ); + + // Plain messages never show the icon. + final plainBubble = find.ancestor( + of: find.text('DM outgoing plain'), + matching: find.byType(MessageBubbleFrame), + ); + expect( + find.descendant( + of: plainBubble, + matching: find.byType(CompressionIndicator), + ), + findsNothing, + ); + } finally { + semantics.dispose(); + } + }, + ); + + testWidgets( + 'ChannelChatScreen hides icon when off, shows between time and ticks when on', + (tester) async { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(showIndicator: false); + }); + addTearDown(harness.dispose); + + final channel = harness.connector.channels.first; + await tester.pumpWidget( + harness.wrap(ChannelChatScreen(channel: channel)), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CompressionIndicator), findsNothing); + + await tester.runAsync( + () => harness.settings.setShowCompressionIndicator(true), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CompressionIndicator), findsNWidgets(2)); + + // Outgoing compressed channel message: icon between timestamp and repeat ticks. + final outgoingBubble = find.ancestor( + of: find.text('Channel outgoing compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final outgoingIndicator = find.descendant( + of: outgoingBubble, + matching: find.byType(CompressionIndicator), + ); + final outgoingTime = find.descendant( + of: outgoingBubble, + matching: find.text('11:14'), + ); + final outgoingTicks = find.descendant( + of: outgoingBubble, + matching: find.byType(MessageStatusIcon), + ); + expect(outgoingIndicator, findsOneWidget); + expect( + tester.getTopLeft(outgoingIndicator).dx, + greaterThan(tester.getTopRight(outgoingTime).dx), + ); + expect( + tester.getTopRight(outgoingIndicator).dx, + lessThanOrEqualTo(tester.getTopLeft(outgoingTicks).dx), + ); + + // Incoming compressed channel message: icon right after timestamp. + final incomingBubble = find.ancestor( + of: find.text('Channel incoming compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final incomingIndicator = find.descendant( + of: incomingBubble, + matching: find.byType(CompressionIndicator), + ); + final incomingTime = find.descendant( + of: incomingBubble, + matching: find.text('11:11'), + ); + expect(incomingIndicator, findsOneWidget); + expect( + tester.getTopLeft(incomingIndicator).dx, + greaterThan(tester.getTopRight(incomingTime).dx), + ); + }, + ); + + testWidgets('No overflow at 320dp width and 2.0x text scale across themes', ( + tester, + ) async { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(showIndicator: true); + }); + addTearDown(harness.dispose); + + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (text.contains('overflowed')) { + overflows.add(text.split('\n').first); + } else { + previous?.call(details); + } + }; + addTearDown(() => FlutterError.onError = previous); + + final contact = harness.connector.contacts.first; + final channel = harness.connector.channels.first; + + final themes = [ + MeshTheme.light(), + MeshTheme.dark(), + MeshTheme.fromCustom(CustomTheme.presets.first), + ]; + + for (final theme in themes) { + await tester.pumpWidget( + harness.wrap( + ChatScreen(contact: contact), + theme: theme, + textScale: 2.0, + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(CompressionIndicator), findsAtLeastNWidgets(1)); + + await tester.pumpWidget( + harness.wrap( + ChannelChatScreen(channel: channel), + theme: theme, + textScale: 2.0, + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(CompressionIndicator), findsAtLeastNWidgets(1)); + } + + FlutterError.onError = previous; + expect(overflows, isEmpty, reason: overflows.join('\n')); + }); +} From 3e2a1207dd1785cf5b8c47540225392f8462e377 Mon Sep 17 00:00:00 2001 From: Juraj Bednar Date: Sat, 21 Nov 2026 15:58:31 +0100 Subject: [PATCH 30/50] Slovak: translate the 37 strings that were still in English --- lib/l10n/app_localizations_sk.dart | 87 ++++++++++---------- lib/l10n/app_sk.arb | 39 ++++++++- untranslated.json | 127 ++++++++++++++++------------- 3 files changed, 154 insertions(+), 99 deletions(-) diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 2be7f8c4..d77c0a0d 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1,6 +1,5 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; - import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -530,7 +529,7 @@ class AppLocalizationsSk extends AppLocalizations { 'Objavené kontakty a ich uložené údaje'; @override - String get backupRestore_bookmarks => 'Bookmarks'; + String get backupRestore_bookmarks => 'Záložky'; @override String get backupRestore_channels => 'Kanály'; @@ -1375,11 +1374,11 @@ class AppLocalizationsSk extends AppLocalizations { 'Zobraziť región správy kanála v rovnakom riadku ako počet skokov namiesto pod ním.'; @override - String get appSettings_showCompressionIndicator => 'Compression indicator'; + String get appSettings_showCompressionIndicator => 'Indikátor kompresie'; @override String get appSettings_showCompressionIndicatorSubtitle => - 'Show an icon on messages compressed with SMAZ.'; + 'Zobraziť ikonu pri správach komprimovaných metódou SMAZ.'; @override String get appSettings_notifications => 'Upozornenia'; @@ -1832,7 +1831,7 @@ class AppLocalizationsSk extends AppLocalizations { String get contacts_lastSeenNow => 'nedávno'; @override - String get contacts_lastSeenNever => 'not heard yet'; + String get contacts_lastSeenNever => 'zatiaľ nezachytený'; @override String contacts_lastSeenMinsAgo(int minutes) { @@ -2270,28 +2269,28 @@ class AppLocalizationsSk extends AppLocalizations { String get chat_messageDeleted => 'Správa odstránená'; @override - String get chat_bookmark => 'Bookmark'; + String get chat_bookmark => 'Záložka'; @override - String get chat_removeBookmark => 'Remove bookmark'; + String get chat_removeBookmark => 'Odstrániť záložku'; @override - String get chat_showBookmarks => 'Show bookmarks'; + String get chat_showBookmarks => 'Zobraziť záložky'; @override - String get bookmarks_title => 'Bookmarks'; + String get bookmarks_title => 'Záložky'; @override - String get bookmarks_empty => 'No bookmarked messages'; + String get bookmarks_empty => 'Žiadne správy v záložkách'; @override - String get bookmarks_channel => 'Channel'; + String get bookmarks_channel => 'Kanál'; @override - String get bookmarks_contact => 'Contact'; + String get bookmarks_contact => 'Kontakt'; @override - String get bookmarks_remove => 'Remove bookmark'; + String get bookmarks_remove => 'Odstrániť záložku'; @override String get chat_selectMessages => 'Vybrať správy'; @@ -5611,17 +5610,18 @@ class AppLocalizationsSk extends AppLocalizations { 'MeshCore Open nebeží. Otvorte ho a odošlite odpoveď ešte raz.'; @override - String get settings_exportBookmarks => 'Export bookmarks to Markdown'; + String get settings_exportBookmarks => 'Exportovať záložky do Markdownu'; @override String get settings_exportBookmarksSubtitle => - 'Share or save bookmarked messages as a Markdown file.'; + 'Zdieľať alebo uložiť správy so záložkou ako súbor Markdown.'; @override - String get settings_exportBookmarksSuccess => 'Bookmarks exported.'; + String get settings_exportBookmarksSuccess => 'Záložky boli exportované.'; @override - String get settings_exportBookmarksNoBookmarks => 'No bookmarks to export.'; + String get settings_exportBookmarksNoBookmarks => + 'Nie sú žiadne záložky na export.'; @override String get settings_gpxExportRepeaters => @@ -6283,11 +6283,11 @@ class AppLocalizationsSk extends AppLocalizations { String _temp0 = intl.Intl.pluralLogic( count, locale: localeName, - other: 'repeated $count times', - one: 'repeated once', - zero: 'no repeater heard', + other: 'zopakovaný $count-krát', + one: 'zopakovaný raz', + zero: 'nezachytil ho žiadny opakovač', ); - return 'Packet $number: $_temp0'; + return 'Paket $number: $_temp0'; } @override @@ -6295,26 +6295,26 @@ class AppLocalizationsSk extends AppLocalizations { String _temp0 = intl.Intl.pluralLogic( count, locale: localeName, - other: 'repeated $count times', - one: 'repeated once', - zero: 'no repeater heard', + other: 'zopakovaný $count-krát', + one: 'zopakovaný raz', + zero: 'nezachytil ho žiadny opakovač', ); - return 'Recovery packet: $_temp0'; + return 'Záchranný paket: $_temp0'; } @override - String get imageSend_preparingPreview => 'Preparing preview…'; + String get imageSend_preparingPreview => 'Pripravuje sa náhľad…'; @override - String get imageSend_tryAnother => 'Try another version'; + String get imageSend_tryAnother => 'Skúsiť inú verziu'; @override String get imageSend_versionsHint => - 'Each version is reconstructed a little differently. Pick the one that looks most like your photo.'; + 'Každá verzia je zrekonštruovaná trochu inak. Vyberte tú, ktorá sa najviac podobá na vašu fotku.'; @override String imageSend_versionLabel(int number) { - return 'Version $number'; + return 'Verzia $number'; } @override @@ -6322,8 +6322,9 @@ class AppLocalizationsSk extends AppLocalizations { String _temp0 = intl.Intl.pluralLogic( count, locale: localeName, - other: '$count packets', - one: '1 packet', + other: '$count paketov', + few: '$count pakety', + one: '1 paket', ); return '$_temp0'; } @@ -7595,15 +7596,15 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get chatCompression_title => 'Compression'; + String get chatCompression_title => 'Kompresia'; @override String chatCompression_label(String mode) { - return 'Compression: $mode'; + return 'Kompresia: $mode'; } @override - String get chatCompression_off => 'Off'; + String get chatCompression_off => 'Vypnutá'; @override String get chatCompression_smaz => 'SMAZ'; @@ -7612,35 +7613,35 @@ class AppLocalizationsSk extends AppLocalizations { String get chatCompression_cyr2lat => 'Cyr2Lat'; @override - String get chatCompression_changeHint => 'Change compression for this chat'; + String get chatCompression_changeHint => 'Zmeniť kompresiu pre tento chat'; @override String get chatCompression_sheetSubtitle => - 'Applies to messages you send in this chat. Saved on this phone.'; + 'Platí pre správy, ktoré v tomto chate odošlete. Uložené v tomto telefóne.'; @override String get chatCompression_offDescription => - 'No compression. Sends your text exactly as typed. Every app can read it. Saves no bytes.'; + 'Bez kompresie. Text sa odošle presne tak, ako ste ho napísali, a prečíta ho každá aplikácia. Neušetrí žiadne bajty.'; @override String get chatCompression_smazDescription => - 'Lossless compression for short text. The recipient\'s app must support SMAZ; other apps show unreadable \"s:…\" text. Only used when it makes a message smaller, so not every message is compressed.'; + 'Bezstratová kompresia krátkych textov. Aplikácia príjemcu musí podporovať SMAZ, ostatné aplikácie ukážu nečitateľný text „s:…“. Použije sa, len keď je správa vďaka nej menšia, takže nie každá správa sa skomprimuje.'; @override String get chatCompression_cyr2latDescription => - 'Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.'; + 'Nie je bezstratová. Niektoré cyrilské písmená nahradí podobnými latinskými (А→A, З→3), aby ušetrila bajty. Prečíta sa v každej aplikácii bez dekódovania, no presné znaky sa zmenia, aj vo vašich odoslaných správach tu. Môže to ovplyvniť kopírovanie, vyhľadávanie a technické texty. Výsledok závisí od zvoleného profilu.'; @override - String get chatCompression_profile => 'Cyr2Lat profile'; + String get chatCompression_profile => 'Profil Cyr2Lat'; @override String get chatCompression_noStorageId => - 'Can\'t change compression until this channel has synced from the radio.'; + 'Kompresiu nemožno zmeniť, kým sa tento kanál nesynchronizuje z rádia.'; @override String get chatCompression_saveFailed => - 'Couldn\'t save the compression setting. Showing the saved setting.'; + 'Nastavenie kompresie sa nepodarilo uložiť. Zobrazuje sa naposledy uložené nastavenie.'; @override - String get messageMeta_smazCompressed => 'SMAZ compressed'; + String get messageMeta_smazCompressed => 'Komprimované metódou SMAZ'; } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index cb06c656..c004142d 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -318,6 +318,7 @@ "contacts_noContactsMatchFilter": "Žiadne kontakty neodídu vášmu filtru.", "contacts_noMembers": "Žiadni členovia", "contacts_lastSeenNow": "nedávno", + "contacts_lastSeenNever": "zatiaľ nezachytený", "contacts_lastSeenMinsAgo": "~ {minutes} min.", "@contacts_lastSeenMinsAgo": { "placeholders": { @@ -488,6 +489,14 @@ }, "chat_messageCopied": "Správa skopírovaná", "chat_messageDeleted": "Správa odstránená", + "chat_bookmark": "Záložka", + "chat_removeBookmark": "Odstrániť záložku", + "chat_showBookmarks": "Zobraziť záložky", + "bookmarks_title": "Záložky", + "bookmarks_empty": "Žiadne správy v záložkách", + "bookmarks_channel": "Kanál", + "bookmarks_contact": "Kontakt", + "bookmarks_remove": "Odstrániť záložku", "chat_retryingMessage": "Pokus o obnovenie", "chat_retryCount": "Skúsiť {current}/{max}", "@chat_retryCount": { @@ -3172,6 +3181,10 @@ "notification_replyUnavailable": "Táto konverzácia už nie je na pripojenom rádiu.", "notification_replySendFailed": "Vaša odpoveď možno nebola odoslaná. Skontrolujte to v MeshCore Open a skúste to znova.", "notification_replyAppNotRunning": "MeshCore Open nebeží. Otvorte ho a odošlite odpoveď ešte raz.", + "settings_exportBookmarks": "Exportovať záložky do Markdownu", + "settings_exportBookmarksSubtitle": "Zdieľať alebo uložiť správy so záložkou ako súbor Markdown.", + "settings_exportBookmarksSuccess": "Záložky boli exportované.", + "settings_exportBookmarksNoBookmarks": "Nie sú žiadne záložky na export.", "snrIndicator_nearByRepeatersDescription": "Opakovače, ktoré vaše rádio počulo priamo, najskôr tie naposledy počuté.", "snrIndicator_unknownRepeater": "Neznámy opakovač", "snrIndicator_unknownRepeaterHint": "Tento opakovač zatiaľ nie je vo vašich kontaktoch. Jeho názov, poloha a možnosti sa zobrazia, keď rádio prijme jeho inzerát.", @@ -3188,6 +3201,13 @@ "imageSend_viewOriginal": "Originál", "imageSend_viewReconstruction": "Čo vidia príjemcovia", "imageSend_reconstructionUnavailable": "Toto zariadenie nedokáže zobraziť náhľad rekonštrukcie.", + "receivedImage_packetEchoes": "Paket {number}: {count, plural, =0{nezachytil ho žiadny opakovač} =1{zopakovaný raz} other{zopakovaný {count}-krát}}", + "receivedImage_recoveryPacketEchoes": "Záchranný paket: {count, plural, =0{nezachytil ho žiadny opakovač} =1{zopakovaný raz} other{zopakovaný {count}-krát}}", + "imageSend_preparingPreview": "Pripravuje sa náhľad…", + "imageSend_tryAnother": "Skúsiť inú verziu", + "imageSend_versionsHint": "Každá verzia je zrekonštruovaná trochu inak. Vyberte tú, ktorá sa najviac podobá na vašu fotku.", + "imageSend_versionLabel": "Verzia {number}", + "imageSend_versionPackets": "{count, plural, =1{1 paket} few{{count} pakety} other{{count} paketov}}", "imageSend_modelNotDownloaded": "Model obrazu ešte nie je stiahnutý. Stiahnite ho v Nastaveniach, aby ste mohli posielať obrázky.", "receivedImage_save": "Uložiť obrázok", "receivedImage_shareCaption": "Zrekonštruované umelou inteligenciou z {bytes} bajtov; jemné detaily sú generované, nie prenášané.", @@ -3228,6 +3248,8 @@ "appSettings_channelMinHopsCountRepeatersSubtitle": "Správu považovať za odoslanú, keď ju zopakuje {count, plural, =1{1 blízky opakovač} few{{count} rôzne blízke opakovače} many{{count} rôznych blízkych opakovačov} other{{count} rôznych blízkych opakovačov}}, aj keď nepočujete, ako putuje ďalej.", "appSettings_regionOnHopsLine": "Región vedľa počtu skokov", "appSettings_regionOnHopsLineSubtitle": "Zobraziť región správy kanála v rovnakom riadku ako počet skokov namiesto pod ním.", + "appSettings_showCompressionIndicator": "Indikátor kompresie", + "appSettings_showCompressionIndicatorSubtitle": "Zobraziť ikonu pri správach komprimovaných metódou SMAZ.", "channels_regionRadioDefaultSuffix": "(predvolený pre rádio)", "channels_regionRadioDefaultApplies": "Toto rádio odosiela flood správy bez regiónu vo svojom predvolenom regióne: {region}.", "chat_futureTimestampWarning": "Čas tejto správy je v budúcnosti, takže hodiny odosielateľa môžu byť nesprávne. Zobrazuje sa v poradí, v akom prišla.", @@ -3802,6 +3824,7 @@ "backupRestore_contactsDescription": "Kontakty, filtre a nastavenia jednotlivých kontaktov, skupiny a história správ", "backupRestore_discoveredContacts": "Objavené kontakty", "backupRestore_discoveredContactsDescription": "Objavené kontakty a ich uložené údaje", + "backupRestore_bookmarks": "Záložky", "backupRestore_channels": "Kanály", "backupRestore_channelsDescription": "Kanály, filtre kanálov, komunity a história správ", "backupRestore_backup": "Vytvoriť zálohu", @@ -3838,5 +3861,19 @@ "modelDownload_verifying": "Overuje sa sťahovanie", "modelDownload_useModel": "Použiť tento model", "modelDownload_removeFailed": "Model sa nepodarilo odstrániť: {error}", - "modelDownload_progress": "{current} / {total} MB ({percent}%)" + "modelDownload_progress": "{current} / {total} MB ({percent}%)", + "chatCompression_title": "Kompresia", + "chatCompression_label": "Kompresia: {mode}", + "chatCompression_off": "Vypnutá", + "chatCompression_smaz": "SMAZ", + "chatCompression_cyr2lat": "Cyr2Lat", + "chatCompression_changeHint": "Zmeniť kompresiu pre tento chat", + "chatCompression_sheetSubtitle": "Platí pre správy, ktoré v tomto chate odošlete. Uložené v tomto telefóne.", + "chatCompression_offDescription": "Bez kompresie. Text sa odošle presne tak, ako ste ho napísali, a prečíta ho každá aplikácia. Neušetrí žiadne bajty.", + "chatCompression_smazDescription": "Bezstratová kompresia krátkych textov. Aplikácia príjemcu musí podporovať SMAZ, ostatné aplikácie ukážu nečitateľný text „s:…“. Použije sa, len keď je správa vďaka nej menšia, takže nie každá správa sa skomprimuje.", + "chatCompression_cyr2latDescription": "Nie je bezstratová. Niektoré cyrilské písmená nahradí podobnými latinskými (А→A, З→3), aby ušetrila bajty. Prečíta sa v každej aplikácii bez dekódovania, no presné znaky sa zmenia, aj vo vašich odoslaných správach tu. Môže to ovplyvniť kopírovanie, vyhľadávanie a technické texty. Výsledok závisí od zvoleného profilu.", + "chatCompression_profile": "Profil Cyr2Lat", + "chatCompression_noStorageId": "Kompresiu nemožno zmeniť, kým sa tento kanál nesynchronizuje z rádia.", + "chatCompression_saveFailed": "Nastavenie kompresie sa nepodarilo uložiť. Zobrazuje sa naposledy uložené nastavenie.", + "messageMeta_smazCompressed": "Komprimované metódou SMAZ" } diff --git a/untranslated.json b/untranslated.json index c802d876..afa5f143 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,6 +1,8 @@ { "bg": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -33,11 +35,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "cs": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -70,11 +75,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "de": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -107,11 +115,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "es": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -144,11 +155,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "fr": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -181,11 +195,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "hu": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -218,11 +235,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "it": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -255,11 +275,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "ja": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -292,11 +315,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "ko": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -329,11 +355,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "nl": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -366,11 +395,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "pl": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -403,11 +435,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "pt": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -440,11 +475,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "pt_PT": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -477,11 +515,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "ru": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -514,48 +555,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" - ], - - "sk": [ - "backupRestore_bookmarks", - "contacts_lastSeenNever", - "chat_bookmark", - "chat_removeBookmark", - "chat_showBookmarks", - "bookmarks_title", - "bookmarks_empty", - "bookmarks_channel", - "bookmarks_contact", - "bookmarks_remove", - "settings_exportBookmarks", - "settings_exportBookmarksSubtitle", - "settings_exportBookmarksSuccess", - "settings_exportBookmarksNoBookmarks", - "receivedImage_packetEchoes", - "receivedImage_recoveryPacketEchoes", - "imageSend_preparingPreview", - "imageSend_tryAnother", - "imageSend_versionsHint", - "imageSend_versionLabel", - "imageSend_versionPackets", - "chatCompression_title", - "chatCompression_label", - "chatCompression_off", - "chatCompression_smaz", - "chatCompression_cyr2lat", - "chatCompression_changeHint", - "chatCompression_sheetSubtitle", - "chatCompression_offDescription", - "chatCompression_smazDescription", - "chatCompression_cyr2latDescription", - "chatCompression_profile", - "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "sl": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -588,11 +595,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "sv": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -625,11 +635,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "uk": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -662,11 +675,14 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ], "zh": [ "backupRestore_bookmarks", + "appSettings_showCompressionIndicator", + "appSettings_showCompressionIndicatorSubtitle", "contacts_lastSeenNever", "chat_bookmark", "chat_removeBookmark", @@ -699,6 +715,7 @@ "chatCompression_cyr2latDescription", "chatCompression_profile", "chatCompression_noStorageId", - "chatCompression_saveFailed" + "chatCompression_saveFailed", + "messageMeta_smazCompressed" ] } From ee7b4c8f8b12fcb850a1219838fb9317ba769778 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:03:25 -0700 Subject: [PATCH 31/50] Preserve reply mentions and support copying image messages --- documentation/image-messages.md | 2 +- lib/models/bookmarked_message.dart | 2 +- lib/models/channel_message.dart | 11 + lib/screens/channel_chat_screen.dart | 27 +- test/models/channel_message_reply_test.dart | 48 ++ test/screens/copy_messages_test.dart | 619 ++++++++++++++++++++ 6 files changed, 703 insertions(+), 6 deletions(-) create mode 100644 test/screens/copy_messages_test.dart diff --git a/documentation/image-messages.md b/documentation/image-messages.md index 1881ba0a..5aa138e5 100644 --- a/documentation/image-messages.md +++ b/documentation/image-messages.md @@ -38,7 +38,7 @@ Chunks are reassembled into an image entry in channel chat. A partially received With Process images automatically enabled, complete images are queued for local reconstruction. Automatic decoding runs only while the app is in the foreground, one image at a time, with at most 3 images queued; when more arrive, the newest 3 are kept and the rest wait for a tap. Otherwise, tap an image entry to process it. Download/enable the model if prompted. A failed reconstruction can be retried; missing chunks and inference errors are different failures. -Tap a reconstructed image to inspect it. Long-press or right-click its chat bubble for Packet info, Delete, and Save (available once decoded). Deletion is local. Encoded streams and reconstructed images are persisted in application storage, capped at 200 images, 64 MB, and 30 days, plus a limit of 400 image entries (including ones waiting to be decoded and your own sent images once their data has expired). When the cap is reached, the oldest reconstructed images are evicted first and show "Image no longer stored"; they can be decoded again while their small encoded stream remains. Past 30 days the stream is removed too. +Tap a reconstructed image to inspect it. Long-press or right-click its chat bubble for Copy (copies sender, timestamp, byte/packet summary, and the AI-reconstruction caption when decoded), Packet info, Delete, and Save (available once decoded). Copying raw image pixels to the clipboard is not supported—use Save image to export or share the PNG with its provenance caption—and AEIC images cannot be re-sent by pasting text into the composer because they travel as binary `GRP_DATA` chunks. Deletion is local. Encoded streams and reconstructed images are persisted in application storage, capped at 200 images, 64 MB, and 30 days, plus a limit of 400 image entries (including ones waiting to be decoded and your own sent images once their data has expired). When the cap is reached, the oldest reconstructed images are evicted first and show "Image no longer stored"; they can be decoded again while their small encoded stream remains. Past 30 days the stream is removed too. ## Other image features diff --git a/lib/models/bookmarked_message.dart b/lib/models/bookmarked_message.dart index a078625c..8ba0f477 100644 --- a/lib/models/bookmarked_message.dart +++ b/lib/models/bookmarked_message.dart @@ -60,7 +60,7 @@ class BookmarkedMessage { sourceName: channelName, messageId: message.messageId, senderName: senderName, - text: message.text, + text: message.fullText, translatedText: message.translatedText, timestamp: message.timestamp, receivedAt: message.receivedAt, diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index f3460138..73e9f23a 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -109,6 +109,17 @@ class ChannelMessage { bool get isFiltered => filterReason != null; + /// Full wire/sent text, restoring the `@[sender] ` reply prefix when it + /// was split into [replyToSenderName] on storage. + String get fullText { + if (replyToMessageId != null && + replyToSenderName != null && + replyToSenderName!.isNotEmpty) { + return '@[$replyToSenderName] $text'; + } + return text; + } + String? get senderKeyHex => senderKey != null ? pubKeyToHex(senderKey!) : null; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 35bc8a71..03aab788 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -699,7 +699,7 @@ class _ChannelChatScreenState extends State { ChatSearchEntry( id: m.messageId, sender: m.senderName, - text: m.text, + text: m.fullText, translatedText: m.translatedText, time: m.receivedAt, matchSender: true, @@ -2492,6 +2492,14 @@ class _ChannelChatScreenState extends State { ), subtitle: _imageSenderLabel(entry), ), + ListTile( + leading: const Icon(Icons.copy), + title: Text(l10n.common_copy), + onTap: () { + Navigator.pop(sheetContext); + copyChatMessageText(context, _imageCopyText(entry)); + }, + ), if (canSave) ListTile( leading: const Icon(Icons.save_alt), @@ -2544,6 +2552,17 @@ class _ChannelChatScreenState extends State { ); } + String _imageCopyText(ReceivedImageEntry entry) { + final l10n = context.l10n; + final lines = [ + '${_imageSenderLabel(entry)} (${formatChatTime(context, entry.firstSeen)})', + l10n.receivedImage_awaiting(entry.bitstreamByteCount, entry.totalChunks), + if (entry.state == ReceivedImageState.decoded && entry.synthesized) + l10n.receivedImage_shareCaption(entry.bitstreamByteCount), + ]; + return lines.join('\n'); + } + Future _saveImage(ReceivedImageEntry entry) async { final l10n = context.l10n; final shareOrigin = shareOriginOf(context); @@ -3047,7 +3066,7 @@ class _ChannelChatScreenState extends State { title: Text(context.l10n.common_copy), onTap: () { Navigator.pop(sheetContext); - copyChatMessageText(context, message.text); + copyChatMessageText(context, message.fullText); }, ), if (canTranslateMessage) @@ -3379,8 +3398,8 @@ class _ChannelChatScreenState extends State { final text = messages .map( (m) => m.senderName.isEmpty || m.isOutgoing - ? m.text - : '${m.senderName}: ${m.text}', + ? m.fullText + : '${m.senderName}: ${m.fullText}', ) .join('\n'); setState(_selectedIds.clear); diff --git a/test/models/channel_message_reply_test.dart b/test/models/channel_message_reply_test.dart index 1f350aa0..ca750ad8 100644 --- a/test/models/channel_message_reply_test.dart +++ b/test/models/channel_message_reply_test.dart @@ -1,4 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/bookmarked_message.dart'; import 'package:meshcore_open/models/channel_message.dart'; void main() { @@ -25,5 +26,52 @@ void main() { test('outgoing message without reply has no reply target', () { final message = ChannelMessage.outgoing('hello', 'Me', 0); expect(message.replyToMessageId, isNull); + expect(message.fullText, 'hello'); + }); + + test('fullText restores @[username] prefix for stored replies', () { + final storedReply = ChannelMessage( + senderName: 'Me', + text: 'answer', + timestamp: DateTime(2026, 1, 1, 12), + isOutgoing: true, + replyToMessageId: 'msg-1', + replyToSenderName: 'Alice', + replyToText: 'question', + ); + + expect(storedReply.fullText, '@[Alice] answer'); + + final bookmark = BookmarkedMessage.fromChannel( + message: storedReply, + channelId: 'ch-0', + channelName: 'Public', + senderName: 'Me', + ); + expect(bookmark.text, '@[Alice] answer'); + }); + + test('fullText preserves nested mention and special payloads in replies', () { + final nestedReply = ChannelMessage( + senderName: 'Bob', + text: '@[Alice] nested', + timestamp: DateTime(2026, 1, 1, 12), + isOutgoing: false, + replyToMessageId: 'msg-1', + replyToSenderName: 'Alice', + replyToText: 'original', + ); + expect(nestedReply.fullText, '@[Alice] @[Alice] nested'); + + final gifReply = ChannelMessage( + senderName: 'Bob', + text: 'g:abc123', + timestamp: DateTime(2026, 1, 1, 12), + isOutgoing: false, + replyToMessageId: 'msg-1', + replyToSenderName: 'Alice', + replyToText: 'original', + ); + expect(gifReply.fullText, '@[Alice] g:abc123'); }); } diff --git a/test/screens/copy_messages_test.dart b/test/screens/copy_messages_test.dart new file mode 100644 index 00000000..2d10bd95 --- /dev/null +++ b/test/screens/copy_messages_test.dart @@ -0,0 +1,619 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/helpers/message_url_image_helper.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/gif_message.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; +import 'package:meshcore_open/widgets/received_image_message.dart'; +import 'package:meshcore_open/widgets/shared_contact_card.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +const _contactShareHex = + '50ba28f599799142622d188469a63f3890d495cdcedd24239052abd364c0283d'; +const _contactShareToken = '<$_contactShareHex:1:Bob>'; +const _gifToken = 'g:testgif123'; +const _markerToken = 'm:45.515232,-122.678385|Camp|poi'; +const _urlText = 'Check https://example.com/photo.png'; +const _png1x1 = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg=='; + +(MeshCoreConnector, List, ReceivedImageStore)? _shared; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('copy_messages_test'); + String? copiedText; + late bool previousLoadLinkImages; + + setUpAll(() async { + previousLoadLinkImages = MessageUrlImageHelper.loadLinkImages.value; + MessageUrlImageHelper.loadLinkImages.value = false; + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + copiedText = + (call.arguments as Map)['text'] as String?; + } + return null; + }); + + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDownAll(() { + MessageUrlImageHelper.loadLinkImages.value = previousLoadLinkImages; + _shared = null; + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + setUp(() { + copiedText = null; + }); + + /// Scrolls the reversed chat ListView upward toward older items until + /// [target] is built and centered in the viewport. + Future scrollToTarget(WidgetTester tester, Finder target) async { + final scrollable = find.byType(Scrollable).first; + if (target.evaluate().isEmpty) { + await tester.dragUntilVisible( + target, + scrollable, + const Offset(0, 200), + maxIteration: 30, + ); + } + await Scrollable.ensureVisible(tester.element(target), alignment: 0.5); + await _settle(tester); + } + + /// Opens the message action sheet by long-pressing the bubble padding + /// (outside desktop SelectableLinkify) and taps Copy. + Future copyFromBubbleContaining( + WidgetTester tester, + Finder contentFinder, + ) async { + await scrollToTarget(tester, contentFinder); + final bubble = find.ancestor( + of: contentFinder, + matching: find.byType(MessageBubbleFrame), + ); + await tester.longPressAt(tester.getTopLeft(bubble) + const Offset(8, 8)); + await _settle(tester); + await tester.tap(find.text(_l10n.common_copy)); + await _settle(tester); + } + + /// Opens the action sheet on a non-text special widget and taps Copy. + Future copyFromWidget(WidgetTester tester, Finder widgetFinder) async { + await scrollToTarget(tester, widgetFinder); + await tester.longPressAt(tester.getCenter(widgetFinder)); + await _settle(tester); + await tester.tap(find.text(_l10n.common_copy)); + await _settle(tester); + } + + group('ChannelChatScreen & ChatScreen copy', () { + testWidgets('copies special channel messages (contact, GIF, location, URL) ' + 'and image metadata/caption', (tester) async { + final (connector, providers, imageStore) = _shared ??= await _connect( + tester, + ); + final channel = connector.channels[2]; + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + await tester.runAsync(() async { + await connector.sendChannelMessage(channel, _contactShareToken); + await connector.sendChannelMessage(channel, _gifToken); + await connector.sendChannelMessage(channel, _markerToken); + await connector.sendChannelMessage(channel, _urlText); + + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: _contactShareToken, + timestampSecs: nowSecs - 40, + ), + ); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: _gifToken, + timestampSecs: nowSecs - 30, + ), + ); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: _markerToken, + timestampSecs: nowSecs - 20, + ), + ); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: _urlText, + timestampSecs: nowSecs - 10, + ), + ); + + await imageStore.registerOutgoing( + channelIndex: channel.index, + channelId: channel.storageId, + senderPrefix: 0x1234, + imgId: 1, + previewPng: Uint8List.fromList(base64Decode(_png1x1)), + rate: AeicRatePoint.ft32, + chunkCount: 2, + synthesized: true, + payloadBytes: 156, + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + await _pump(tester, providers, ChannelChatScreen(channel: channel)); + + // Image message (newest, at bottom): long-press -> Copy copies metadata + // + R6 caption. + final imageBubble = find.byType(ReceivedImageMessage); + expect(imageBubble, findsOneWidget); + await copyFromWidget(tester, imageBubble); + expect(copiedText, contains(_l10n.receivedImage_awaiting(156, 2))); + expect(copiedText, contains(_l10n.receivedImage_shareCaption(156))); + + // Received special messages + await copyFromBubbleContaining( + tester, + find + .textContaining('https://example.com/photo.png', findRichText: true) + .first, + ); + expect(copiedText, _urlText); + + await copyFromWidget(tester, find.text(_l10n.chat_poiShared).first); + expect(copiedText, _markerToken); + + await copyFromWidget(tester, find.byType(GifMessage).first); + expect(copiedText, _gifToken); + + await copyFromWidget(tester, find.byType(SharedContactCard).first); + expect(copiedText, _contactShareToken); + + // Sent special messages (further up the transcript) + await copyFromBubbleContaining( + tester, + find + .textContaining('https://example.com/photo.png', findRichText: true) + .last, + ); + expect(copiedText, _urlText); + + await copyFromWidget(tester, find.text(_l10n.chat_poiShared).last); + expect(copiedText, _markerToken); + + await copyFromWidget(tester, find.byType(GifMessage).last); + expect(copiedText, _gifToken); + + await copyFromWidget(tester, find.byType(SharedContactCard).last); + expect(copiedText, _contactShareToken); + + // Verify image action sheet fits 320dp at 1.3x and 2.0x text scale. + for (final scale in [1.3, 2.0]) { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget( + MediaQuery( + data: MediaQueryData( + size: const Size(320, 568), + textScaler: TextScaler.linear(scale), + ), + child: MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: ChannelChatScreen(channel: channel), + ), + ), + ), + ); + await _settle(tester); + await scrollToTarget(tester, find.byType(ReceivedImageMessage)); + await tester.longPress(find.byType(ReceivedImageMessage)); + await _settle(tester); + expect(find.text(_l10n.common_copy), findsOneWidget); + expect(tester.takeException(), isNull); + Navigator.of(tester.element(find.text(_l10n.common_copy))).pop(); + await _settle(tester); + } + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + + await _tearDown(tester); + }); + + testWidgets('copies regular, @[username], and special DM messages ' + '(sent and received)', (tester) async { + final (connector, providers, _) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere( + (c) => c.type == advTypeChat, + ); + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + await tester.runAsync(() async { + await connector.sendMessage(contact, '@[Maya] DM mention sent'); + await connector.sendMessage(contact, _contactShareToken); + await connector.sendMessage(contact, _gifToken); + await connector.sendMessage(contact, _markerToken); + await connector.sendMessage(contact, _urlText); + + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Regular DM received', + timestampSecs: nowSecs - 50, + ), + ); + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: '@[Review Radio] DM mention received', + timestampSecs: nowSecs - 40, + ), + ); + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: _contactShareToken, + timestampSecs: nowSecs - 30, + ), + ); + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: _gifToken, + timestampSecs: nowSecs - 20, + ), + ); + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: _markerToken, + timestampSecs: nowSecs - 10, + ), + ); + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: _urlText, + timestampSecs: nowSecs - 5, + ), + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + await _pump(tester, providers, ChatScreen(contact: contact)); + + await copyFromBubbleContaining( + tester, + find + .textContaining('https://example.com/photo.png', findRichText: true) + .first, + ); + expect(copiedText, _urlText); + + await copyFromWidget(tester, find.text(_l10n.chat_poiShared).first); + expect(copiedText, _markerToken); + + await copyFromWidget(tester, find.byType(GifMessage).first); + expect(copiedText, _gifToken); + + await copyFromWidget(tester, find.byType(SharedContactCard).first); + expect(copiedText, _contactShareToken); + + await copyFromBubbleContaining( + tester, + find.textContaining('DM mention received', findRichText: true), + ); + expect(copiedText, '@[Review Radio] DM mention received'); + + await copyFromBubbleContaining( + tester, + find.textContaining('Regular DM received', findRichText: true), + ); + expect(copiedText, 'Regular DM received'); + + await copyFromBubbleContaining( + tester, + find + .textContaining('https://example.com/photo.png', findRichText: true) + .last, + ); + expect(copiedText, _urlText); + + await copyFromWidget(tester, find.text(_l10n.chat_poiShared).last); + expect(copiedText, _markerToken); + + await copyFromWidget(tester, find.byType(GifMessage).last); + expect(copiedText, _gifToken); + + await copyFromWidget(tester, find.byType(SharedContactCard).last); + expect(copiedText, _contactShareToken); + + await copyFromBubbleContaining( + tester, + find.textContaining('DM mention sent', findRichText: true), + ); + expect(copiedText, '@[Maya] DM mention sent'); + + await _tearDown(tester); + }); + + testWidgets('copies sent and received channel replies with @[username] ' + 'and leaves regular messages unchanged', (tester) async { + final (connector, providers, _) = _shared ??= await _connect(tester); + final channel = connector.channels[1]; + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + await tester.runAsync(() async { + await connector.sendChannelMessage(channel, 'Plain outgoing'); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: 'Regular channel hello', + timestampSecs: nowSecs - 40, + ), + ); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Jordan', + message: '@[Maya] Matched channel reply', + timestampSecs: nowSecs - 30, + ), + ); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Sam', + message: '@[GhostNode] Unmatched channel reply', + timestampSecs: nowSecs - 20, + ), + ); + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Ranger Pat', + message: 'Reply target message', + timestampSecs: nowSecs - 10, + ), + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + await _pump(tester, providers, ChannelChatScreen(channel: channel)); + + // Reply to Ranger Pat's message via UI composer and send. + final replyTargetText = find.textContaining( + 'Reply target message', + findRichText: true, + ); + await scrollToTarget(tester, replyTargetText); + final targetBubble = find.ancestor( + of: replyTargetText, + matching: find.byType(MessageBubbleFrame), + ); + await tester.longPressAt( + tester.getTopLeft(targetBubble) + const Offset(8, 8), + ); + await _settle(tester); + await tester.tap(find.text(_l10n.chat_reply)); + await _settle(tester); + await tester.enterText(find.byType(TextField), 'Sent reply body'); + await _settle(tester); + await tester.tap(find.byTooltip(_l10n.chat_sendMessage)); + await _settle(tester); + + // 1. Sent reply includes @[Ranger Pat]. + await copyFromBubbleContaining( + tester, + find.textContaining('Sent reply body', findRichText: true), + ); + expect(copiedText, '@[Ranger Pat] Sent reply body'); + + // 2. Bulk copy on the sent reply also includes @[Ranger Pat]. + final sentReplyBubble = find.ancestor( + of: find.textContaining('Sent reply body', findRichText: true), + matching: find.byType(MessageBubbleFrame), + ); + await tester.longPressAt( + tester.getTopLeft(sentReplyBubble) + const Offset(8, 8), + ); + await _settle(tester); + await tester.tap(find.text(_l10n.chat_selectMessages)); + await _settle(tester); + await tester.tap(find.byIcon(Icons.more_vert)); + await _settle(tester); + await tester.tap(find.text(_l10n.common_copy)); + await _settle(tester); + expect(copiedText, '@[Ranger Pat] Sent reply body'); + + // 3. Received unmatched reply includes @[GhostNode]. + await copyFromBubbleContaining( + tester, + find.textContaining('Unmatched channel reply', findRichText: true), + ); + expect(copiedText, '@[GhostNode] Unmatched channel reply'); + + // 4. Received matched reply includes @[Maya]. + await copyFromBubbleContaining( + tester, + find.textContaining('Matched channel reply', findRichText: true), + ); + expect(copiedText, '@[Maya] Matched channel reply'); + + // 5. Regular incoming message unchanged. + await copyFromBubbleContaining( + tester, + find.textContaining('Regular channel hello', findRichText: true).last, + ); + expect(copiedText, 'Regular channel hello'); + + // 6. Regular outgoing message unchanged. + await copyFromBubbleContaining( + tester, + find.textContaining('Plain outgoing', findRichText: true), + ); + expect(copiedText, 'Plain outgoing'); + + await _tearDown(tester); + }); + }); +} + +Future _pump( + WidgetTester tester, + List providers, + Widget home, +) async { + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ), + ); + await _settle(tester); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(hours: 2)); +} + +Future<(MeshCoreConnector, List, ReceivedImageStore)> +_connect(WidgetTester tester) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + final imageStore = ReceivedImageStore(); + + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(milliseconds: 50), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || + connector.channels.isEmpty || + !connector.channelMapConfirmed) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels, isNotEmpty); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: imageStore), + ], + imageStore, + ); +} From 79f624c74343855f20ac1f2899e1ff5e4f123914 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:14:32 -0700 Subject: [PATCH 32/50] Ignore impossible hops in path map resolution Reject repeater matches and peer inferences whose distance from the previous plausible hop anchor exceeds the per-hop LoRa range budget (250 km scaled by consecutive unresolved hops). Without a known self location, select the anchor chain that explains the most local hops so a single distant prefix collision does not poison resolution for the remaining hops. Apply the same hop-order resolution and anchor-bounded peer inference in PathTraceMapScreen. --- lib/helpers/path_hop_resolver.dart | 262 ++++++++-- lib/screens/path_trace_map.dart | 480 ++++++++++++------ test/helpers/path_hop_resolver_test.dart | 257 +++++++++- .../channel_message_path_map_test.dart | 292 +++++++++++ test/screens/path_trace_test.dart | 190 ++++++- 5 files changed, 1292 insertions(+), 189 deletions(-) create mode 100644 test/screens/channel_message_path_map_test.dart diff --git a/lib/helpers/path_hop_resolver.dart b/lib/helpers/path_hop_resolver.dart index a6f2c018..af39983d 100644 --- a/lib/helpers/path_hop_resolver.dart +++ b/lib/helpers/path_hop_resolver.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:latlong2/latlong.dart'; import '../connector/meshcore_protocol.dart'; @@ -7,59 +9,261 @@ import '../models/contact.dart'; class PathHopResolver { const PathHopResolver._(); + /// Maximum plausible single-hop LoRa RF link distance in meters (250 km). + /// Accommodates long-range line-of-sight mountain-top hops while rejecting + /// multi-hundred/multi-thousand-km prefix collisions. + static const double maxSingleHopDistanceMeters = 250000.0; + static List resolve({ required List pathBytes, required List contacts, LatLng? endpoint, bool resolveFromEnd = false, int pathHashByteWidth = 1, + double maxHopDistanceMeters = maxSingleHopDistanceMeters, }) { final width = pathHashByteWidth.clamp(1, 3).toInt(); + final hops = PathHelper.splitPathBytes(pathBytes, width); + return resolveHops( + hops: hops, + contacts: contacts, + endpoint: endpoint, + resolveFromEnd: resolveFromEnd, + maxHopDistanceMeters: maxHopDistanceMeters, + ); + } + + static List resolveHops({ + required List hops, + required List contacts, + LatLng? endpoint, + bool resolveFromEnd = false, + double maxHopDistanceMeters = maxSingleHopDistanceMeters, + bool Function(Contact)? contactFilter, + }) { + if (hops.isEmpty) return const []; + + final widths = { + for (final hop in hops) + if (hop.isNotEmpty) hop.length, + }; final candidatesByPrefix = >{}; for (final contact in contacts) { - if (contact.publicKey.length < width) continue; - if (contact.type != advTypeRepeater && contact.type != advTypeRoom) { - continue; + final include = + contactFilter?.call(contact) ?? + (contact.type == advTypeRepeater || contact.type == advTypeRoom); + if (!include) continue; + for (final width in widths) { + if (contact.publicKey.length < width) continue; + final prefix = PathHelper.formatHopHex( + contact.publicKey.sublist(0, width), + ); + candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); } - final prefix = PathHelper.formatHopHex( - contact.publicKey.sublist(0, width), - ); - candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); } for (final candidates in candidatesByPrefix.values) { candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); } - final hops = PathHelper.splitPathBytes(pathBytes, width); - final resolved = List.filled(hops.length, null); + final hopCount = hops.length; + final resolved = List.filled(hopCount, null); final indexes = resolveFromEnd - ? List.generate(hops.length, (i) => hops.length - 1 - i) - : List.generate(hops.length, (i) => i); + ? List.generate(hopCount, (i) => hopCount - 1 - i) + : List.generate(hopCount, (i) => i); + final stepPrefixes = [ + for (final index in indexes) PathHelper.formatHopHex(hops[index]), + ]; final distance = Distance(); - var previousPosition = endpoint; - for (final index in indexes) { - final candidates = - candidatesByPrefix[PathHelper.formatHopHex(hops[index])]; - if (candidates == null || candidates.isEmpty) continue; + (Contact, double)? pickNearestLocated( + String prefix, + Set used, + LatLng anchor, + double maxDistanceMeters, + ) { + final candidates = candidatesByPrefix[prefix]; + if (candidates == null || candidates.isEmpty) return null; + Contact? best; + double? bestDistance; + for (final candidate in candidates) { + if (used.contains(candidate)) continue; + final position = _positionOf(candidate); + if (position == null) continue; + final d = distance(anchor, position); + if (d <= maxDistanceMeters && + (bestDistance == null || d < bestDistance)) { + bestDistance = d; + best = candidate; + } + } + if (best == null || bestDistance == null) return null; + return (best, bestDistance); + } - var bestIndex = 0; - if (previousPosition != null && candidates.length > 1) { - double? nearestDistance; - for (var i = 0; i < candidates.length; i++) { - final position = _positionOf(candidates[i]); - if (position == null) continue; - final candidateDistance = distance(previousPosition, position); - if (nearestDistance == null || candidateDistance < nearestDistance) { - nearestDistance = candidateDistance; - bestIndex = i; + Contact? pickFirstUnlocated(String prefix, Set used) { + final candidates = candidatesByPrefix[prefix]; + if (candidates == null || candidates.isEmpty) return null; + for (final candidate in candidates) { + if (used.contains(candidate)) continue; + if (_positionOf(candidate) == null) return candidate; + } + return null; + } + + Contact? pickFirstAny(String prefix, Set used) { + final candidates = candidatesByPrefix[prefix]; + if (candidates == null || candidates.isEmpty) return null; + for (final candidate in candidates) { + if (!used.contains(candidate)) return candidate; + } + return null; + } + + final used = Set.identity(); + + if (endpoint != null) { + var previousPosition = endpoint; + var lastAnchorStep = -1; + for (var step = 0; step < hopCount; step++) { + final prefix = stepPrefixes[step]; + final hopGap = step - lastAnchorStep; + final maxAllowed = hopGap * maxHopDistanceMeters; + final match = pickNearestLocated( + prefix, + used, + previousPosition, + maxAllowed, + ); + if (match != null) { + used.add(match.$1); + resolved[indexes[step]] = match.$1; + previousPosition = _positionOf(match.$1)!; + lastAnchorStep = step; + } else { + final unlocated = pickFirstUnlocated(prefix, used); + if (unlocated != null) { + used.add(unlocated); + resolved[indexes[step]] = unlocated; } } } + return resolved; + } - final contact = candidates.removeAt(bestIndex); - resolved[index] = contact; - previousPosition = _positionOf(contact) ?? previousPosition; + // Without a known endpoint, find the located anchor whose plausible chain + // explains the most located hops so a single distant prefix collision does + // not poison the rest of the path. + var hasAnyLocated = false; + for (final prefix in stepPrefixes) { + final candidates = candidatesByPrefix[prefix]; + if (candidates != null && candidates.any((c) => _positionOf(c) != null)) { + hasAnyLocated = true; + break; + } + } + + if (!hasAnyLocated) { + for (var step = 0; step < hopCount; step++) { + final contact = pickFirstAny(stepPrefixes[step], used); + if (contact != null) { + used.add(contact); + resolved[indexes[step]] = contact; + } + } + return resolved; + } + + List? bestRun; + var bestLocatedCount = 0; + var bestTotalDistance = double.infinity; + var bestLastSeenSum = -1; + + for (var anchorStep = 0; anchorStep < hopCount; anchorStep++) { + final candidates = candidatesByPrefix[stepPrefixes[anchorStep]]; + if (candidates == null) continue; + for (final anchorCandidate in candidates) { + final anchorPos = _positionOf(anchorCandidate); + if (anchorPos == null) continue; + + final run = List.filled(hopCount, null); + final runUsed = Set.identity()..add(anchorCandidate); + run[anchorStep] = anchorCandidate; + var locatedCount = 1; + var totalDistance = 0.0; + var lastSeenSum = anchorCandidate.lastSeen.millisecondsSinceEpoch; + + var prevPos = anchorPos; + var lastAnchor = anchorStep; + for (var step = anchorStep + 1; step < hopCount; step++) { + final maxAllowed = (step - lastAnchor) * maxHopDistanceMeters; + final match = pickNearestLocated( + stepPrefixes[step], + runUsed, + prevPos, + maxAllowed, + ); + if (match == null) continue; + run[step] = match.$1; + runUsed.add(match.$1); + prevPos = _positionOf(match.$1)!; + lastAnchor = step; + locatedCount++; + totalDistance += match.$2; + lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; + } + + prevPos = anchorPos; + lastAnchor = anchorStep; + for (var step = anchorStep - 1; step >= 0; step--) { + final maxAllowed = (lastAnchor - step) * maxHopDistanceMeters; + final match = pickNearestLocated( + stepPrefixes[step], + runUsed, + prevPos, + maxAllowed, + ); + if (match == null) continue; + run[step] = match.$1; + runUsed.add(match.$1); + prevPos = _positionOf(match.$1)!; + lastAnchor = step; + locatedCount++; + totalDistance += match.$2; + lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; + } + + final isBetter = + locatedCount > bestLocatedCount || + (locatedCount == bestLocatedCount && + totalDistance < bestTotalDistance - 1e-6) || + (locatedCount == bestLocatedCount && + (totalDistance - bestTotalDistance).abs() <= 1e-6 && + lastSeenSum > bestLastSeenSum); + if (isBetter) { + bestRun = run; + bestLocatedCount = locatedCount; + bestTotalDistance = totalDistance; + bestLastSeenSum = lastSeenSum; + } + } + } + + if (bestRun != null) { + for (var step = 0; step < hopCount; step++) { + final contact = bestRun[step]; + if (contact != null) { + used.add(contact); + resolved[indexes[step]] = contact; + } + } + for (var step = 0; step < hopCount; step++) { + if (bestRun[step] != null) continue; + final unlocated = pickFirstUnlocated(stepPrefixes[step], used); + if (unlocated != null) { + used.add(unlocated); + resolved[indexes[step]] = unlocated; + } + } } return resolved; diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index 5e5309ae..63d6d59c 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -8,6 +8,7 @@ import 'package:latlong2/latlong.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/helpers/path_helper.dart'; +import 'package:meshcore_open/helpers/path_hop_resolver.dart'; import 'package:meshcore_open/l10n/l10n.dart'; import 'package:meshcore_open/models/app_settings.dart'; import 'package:meshcore_open/models/contact.dart'; @@ -95,8 +96,6 @@ class _PathTraceMapScreenState extends State static const double _labelZoomThreshold = kPathMapLabelZoomThreshold; // Used when the radio never acknowledges the trace request. static const Duration _sendAckTimeout = Duration(seconds: 15); - //miles to meters conversion for filtering out repeaters that are too far from the last known GPS hop to be a likely match, to avoid false matches that throw off the inferred positions of other hops in the path - static const double _maxRepeaterMatchDistanceMeters = 40 * 1609.344; final MapController _mapController = MapController(); StreamSubscription? _frameSubscription; @@ -143,9 +142,10 @@ class _PathTraceMapScreenState extends State bool _animationEnabled = true; bool _followPacket = false; - // Hop-prefix -> contact lookups, invalidated when the contact list changes. - final Map _hopContactCache = {}; - int? _hopContactCacheSignature; + // Resolved hop contacts and inferred positions per display path id, used by + // combined markers and the generic hop list. + final Map contacts, List inferred})> + _resolvedDisplayPaths = {}; String _formatPathPrefixes(Uint8List pathBytes, [int? hashByteWidth]) { return PathHelper.splitPathBytes( @@ -584,78 +584,40 @@ class _PathTraceMapScreenState extends State .map((snr) => snr.toSigned(8).toDouble() / 4) .toList(); - Map pathContacts = {}; - Contact lastContact = Contact( - path: Uint8List(0), - pathLength: 0, - publicKey: connector.selfPublicKey ?? Uint8List(0), - name: context.l10n.pathTrace_you, - type: advTypeChat, - latitude: connector.selfLatitude, - longitude: connector.selfLongitude, - lastSeen: DateTime.now(), + final selfPoint = plausibleSelfPoint(connector); + final outboundHops = _outboundHops(pathData); + final candidateContacts = _mergeTraceContacts( + widget.pathContacts, + connector.allContactsUnfiltered, ); - if (widget.pathContacts != null) { - final hopWidth = width.clamp(1, pubKeySize).toInt(); - pathContacts = { - for (var c in widget.pathContacts!) - if (c.publicKey.length >= hopWidth) - _hopKey(Uint8List.fromList(c.publicKey.sublist(0, hopWidth))): c, - }; - } else { - final contacts = connector.allContactsUnfiltered; - contacts.where((c) => c.type != advTypeChat).forEach((repeater) { - if (lastContact.latitude != null && - lastContact.longitude != null && - repeater.hasLocation && - lastContact.hasLocation && - Distance().distance( - LatLng(lastContact.latitude!, lastContact.longitude!), - LatLng(repeater.latitude!, repeater.longitude!), - ) > - _maxRepeaterMatchDistanceMeters) { - return; //skip reapeaters that are far away from the last one with known GPS, to avoid false matches - } - for (final repeaterData in pathData) { - final hopWidth = repeaterData.length; - if (repeater.publicKey.length < hopWidth) continue; - if (listEquals( - repeater.publicKey.sublist(0, hopWidth), - repeaterData, - )) { - pathContacts[_hopKey(repeaterData)] = repeater; - lastContact = repeater; - } - } - }); + final resolvedOutbound = PathHopResolver.resolveHops( + hops: outboundHops, + contacts: candidateContacts, + endpoint: selfPoint, + contactFilter: (c) => c.type != advTypeChat, + ); + final Map pathContacts = {}; + for (var i = 0; i < outboundHops.length; i++) { + final contact = resolvedOutbound[i]; + if (contact != null) { + pathContacts[_hopKey(outboundHops[i])] = contact; + } } // For hops with no GPS contact, infer position from other contacts - // with known GPS that share the same last-hop byte. + // with known GPS that share the same last-hop byte, bounded by the + // plausible hop distance from neighboring anchors. + final inferredOutbound = _inferHopPositions( + hops: outboundHops, + resolvedContacts: resolvedOutbound, + selfPoint: selfPoint, + peerContacts: connector.contacts, + ); final Map inferredPositions = {}; - for (final hop in pathData) { - final hopKey = _hopKey(hop); - final contact = pathContacts[hopKey]; - if (contact != null && contact.hasLocation) continue; - final peers = connector.contacts - .where( - (c) => - c.hasLocation && - c.path.isNotEmpty && - _matchesHopPrefix( - _lastHopChunk(c.path, c.pathHashWidth), - hop, - ), - ) - .toList(); - if (peers.isNotEmpty) { - final lat = - peers.map((c) => c.latitude!).reduce((a, b) => a + b) / - peers.length; - final lon = - peers.map((c) => c.longitude!).reduce((a, b) => a + b) / - peers.length; - inferredPositions[hopKey] = LatLng(lat, lon); + for (var i = 0; i < outboundHops.length; i++) { + final inferred = inferredOutbound[i]; + if (inferred != null) { + inferredPositions[_hopKey(outboundHops[i])] = inferred; } } @@ -693,7 +655,7 @@ class _PathTraceMapScreenState extends State : hopsForEndpoint.last; final lastHopKey = _hopKey(lastHop); - final peers = connector.allContacts + final rawPeers = connector.allContacts .where( (c) => c.hasLocation && @@ -704,6 +666,19 @@ class _PathTraceMapScreenState extends State ), ) .toList(); + final (anchorPos, anchorGap) = _lastPlausibleAnchor( + outboundHops: outboundHops, + resolvedOutbound: resolvedOutbound, + inferredOutbound: inferredOutbound, + selfPoint: selfPoint, + ); + final peers = _filterPlausiblePeers( + rawPeers, + prevPos: anchorPos, + prevMaxMeters: anchorPos != null + ? anchorGap * PathHopResolver.maxSingleHopDistanceMeters + : null, + ); if (peers.isNotEmpty) { final lat = peers.map((c) => c.latitude!).reduce((a, b) => a + b) / @@ -747,7 +722,6 @@ class _PathTraceMapScreenState extends State _targetContactIsGuessed = targetGuessed; _points = []; - final selfPoint = plausibleSelfPoint(connector); if (selfPoint != null) _points.add(selfPoint); String hopLast = ''; String hopLastLast = ''; @@ -790,8 +764,12 @@ class _PathTraceMapScreenState extends State '${context.l10n.pathTrace_you},${_traceData!.pathData.map(PathHelper.formatHopHex).join(',')}', ); _pathDistanceMeters = getPathDistanceMeters(_points); - _primaryOutboundHops = _outboundHops(pathData); - _rebuildDisplayPaths(connector); + _primaryOutboundHops = outboundHops; + _rebuildDisplayPaths( + connector, + primaryResolved: resolvedOutbound, + primaryInferred: inferredOutbound, + ); }); } catch (e) { appLogger.error( @@ -823,54 +801,170 @@ class _PathTraceMapScreenState extends State return hops; } - Contact? _contactForHop(Uint8List hop, MeshCoreConnector connector) { - final hopKey = _hopKey(hop); - final traced = _traceData?.pathContacts[hopKey]; - if (traced != null) return traced; - _hopContactCacheSignature ??= _refreshHopContactCache(connector); - return _hopContactCache.putIfAbsent(hopKey, () { - for (final c in connector.allContactsUnfiltered) { - if (c.type != advTypeChat && - c.publicKey.length >= hop.length && - listEquals(c.publicKey.sublist(0, hop.length), hop)) { - return c; + List _mergeTraceContacts( + List? explicitContacts, + List allContacts, + ) { + if (explicitContacts == null) return allContacts; + final seenKeys = {}; + final merged = []; + for (final c in explicitContacts) { + if (seenKeys.add(c.publicKeyHex)) merged.add(c); + } + for (final c in allContacts) { + if (seenKeys.add(c.publicKeyHex)) merged.add(c); + } + return merged; + } + + LatLng? _contactLatLng(Contact? contact) { + if (contact == null || + !contact.hasLocation || + contact.latitude == null || + contact.longitude == null) { + return null; + } + return LatLng(contact.latitude!, contact.longitude!); + } + + List _filterPlausiblePeers( + List peers, { + LatLng? prevPos, + double? prevMaxMeters, + LatLng? nextPos, + double? nextMaxMeters, + }) { + if (peers.isEmpty) return const []; + const distance = Distance(); + var filtered = peers; + if (prevPos != null && prevMaxMeters != null) { + filtered = filtered + .where( + (c) => + distance(prevPos, LatLng(c.latitude!, c.longitude!)) <= + prevMaxMeters, + ) + .toList(); + } + if (nextPos != null && nextMaxMeters != null) { + filtered = filtered + .where( + (c) => + distance(nextPos, LatLng(c.latitude!, c.longitude!)) <= + nextMaxMeters, + ) + .toList(); + } + if (prevPos == null && nextPos == null && filtered.length > 1) { + // Without a neighboring anchor, keep only the largest consistent peer + // cluster so a single distant prefix match does not skew the average. + const maxPeerSpreadMeters = + 2 * PathHopResolver.maxSingleHopDistanceMeters; + var bestCluster = [filtered.first]; + for (final seed in filtered) { + final seedPos = LatLng(seed.latitude!, seed.longitude!); + final cluster = filtered.where((other) { + final otherPos = LatLng(other.latitude!, other.longitude!); + return distance(seedPos, otherPos) <= maxPeerSpreadMeters; + }).toList(); + if (cluster.length > bestCluster.length || + (cluster.length == bestCluster.length && + seed.lastSeen.isAfter(bestCluster.first.lastSeen))) { + bestCluster = cluster; } } - return null; - }); - } - - /// Drops cached hop -> contact lookups when the contact list changed; - /// called once per build so per-hop lookups stay cheap. - int _refreshHopContactCache(MeshCoreConnector connector) { - final signature = contactListSignature(connector.allContactsUnfiltered); - if (signature != _hopContactCacheSignature) { - _hopContactCache.clear(); - _hopContactCacheSignature = signature; + return bestCluster; } - return signature; + return filtered; } - LatLng? _inferredPositionForHop(Uint8List hop, MeshCoreConnector connector) { - final hopKey = _hopKey(hop); - final cached = _inferredHopPositions[hopKey]; - if (cached != null) return cached; - final peers = connector.contacts - .where( - (c) => - c.hasLocation && - c.path.isNotEmpty && - _matchesHopPrefix(_lastHopChunk(c.path, c.pathHashWidth), hop), - ) - .toList(); - if (peers.isEmpty) return null; - final lat = - peers.map((c) => c.latitude!).reduce((a, b) => a + b) / peers.length; - final lon = - peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length; - final pos = LatLng(lat, lon); - _inferredHopPositions[hopKey] = pos; - return pos; + List _inferHopPositions({ + required List hops, + required List resolvedContacts, + required LatLng? selfPoint, + required List peerContacts, + }) { + final inferred = List.filled(hops.length, null); + if (hops.isEmpty) return inferred; + + final anchorPositions = [ + for (var i = 0; i < hops.length; i++) + i < resolvedContacts.length + ? _contactLatLng(resolvedContacts[i]) + : null, + ]; + + LatLng? prevPos = selfPoint; + int prevStep = -1; + + for (var i = 0; i < hops.length; i++) { + final knownPos = anchorPositions[i]; + if (knownPos != null) { + prevPos = knownPos; + prevStep = i; + continue; + } + + LatLng? nextPos; + int? nextStep; + for (var j = i + 1; j < hops.length; j++) { + if (anchorPositions[j] != null) { + nextPos = anchorPositions[j]; + nextStep = j; + break; + } + } + + final hop = hops[i]; + final rawPeers = peerContacts + .where( + (c) => + c.hasLocation && + c.path.isNotEmpty && + _matchesHopPrefix(_lastHopChunk(c.path, c.pathHashWidth), hop), + ) + .toList(); + final plausiblePeers = _filterPlausiblePeers( + rawPeers, + prevPos: prevPos, + prevMaxMeters: prevPos != null + ? (i - prevStep) * PathHopResolver.maxSingleHopDistanceMeters + : null, + nextPos: nextPos, + nextMaxMeters: nextPos != null && nextStep != null + ? (nextStep - i) * PathHopResolver.maxSingleHopDistanceMeters + : null, + ); + if (plausiblePeers.isNotEmpty) { + final lat = + plausiblePeers.map((c) => c.latitude!).reduce((a, b) => a + b) / + plausiblePeers.length; + final lon = + plausiblePeers.map((c) => c.longitude!).reduce((a, b) => a + b) / + plausiblePeers.length; + final pos = LatLng(lat, lon); + inferred[i] = pos; + prevPos = pos; + prevStep = i; + } + } + + return inferred; + } + + (LatLng?, int) _lastPlausibleAnchor({ + required List outboundHops, + required List resolvedOutbound, + required List inferredOutbound, + required LatLng? selfPoint, + }) { + for (var i = outboundHops.length - 1; i >= 0; i--) { + final pos = _contactLatLng(resolvedOutbound[i]) ?? inferredOutbound[i]; + if (pos != null) { + return (pos, outboundHops.length - i); + } + } + return (selfPoint, max(1, outboundHops.length)); } String _pathKeyForHops(List hops) { @@ -879,16 +973,42 @@ class _PathTraceMapScreenState extends State /// Rebuilds the renderable paths: the traced path as primary plus up to /// four distinct alternates from the target contact's path history. - void _rebuildDisplayPaths(MeshCoreConnector connector) { - _refreshHopContactCache(connector); + void _rebuildDisplayPaths( + MeshCoreConnector connector, { + List? primaryResolved, + List? primaryInferred, + }) { + final selfPoint = plausibleSelfPoint(connector); final paths = []; + final resolvedMap = + contacts, List inferred})>{}; + + final resolvedPrimary = + primaryResolved ?? + [ + for (final hop in _primaryOutboundHops) + _traceData?.pathContacts[_hopKey(hop)], + ]; + final inferredPrimary = + primaryInferred ?? + [ + for (final hop in _primaryOutboundHops) + _inferredHopPositions[_hopKey(hop)], + ]; + resolvedMap['primary'] = ( + contacts: resolvedPrimary, + inferred: inferredPrimary, + ); + final primary = _buildDisplayPath( id: 'primary', label: context.l10n.pathMap_primary, color: kPrimaryPathColor, isPrimary: true, hops: _primaryOutboundHops, - connector: connector, + resolvedContacts: resolvedPrimary, + inferredPositions: inferredPrimary, + selfPoint: selfPoint, ); if (primary != null) paths.add(primary); @@ -905,14 +1025,30 @@ class _PathTraceMapScreenState extends State ); if (!seen.add(_pathKeyForHops(recordHops))) continue; if (altIndex >= kAlternatePathColors.length) break; + final altId = 'alt-${_pathKeyForHops(recordHops)}'; + final altResolved = PathHopResolver.resolveHops( + hops: recordHops, + contacts: connector.allContactsUnfiltered, + endpoint: selfPoint, + contactFilter: (c) => c.type != advTypeChat, + ); + final altInferred = _inferHopPositions( + hops: recordHops, + resolvedContacts: altResolved, + selfPoint: selfPoint, + peerContacts: connector.contacts, + ); + resolvedMap[altId] = (contacts: altResolved, inferred: altInferred); final alt = _buildDisplayPath( - id: 'alt-${_pathKeyForHops(recordHops)}', + id: altId, label: context.l10n.pathMap_alternate(altIndex + 1), color: kAlternatePathColors[altIndex], isPrimary: false, hops: recordHops, + resolvedContacts: altResolved, + inferredPositions: altInferred, + selfPoint: selfPoint, record: record, - connector: connector, ); if (alt != null) { paths.add(alt); @@ -921,6 +1057,9 @@ class _PathTraceMapScreenState extends State } } + _resolvedDisplayPaths + ..clear() + ..addAll(resolvedMap); _displayPaths = paths; _hiddenPathIds.removeWhere((id) => !paths.any((p) => p.id == id)); if (!paths.any((p) => p.id == _selectedPathId)) { @@ -936,12 +1075,13 @@ class _PathTraceMapScreenState extends State required Color color, required bool isPrimary, required List hops, - required MeshCoreConnector connector, + required List resolvedContacts, + required List inferredPositions, + required LatLng? selfPoint, PathRecord? record, }) { // Without a GPS fix for the local radio the path starts at the first // located hop instead of a bogus "You" at 0,0. - final selfPoint = plausibleSelfPoint(connector); final points = [?selfPoint]; final labels = [if (selfPoint != null) context.l10n.pathTrace_you]; final confirmed = [if (selfPoint != null) true]; @@ -954,15 +1094,14 @@ class _PathTraceMapScreenState extends State for (var i = 0; i < hops.length; i++) { final hop = hops[i]; final hex = PathHelper.formatHopHex(hop); - final contact = _contactForHop(hop, connector); - LatLng? pos; + final contact = i < resolvedContacts.length ? resolvedContacts[i] : null; + LatLng? pos = _contactLatLng(contact); var isGps = false; - if (contact != null && contact.hasLocation) { - pos = LatLng(contact.latitude!, contact.longitude!); + if (pos != null) { isGps = true; gpsConfirmedHops++; - } else { - pos = _inferredPositionForHop(hop, connector); + } else if (i < inferredPositions.length) { + pos = inferredPositions[i]; } if (pos == null) { unresolvedHops++; @@ -1074,7 +1213,6 @@ class _PathTraceMapScreenState extends State Widget build(BuildContext context) { return Consumer( builder: (context, connector, _) { - if (_hasData) _refreshHopContactCache(connector); final settings = context.watch().settings; final isImperial = settings.unitSystem == UnitSystem.imperial; final tileCache = context.read(); @@ -1364,32 +1502,58 @@ class _PathTraceMapScreenState extends State required bool showLabels, required Contact? target, }) { - final connector = context.read(); final markers = []; - // Hop prefix -> paths that use it, in display order. - final hopPaths = >{}; - final hopsByKey = {}; + // Hop prefix + resolved position -> paths that use it, in display order. + final hopNodes = + < + String, + ({ + Uint8List hop, + Contact? contact, + LatLng point, + bool hasGps, + List paths, + }) + >{}; for (final path in _visiblePaths) { - for (final hop in path.hopBytes) { - final hopKey = _hopKey(hop); - hopsByKey[hopKey] = hop; - final list = hopPaths.putIfAbsent(hopKey, () => []); - if (!list.contains(path)) list.add(path); + final resolved = _resolvedDisplayPaths[path.id]; + for (var i = 0; i < path.hopBytes.length; i++) { + final hop = path.hopBytes[i]; + final contact = resolved != null && i < resolved.contacts.length + ? resolved.contacts[i] + : null; + final inferred = resolved != null && i < resolved.inferred.length + ? resolved.inferred[i] + : null; + final gpsPos = _contactLatLng(contact); + final hasGps = gpsPos != null; + final point = gpsPos ?? inferred; + if (point == null) continue; + final hopKey = + '${_hopKey(hop)}|${point.latitude.toStringAsFixed(5)},' + '${point.longitude.toStringAsFixed(5)}'; + final existing = hopNodes[hopKey]; + if (existing == null) { + hopNodes[hopKey] = ( + hop: hop, + contact: contact, + point: point, + hasGps: hasGps, + paths: [path], + ); + } else if (!existing.paths.contains(path)) { + existing.paths.add(path); + } } } - for (final entry in hopPaths.entries) { - final hopKey = entry.key; - final hop = hopsByKey[hopKey]; - if (hop == null) continue; - final paths = entry.value; - final contact = _contactForHop(hop, connector); - final hasGps = contact != null && contact.hasLocation; - final point = hasGps - ? LatLng(contact.latitude!, contact.longitude!) - : _inferredPositionForHop(hop, connector); - if (point == null) continue; + for (final entry in hopNodes.values) { + final hop = entry.hop; + final paths = entry.paths; + final contact = entry.contact; + final hasGps = entry.hasGps; + final point = entry.point; final label = PathHelper.formatHopHex(hop); final baseColor = hasGps ? MeshPalette.signal : MeshPalette.warn; final shared = paths.length > 1; @@ -1796,13 +1960,19 @@ class _PathTraceMapScreenState extends State if (index < path.hopBytes.length) { final hop = path.hopBytes[index]; final hex = PathHelper.formatHopHex(hop); - final contact = _contactForHop(hop, connector); + final resolved = _resolvedDisplayPaths[path.id]; + final contact = resolved != null && index < resolved.contacts.length + ? resolved.contacts[index] + : null; title = contact != null ? '$hex: ${contact.name}' : '$hex: ${l10n.channelPath_unknownRepeater}'; final hasGps = contact != null && contact.hasLocation; final inferred = - !hasGps && _inferredPositionForHop(hop, connector) != null; + !hasGps && + resolved != null && + index < resolved.inferred.length && + resolved.inferred[index] != null; final status = hasGps ? l10n.pathTrace_legendGpsConfirmed : inferred diff --git a/test/helpers/path_hop_resolver_test.dart b/test/helpers/path_hop_resolver_test.dart index 8e903bc6..ebcbcb35 100644 --- a/test/helpers/path_hop_resolver_test.dart +++ b/test/helpers/path_hop_resolver_test.dart @@ -8,13 +8,16 @@ import 'package:meshcore_open/models/contact.dart'; Contact _contact({ required int prefix, + int? secondByte, required String name, required double latitude, required double longitude, DateTime? lastSeen, }) { + final key = Uint8List(32)..first = prefix; + if (secondByte != null) key[1] = secondByte; return Contact( - publicKey: Uint8List(32)..first = prefix, + publicKey: key, name: name, type: advTypeRepeater, pathLength: 0, @@ -91,4 +94,256 @@ void main() { expect(resolved.single?.name, 'Newer'); }); + + test( + 'rejects single candidate impossibly far and preserves previousPosition', + () { + // Arizona self/local repeaters vs East Coast collision (~3700 km away). + const selfArizona = LatLng(33.4484, -112.0740); + final azHop1 = _contact( + prefix: 0x48, + name: 'AZ Repeater 1', + latitude: 33.60097, + longitude: -112.02457, + ); + final eastCoastBogus = _contact( + prefix: 0x9C, + name: 'East Coast 9C', + latitude: 42.3601, + longitude: -71.0589, + ); + final azHop3 = _contact( + prefix: 0x53, + name: 'AZ Repeater 2', + latitude: 33.46300, + longitude: -111.65000, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x53, 0x9C, 0x48], + contacts: [azHop1, eastCoastBogus, azHop3], + endpoint: selfArizona, + resolveFromEnd: true, + ); + + expect(resolved.map((c) => c?.name), [ + 'AZ Repeater 2', + null, + 'AZ Repeater 1', + ]); + }, + ); + + test('rejects multiple candidates when all are impossibly far', () { + const selfArizona = LatLng(33.4484, -112.0740); + final eastCoast = _contact( + prefix: 0x9C, + name: 'East Coast 9C', + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026, 2), + ); + final europe = _contact( + prefix: 0x9C, + name: 'Europe 9C', + latitude: 48.8566, + longitude: 2.3522, + lastSeen: DateTime.utc(2026, 1), + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C], + contacts: [eastCoast, europe], + endpoint: selfArizona, + ); + + expect(resolved, [null]); + }); + + test( + 'picks plausible candidate when another candidate is impossibly far', + () { + const selfArizona = LatLng(33.4484, -112.0740); + final eastCoastNewer = _contact( + prefix: 0x9C, + name: 'East Coast 9C', + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026, 5), + ); + final localOlder = _contact( + prefix: 0x9C, + name: 'Local AZ 9C', + latitude: 33.50, + longitude: -111.90, + lastSeen: DateTime.utc(2026, 1), + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C], + contacts: [eastCoastNewer, localOlder], + endpoint: selfArizona, + ); + + expect(resolved.single?.name, 'Local AZ 9C'); + }, + ); + + test('consecutive unresolved hops widen distance budget proportionally', () { + // At equator, 1 degree longitude is ~111.32 km. + // With 2 unresolved intermediate hops (hopGap = 3), budget is 3 * 250 km = 750 km. + // 6.0 degrees (~667.9 km) is beyond 1-hop (250 km) and 2-hop (500 km), + // but within 3-hop (750 km). + const endpoint = LatLng(0, 0); + final distantValid = _contact( + prefix: 0xCC, + name: 'Valid 3-hop target', + latitude: 0, + longitude: 6.0, + ); + + final resolvedWithTwoUnknowns = PathHopResolver.resolve( + pathBytes: const [0xAA, 0xBB, 0xCC], + contacts: [distantValid], + endpoint: endpoint, + ); + expect(resolvedWithTwoUnknowns, [null, null, distantValid]); + + // With only 1 hop (hopGap = 1, budget = 250 km), 6.0 degrees is rejected. + final resolvedDirect = PathHopResolver.resolve( + pathBytes: const [0xCC], + contacts: [distantValid], + endpoint: endpoint, + ); + expect(resolvedDirect, [null]); + }); + + test( + 'endpoint == null rejects a leading distant outlier and keeps local cluster', + () { + final bogusFirst = _contact( + prefix: 0x9C, + name: 'East Coast Outlier', + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026, 6), + ); + final local1 = _contact( + prefix: 0x48, + name: 'Local 1', + latitude: 33.60097, + longitude: -112.02457, + ); + final local2 = _contact( + prefix: 0x53, + name: 'Local 2', + latitude: 33.46300, + longitude: -111.65000, + ); + final local3 = _contact( + prefix: 0x6C, + name: 'Local 3', + latitude: 33.42, + longitude: -111.80, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C, 0x48, 0x53, 0x6C], + contacts: [bogusFirst, local1, local2, local3], + endpoint: null, + ); + + expect(resolved.map((c) => c?.name), [ + null, + 'Local 1', + 'Local 2', + 'Local 3', + ]); + }, + ); + + test( + 'endpoint != null rejects first-hop outlier and resolves subsequent local hops', + () { + const selfArizona = LatLng(33.4484, -112.0740); + final bogusFirst = _contact( + prefix: 0xEA, + name: 'East Coast First Hop', + latitude: 42.3601, + longitude: -71.0589, + ); + final local2 = _contact( + prefix: 0x48, + name: 'Local 2', + latitude: 33.60097, + longitude: -112.02457, + ); + final local3 = _contact( + prefix: 0x53, + name: 'Local 3', + latitude: 33.46300, + longitude: -111.65000, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0xEA, 0x48, 0x53], + contacts: [bogusFirst, local2, local3], + endpoint: selfArizona, + ); + + expect(resolved.map((c) => c?.name), [null, 'Local 2', 'Local 3']); + }, + ); + + test('legitimate long-range line-of-sight LoRa hops still resolve', () { + // ~200 km mountain-to-mountain hop (within 250 km single-hop budget). + const self = LatLng(33.4484, -112.0740); + final mountainPeak = _contact( + prefix: 0xAA, + name: 'Mountain Peak', + latitude: 35.1983, + longitude: -111.6513, // Flagstaff (~198 km from Phoenix) + ); + final secondPeak = _contact( + prefix: 0xBB, + name: 'North Rim', + latitude: 36.2100, + longitude: -112.0600, // ~118 km from Flagstaff + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0xAA, 0xBB], + contacts: [mountainPeak, secondPeak], + endpoint: self, + ); + + expect(resolved.map((c) => c?.name), ['Mountain Peak', 'North Rim']); + }); + + test('multi-byte path hash width rejects impossible hop', () { + const self = LatLng(33.4484, -112.0740); + final local = _contact( + prefix: 0x48, + secondByte: 0x01, + name: 'Local 2-byte', + latitude: 33.60, + longitude: -112.02, + ); + final bogus = _contact( + prefix: 0x9C, + secondByte: 0x02, + name: 'Bogus 2-byte', + latitude: 40.7128, + longitude: -74.0060, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x48, 0x01, 0x9C, 0x02], + contacts: [local, bogus], + endpoint: self, + pathHashByteWidth: 2, + ); + + expect(resolved.map((c) => c?.name), ['Local 2-byte', null]); + }); } diff --git a/test/screens/channel_message_path_map_test.dart b/test/screens/channel_message_path_map_test.dart new file mode 100644 index 00000000..50d1a3c1 --- /dev/null +++ b/test/screens/channel_message_path_map_test.dart @@ -0,0 +1,292 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/channel_message_path_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:provider/provider.dart'; + +class _FakeConnector extends MeshCoreConnector { + _FakeConnector(this._contacts, {this.lat = 33.4484, this.lon = -112.0740}); + + final List _contacts; + final double? lat; + final double? lon; + + @override + List get allContacts => _contacts; + + @override + double? get selfLatitude => lat; + + @override + double? get selfLongitude => lon; +} + +Contact _repeater({ + required int prefix, + required String name, + required double latitude, + required double longitude, +}) { + return Contact( + publicKey: Uint8List(32)..first = prefix, + name: name, + type: advTypeRepeater, + pathLength: 0, + path: Uint8List(0), + latitude: latitude, + longitude: longitude, + lastSeen: DateTime.utc(2026), + ); +} + +Widget _wrapWithProviders(MeshCoreConnector connector, Widget child) { + final settings = AppSettingsService(); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider( + create: (_) => MapTileCacheService(appSettingsService: settings), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: child, + ), + ); +} + +void main() { + testWidgets( + 'ChannelMessagePathMapScreen ignores impossible distant hop in polylines, markers, bounds, distance, and hop list', + (tester) async { + final localHop3 = _repeater( + prefix: 0x53, + name: "Rod's Repeater", + latitude: 33.46300, + longitude: -111.65000, + ); + final localHop4 = _repeater( + prefix: 0x48, + name: 'Twain - Clearview', + latitude: 33.60097, + longitude: -112.02457, + ); + final bogusEastCoastHop5 = _repeater( + prefix: 0x9C, + name: 'Beacon Hill 1W Repeater', + latitude: 42.3601, + longitude: -71.0589, + ); + final connector = _FakeConnector([ + localHop3, + localHop4, + bogusEastCoastHop5, + ]); + + final message = ChannelMessage( + senderName: 'Alice', + text: 'test', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([ + 0x6C, + 0x84, + 0x53, + 0x48, + 0x9C, + 0x21, + 0xC9, + 0xEA, + ]), + channelIndex: 0, + ); + + await tester.pumpWidget( + _wrapWithProviders( + connector, + ChannelMessagePathMapScreen(message: message, channelMessage: true), + ), + ); + await tester.pumpAndSettle(); + + // East Coast repeater must not appear as a resolved repeater or in markers. + expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing); + expect(find.textContaining('42.36010'), findsNothing); + + // Expand the hop list panel so all 8 hops in the ListView are built. + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.text('(9C) Unknown Repeater'), findsOneWidget); + + // Local repeaters should still be listed and plotted. + expect(find.text("(53) Rod's Repeater"), findsOneWidget); + expect(find.text('(48) Twain - Clearview'), findsOneWidget); + + // Collapse back so map assertions (PolylineLayer, MarkerLayer, header distance) are visible. + await tester.tap(find.byIcon(Icons.close_fullscreen)); + await tester.pumpAndSettle(); + + // Polyline points and markers must stay in Arizona (no East Coast jump). + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPolylinePoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPolylinePoints, isNotEmpty); + for (final point in allPolylinePoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + + // Segment across unresolved/ignored hops (4 -> You) must be dashed while + // adjacent local hops (3 -> 4) remain solid. + expect( + polylineLayer.polylines.any((p) => p.pattern != StrokePattern.solid()), + isTrue, + ); + + final markerLayer = tester.widget( + find.byType(MarkerLayer).first, + ); + for (final marker in markerLayer.markers) { + expect(marker.point.latitude, inInclusiveRange(33.0, 34.0)); + expect(marker.point.longitude, inInclusiveRange(-113.0, -111.0)); + } + + // Camera bounds must stay local, not continental. + final flutterMap = tester.widget(find.byType(FlutterMap)); + final fit = flutterMap.options.initialCameraFit as FitBounds; + expect(fit.bounds.north, lessThan(34.0)); + expect(fit.bounds.east, lessThan(-111.0)); + + // Reported path distance must be local (~50-65 km), not thousands of km. + final distanceFinder = find.textContaining(' km)'); + expect(distanceFinder, findsOneWidget); + final distanceText = tester.widget(distanceFinder).data!; + final kmMatch = RegExp(r'\((\d+\.\d+) km\)').firstMatch(distanceText); + expect(kmMatch, isNotNull); + final kmValue = double.parse(kmMatch!.group(1)!); + expect(kmValue, lessThan(200.0)); + expect(kmValue, greaterThan(10.0)); + }, + ); + + testWidgets( + 'ChannelMessagePathMapScreen without self GPS rejects leading outlier and keeps local cluster', + (tester) async { + final bogusEastCoast = _repeater( + prefix: 0x9C, + name: 'Beacon Hill 1W Repeater', + latitude: 42.3601, + longitude: -71.0589, + ); + final localHop1 = _repeater( + prefix: 0x48, + name: 'Twain - Clearview', + latitude: 33.60097, + longitude: -112.02457, + ); + final localHop2 = _repeater( + prefix: 0x53, + name: "Rod's Repeater", + latitude: 33.46300, + longitude: -111.65000, + ); + final connector = _FakeConnector( + [bogusEastCoast, localHop1, localHop2], + lat: null, + lon: null, + ); + + final message = ChannelMessage( + senderName: 'Alice', + text: 'test', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([0x53, 0x48, 0x9C]), + channelIndex: 0, + ); + + await tester.pumpWidget( + _wrapWithProviders( + connector, + ChannelMessagePathMapScreen(message: message, channelMessage: true), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing); + expect(find.text('(9C) Unknown Repeater'), findsOneWidget); + expect(find.text('(48) Twain - Clearview'), findsOneWidget); + expect(find.text("(53) Rod's Repeater"), findsOneWidget); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 2); + for (final point in allPoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + }, + ); + + testWidgets( + 'ChannelMessagePathScreen timeline treats impossible distant hop as unknown', + (tester) async { + final localHop = _repeater( + prefix: 0x48, + name: 'Twain - Clearview', + latitude: 33.60097, + longitude: -112.02457, + ); + final bogusHop = _repeater( + prefix: 0x9C, + name: 'Beacon Hill 1W Repeater', + latitude: 42.3601, + longitude: -71.0589, + ); + final connector = _FakeConnector([localHop, bogusHop]); + + final message = ChannelMessage( + senderName: 'Alice', + text: 'test', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([0x48, 0x9C]), + channelIndex: 0, + ); + + await tester.pumpWidget( + _wrapWithProviders( + connector, + ChannelMessagePathScreen(message: message, channelMessage: true), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('(48) Twain - Clearview'), findsOneWidget); + expect(find.text('(9C) Unknown Repeater'), findsOneWidget); + expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing); + }, + ); +} diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart index 74b2b37a..825c76d2 100644 --- a/test/screens/path_trace_test.dart +++ b/test/screens/path_trace_test.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'dart:typed_data'; @@ -40,16 +41,31 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { Uint8List.fromList(List.generate(32, (i) => i)); @override - double? get selfLatitude => 48.8566; + double? get selfLatitude => _selfLat; @override - double? get selfLongitude => 2.3522; + double? get selfLongitude => _selfLon; @override - List get allContactsUnfiltered => []; + List get allContactsUnfiltered => _allContacts; @override - List get contacts => []; + List get contacts => _peerContacts; + + final double? _selfLat; + final double? _selfLon; + final List _allContacts; + final List _peerContacts; + + _FakeMeshCoreConnector({ + double? selfLat = 48.8566, + double? selfLon = 2.3522, + List allContacts = const [], + List peerContacts = const [], + }) : _selfLat = selfLat, + _selfLon = selfLon, + _allContacts = allContacts, + _peerContacts = peerContacts; void emitFrame(Uint8List frame) { _receivedFramesController.add(frame); @@ -400,4 +416,170 @@ void main() { // Verify it parsed correctly (should not show the unavailable message) expect(find.text('Path trace not available.'), findsNothing); }); + + testWidgets( + 'PathTraceMapScreen ignores impossible distant repeater and peer inference', + (tester) async { + final localHop1 = Contact( + publicKey: Uint8List(32)..first = 0x48, + name: 'Local Hop', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.60097, + longitude: -112.02457, + lastSeen: DateTime.utc(2026), + ); + final eastCoastBogus = Contact( + publicKey: Uint8List(32)..first = 0x9C, + name: 'East Coast 9C', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026), + ); + final distantPeerSharing9C = Contact( + publicKey: Uint8List(32)..first = 0xAA, + name: 'Distant Chat Peer', + type: advTypeChat, + path: Uint8List.fromList([0x9C]), + pathLength: 1, + latitude: 42.35, + longitude: -71.06, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + selfLat: 33.4484, + selfLon: -112.0740, + allContacts: [localHop1, eastCoastBogus], + peerContacts: [distantPeerSharing9C], + ); + + final screen = PathTraceMapScreen( + title: 'Trace Impossible Hop', + path: Uint8List.fromList([0x48, 0x9C]), + pathHashByteWidth: 1, + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + final sentFrame = connector.sentFrames.first; + final tag = sentFrame.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x9C]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('East Coast 9C'), findsNothing); + expect(find.textContaining('9C: Unknown Repeater'), findsWidgets); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints, isNotEmpty); + for (final point in allPoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + }, + ); + + testWidgets( + 'PathTraceMapScreen ignores impossible distant contact passed via pathContacts', + (tester) async { + final localHop1 = Contact( + publicKey: Uint8List(32)..first = 0x48, + name: 'Local Hop', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.60097, + longitude: -112.02457, + lastSeen: DateTime.utc(2026), + ); + final eastCoastBogus = Contact( + publicKey: Uint8List(32)..first = 0x9C, + name: 'East Coast 9C', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + selfLat: 33.4484, + selfLon: -112.0740, + allContacts: [localHop1, eastCoastBogus], + ); + + final screen = PathTraceMapScreen( + title: 'Manual Trace Impossible Hop', + path: Uint8List.fromList([0x48, 0x9C]), + pathHashByteWidth: 1, + pathContacts: [localHop1, eastCoastBogus], + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + final sentFrame = connector.sentFrames.first; + final tag = sentFrame.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x9C]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('East Coast 9C'), findsNothing); + expect(find.textContaining('9C: Unknown Repeater'), findsWidgets); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 2); + for (final point in allPoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + }, + ); } From 222b45e13051c557322cda713ca893d1e220b916 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:44:39 -0700 Subject: [PATCH 33/50] Keep explicit trace contacts and re-resolve on self move Keep plausible explicit pathContacts authoritative over nearer general contacts sharing a hop prefix while still rejecting impossibly far hops. Re-resolve primary outbound hops, inferred positions, target guess, and map points when _rebuildDisplayPaths runs after self location changes. --- lib/helpers/path_hop_resolver.dart | 185 +++++++++-- lib/screens/path_trace_map.dart | 401 +++++++++++------------ test/helpers/path_hop_resolver_test.dart | 80 +++++ test/screens/path_trace_test.dart | 247 +++++++++++++- 4 files changed, 671 insertions(+), 242 deletions(-) diff --git a/lib/helpers/path_hop_resolver.dart b/lib/helpers/path_hop_resolver.dart index af39983d..ac712dd6 100644 --- a/lib/helpers/path_hop_resolver.dart +++ b/lib/helpers/path_hop_resolver.dart @@ -21,6 +21,7 @@ class PathHopResolver { bool resolveFromEnd = false, int pathHashByteWidth = 1, double maxHopDistanceMeters = maxSingleHopDistanceMeters, + List? preferredContacts, }) { final width = pathHashByteWidth.clamp(1, 3).toInt(); final hops = PathHelper.splitPathBytes(pathBytes, width); @@ -30,6 +31,7 @@ class PathHopResolver { endpoint: endpoint, resolveFromEnd: resolveFromEnd, maxHopDistanceMeters: maxHopDistanceMeters, + preferredContacts: preferredContacts, ); } @@ -40,6 +42,7 @@ class PathHopResolver { bool resolveFromEnd = false, double maxHopDistanceMeters = maxSingleHopDistanceMeters, bool Function(Contact)? contactFilter, + List? preferredContacts, }) { if (hops.isEmpty) return const []; @@ -47,21 +50,41 @@ class PathHopResolver { for (final hop in hops) if (hop.isNotEmpty) hop.length, }; - final candidatesByPrefix = >{}; - for (final contact in contacts) { - final include = - contactFilter?.call(contact) ?? - (contact.type == advTypeRepeater || contact.type == advTypeRoom); - if (!include) continue; + bool includeContact(Contact contact) => + contactFilter?.call(contact) ?? + (contact.type == advTypeRepeater || contact.type == advTypeRoom); + + void indexContact(Map> buckets, Contact contact) { for (final width in widths) { if (contact.publicKey.length < width) continue; final prefix = PathHelper.formatHopHex( contact.publicKey.sublist(0, width), ); - candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); + buckets.putIfAbsent(prefix, () => []).add(contact); } } - for (final candidates in candidatesByPrefix.values) { + + final preferredKeys = {}; + final preferredByPrefix = >{}; + if (preferredContacts != null) { + for (final contact in preferredContacts) { + if (!includeContact(contact)) continue; + preferredKeys.add(contact.publicKeyHex); + indexContact(preferredByPrefix, contact); + } + } + + final fallbackByPrefix = >{}; + for (final contact in contacts) { + if (!includeContact(contact)) continue; + if (preferredKeys.contains(contact.publicKeyHex)) continue; + indexContact(fallbackByPrefix, contact); + } + + for (final candidates in preferredByPrefix.values) { + candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); + } + for (final candidates in fallbackByPrefix.values) { candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); } @@ -75,13 +98,14 @@ class PathHopResolver { ]; final distance = Distance(); - (Contact, double)? pickNearestLocated( + (Contact, double)? pickNearestLocatedFrom( + Map> buckets, String prefix, Set used, LatLng anchor, double maxDistanceMeters, ) { - final candidates = candidatesByPrefix[prefix]; + final candidates = buckets[prefix]; if (candidates == null || candidates.isEmpty) return null; Contact? best; double? bestDistance; @@ -100,8 +124,12 @@ class PathHopResolver { return (best, bestDistance); } - Contact? pickFirstUnlocated(String prefix, Set used) { - final candidates = candidatesByPrefix[prefix]; + Contact? pickFirstUnlocatedFrom( + Map> buckets, + String prefix, + Set used, + ) { + final candidates = buckets[prefix]; if (candidates == null || candidates.isEmpty) return null; for (final candidate in candidates) { if (used.contains(candidate)) continue; @@ -110,8 +138,12 @@ class PathHopResolver { return null; } - Contact? pickFirstAny(String prefix, Set used) { - final candidates = candidatesByPrefix[prefix]; + Contact? pickFirstAnyFrom( + Map> buckets, + String prefix, + Set used, + ) { + final candidates = buckets[prefix]; if (candidates == null || candidates.isEmpty) return null; for (final candidate in candidates) { if (!used.contains(candidate)) return candidate; @@ -119,6 +151,44 @@ class PathHopResolver { return null; } + (Contact, double, bool)? pickBestLocated( + String prefix, + Set used, + LatLng anchor, + double maxDistanceMeters, + ) { + final preferred = pickNearestLocatedFrom( + preferredByPrefix, + prefix, + used, + anchor, + maxDistanceMeters, + ); + if (preferred != null) return (preferred.$1, preferred.$2, true); + if (pickFirstUnlocatedFrom(preferredByPrefix, prefix, used) != null) { + return null; + } + final fallback = pickNearestLocatedFrom( + fallbackByPrefix, + prefix, + used, + anchor, + maxDistanceMeters, + ); + if (fallback != null) return (fallback.$1, fallback.$2, false); + return null; + } + + Contact? pickBestUnlocated(String prefix, Set used) { + return pickFirstUnlocatedFrom(preferredByPrefix, prefix, used) ?? + pickFirstUnlocatedFrom(fallbackByPrefix, prefix, used); + } + + Contact? pickBestAny(String prefix, Set used) { + return pickFirstAnyFrom(preferredByPrefix, prefix, used) ?? + pickFirstAnyFrom(fallbackByPrefix, prefix, used); + } + final used = Set.identity(); if (endpoint != null) { @@ -128,19 +198,48 @@ class PathHopResolver { final prefix = stepPrefixes[step]; final hopGap = step - lastAnchorStep; final maxAllowed = hopGap * maxHopDistanceMeters; - final match = pickNearestLocated( + final preferred = pickNearestLocatedFrom( + preferredByPrefix, prefix, used, previousPosition, maxAllowed, ); - if (match != null) { - used.add(match.$1); - resolved[indexes[step]] = match.$1; - previousPosition = _positionOf(match.$1)!; + if (preferred != null) { + used.add(preferred.$1); + resolved[indexes[step]] = preferred.$1; + previousPosition = _positionOf(preferred.$1)!; + lastAnchorStep = step; + continue; + } + final preferredUnlocated = pickFirstUnlocatedFrom( + preferredByPrefix, + prefix, + used, + ); + if (preferredUnlocated != null) { + used.add(preferredUnlocated); + resolved[indexes[step]] = preferredUnlocated; + continue; + } + final fallback = pickNearestLocatedFrom( + fallbackByPrefix, + prefix, + used, + previousPosition, + maxAllowed, + ); + if (fallback != null) { + used.add(fallback.$1); + resolved[indexes[step]] = fallback.$1; + previousPosition = _positionOf(fallback.$1)!; lastAnchorStep = step; } else { - final unlocated = pickFirstUnlocated(prefix, used); + final unlocated = pickFirstUnlocatedFrom( + fallbackByPrefix, + prefix, + used, + ); if (unlocated != null) { used.add(unlocated); resolved[indexes[step]] = unlocated; @@ -153,18 +252,24 @@ class PathHopResolver { // Without a known endpoint, find the located anchor whose plausible chain // explains the most located hops so a single distant prefix collision does // not poison the rest of the path. - var hasAnyLocated = false; - for (final prefix in stepPrefixes) { - final candidates = candidatesByPrefix[prefix]; - if (candidates != null && candidates.any((c) => _positionOf(c) != null)) { - hasAnyLocated = true; - break; + bool bucketHasLocated(Map> buckets) { + for (final prefix in stepPrefixes) { + final candidates = buckets[prefix]; + if (candidates != null && + candidates.any((c) => _positionOf(c) != null)) { + return true; + } } + return false; } + final hasAnyLocated = + bucketHasLocated(preferredByPrefix) || + bucketHasLocated(fallbackByPrefix); + if (!hasAnyLocated) { for (var step = 0; step < hopCount; step++) { - final contact = pickFirstAny(stepPrefixes[step], used); + final contact = pickBestAny(stepPrefixes[step], used); if (contact != null) { used.add(contact); resolved[indexes[step]] = contact; @@ -175,13 +280,19 @@ class PathHopResolver { List? bestRun; var bestLocatedCount = 0; + var bestPreferredCount = 0; var bestTotalDistance = double.infinity; var bestLastSeenSum = -1; for (var anchorStep = 0; anchorStep < hopCount; anchorStep++) { - final candidates = candidatesByPrefix[stepPrefixes[anchorStep]]; - if (candidates == null) continue; - for (final anchorCandidate in candidates) { + final prefix = stepPrefixes[anchorStep]; + final anchorCandidates = <(Contact, bool)>[ + for (final c in preferredByPrefix[prefix] ?? const []) + (c, true), + for (final c in fallbackByPrefix[prefix] ?? const []) + (c, false), + ]; + for (final (anchorCandidate, isPreferredAnchor) in anchorCandidates) { final anchorPos = _positionOf(anchorCandidate); if (anchorPos == null) continue; @@ -189,6 +300,7 @@ class PathHopResolver { final runUsed = Set.identity()..add(anchorCandidate); run[anchorStep] = anchorCandidate; var locatedCount = 1; + var preferredCount = isPreferredAnchor ? 1 : 0; var totalDistance = 0.0; var lastSeenSum = anchorCandidate.lastSeen.millisecondsSinceEpoch; @@ -196,7 +308,7 @@ class PathHopResolver { var lastAnchor = anchorStep; for (var step = anchorStep + 1; step < hopCount; step++) { final maxAllowed = (step - lastAnchor) * maxHopDistanceMeters; - final match = pickNearestLocated( + final match = pickBestLocated( stepPrefixes[step], runUsed, prevPos, @@ -208,6 +320,7 @@ class PathHopResolver { prevPos = _positionOf(match.$1)!; lastAnchor = step; locatedCount++; + if (match.$3) preferredCount++; totalDistance += match.$2; lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; } @@ -216,7 +329,7 @@ class PathHopResolver { lastAnchor = anchorStep; for (var step = anchorStep - 1; step >= 0; step--) { final maxAllowed = (lastAnchor - step) * maxHopDistanceMeters; - final match = pickNearestLocated( + final match = pickBestLocated( stepPrefixes[step], runUsed, prevPos, @@ -228,6 +341,7 @@ class PathHopResolver { prevPos = _positionOf(match.$1)!; lastAnchor = step; locatedCount++; + if (match.$3) preferredCount++; totalDistance += match.$2; lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; } @@ -235,13 +349,18 @@ class PathHopResolver { final isBetter = locatedCount > bestLocatedCount || (locatedCount == bestLocatedCount && + preferredCount > bestPreferredCount) || + (locatedCount == bestLocatedCount && + preferredCount == bestPreferredCount && totalDistance < bestTotalDistance - 1e-6) || (locatedCount == bestLocatedCount && + preferredCount == bestPreferredCount && (totalDistance - bestTotalDistance).abs() <= 1e-6 && lastSeenSum > bestLastSeenSum); if (isBetter) { bestRun = run; bestLocatedCount = locatedCount; + bestPreferredCount = preferredCount; bestTotalDistance = totalDistance; bestLastSeenSum = lastSeenSum; } @@ -258,7 +377,7 @@ class PathHopResolver { } for (var step = 0; step < hopCount; step++) { if (bestRun[step] != null) continue; - final unlocated = pickFirstUnlocated(stepPrefixes[step], used); + final unlocated = pickBestUnlocated(stepPrefixes[step], used); if (unlocated != null) { used.add(unlocated); resolved[indexes[step]] = unlocated; diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index 63d6d59c..198616de 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -25,6 +25,7 @@ import 'package:meshcore_open/widgets/path_map_ui.dart'; import 'package:meshcore_open/widgets/snr_indicator.dart'; import 'package:meshcore_open/widgets/set_my_location_dialog.dart'; import 'package:provider/provider.dart'; + import '../theme/mesh_theme.dart'; export 'package:meshcore_open/widgets/path_map_ui.dart' @@ -584,192 +585,20 @@ class _PathTraceMapScreenState extends State .map((snr) => snr.toSigned(8).toDouble() / 4) .toList(); - final selfPoint = plausibleSelfPoint(connector); - final outboundHops = _outboundHops(pathData); - final candidateContacts = _mergeTraceContacts( - widget.pathContacts, - connector.allContactsUnfiltered, - ); - final resolvedOutbound = PathHopResolver.resolveHops( - hops: outboundHops, - contacts: candidateContacts, - endpoint: selfPoint, - contactFilter: (c) => c.type != advTypeChat, - ); - final Map pathContacts = {}; - for (var i = 0; i < outboundHops.length; i++) { - final contact = resolvedOutbound[i]; - if (contact != null) { - pathContacts[_hopKey(outboundHops[i])] = contact; - } - } - - // For hops with no GPS contact, infer position from other contacts - // with known GPS that share the same last-hop byte, bounded by the - // plausible hop distance from neighboring anchors. - final inferredOutbound = _inferHopPositions( - hops: outboundHops, - resolvedContacts: resolvedOutbound, - selfPoint: selfPoint, - peerContacts: connector.contacts, - ); - final Map inferredPositions = {}; - for (var i = 0; i < outboundHops.length; i++) { - final inferred = inferredOutbound[i]; - if (inferred != null) { - inferredPositions[_hopKey(outboundHops[i])] = inferred; - } - } - setState(() { _isLoading = false; _hasData = true; - _inferredHopPositions = inferredPositions; + _targetContact = widget.targetContact; + _primaryOutboundHops = _outboundHops(pathData); _traceData = PathTraceData( pathData: pathData, snrData: snrData, - pathContacts: pathContacts, + pathContacts: const {}, ); - // Compute endpoint position for the target contact. - LatLng? targetPos; - bool targetGuessed = false; - _targetContact = widget.targetContact; - - if (_targetContact != null) { - final tc = _targetContact!; - if (tc.hasLocation) { - targetPos = LatLng(tc.latitude!, tc.longitude!); - } else if (pathData.length > 1 || _tracedPath.isNotEmpty) { - // Infer from the last hop: average GPS contacts sharing that hop. - // For a round-trip path (flipPathAround/reversePathAround), the target-side hop - // sits in the middle of the symmetric sequence; .last is the local side. - final tracedHops = PathHelper.splitPathBytes( - _tracedPath, - _tracedPathHashWidth, - ); - final hopsForEndpoint = tracedHops.isNotEmpty - ? tracedHops - : pathData; - final lastHop = widget.reversePathAround - ? hopsForEndpoint.first - : hopsForEndpoint.last; - final lastHopKey = _hopKey(lastHop); - - final rawPeers = connector.allContacts - .where( - (c) => - c.hasLocation && - c.path.isNotEmpty && - _matchesHopPrefix( - _lastHopChunk(c.path, c.pathHashWidth), - lastHop, - ), - ) - .toList(); - final (anchorPos, anchorGap) = _lastPlausibleAnchor( - outboundHops: outboundHops, - resolvedOutbound: resolvedOutbound, - inferredOutbound: inferredOutbound, - selfPoint: selfPoint, - ); - final peers = _filterPlausiblePeers( - rawPeers, - prevPos: anchorPos, - prevMaxMeters: anchorPos != null - ? anchorGap * PathHopResolver.maxSingleHopDistanceMeters - : null, - ); - if (peers.isNotEmpty) { - final lat = - peers.map((c) => c.latitude!).reduce((a, b) => a + b) / - peers.length; - final lon = - peers.map((c) => c.longitude!).reduce((a, b) => a + b) / - peers.length; - const offsetDeg = 0.003; - final angle = (tc.publicKey[1] / 255.0) * 2 * pi; - targetPos = LatLng( - lat + offsetDeg * cos(angle), - lon + offsetDeg * sin(angle), - ); - targetGuessed = true; - } else if (inferredPositions.containsKey(lastHopKey)) { - final lat = inferredPositions[lastHopKey]!.latitude; - final lon = inferredPositions[lastHopKey]!.longitude; - const offsetDeg = 0.003; - final angle = (tc.publicKey[1] / 255.0) * 2 * pi; - targetPos = LatLng( - lat + offsetDeg * cos(angle), - lon + offsetDeg * sin(angle), - ); - targetGuessed = true; - } else { - // As a last resort, just place it at the same position as the last hop. - final contact = pathContacts[lastHopKey]; - if (contact != null && contact.hasLocation) { - const offsetDeg = 0.003; - final angle = (tc.publicKey[1] / 255.0) * 2 * pi; - targetPos = LatLng( - contact.latitude! + offsetDeg * cos(angle), - contact.longitude! + offsetDeg * sin(angle), - ); - targetGuessed = true; - } - } - } - } - _targetContactPosition = targetPos; - _targetContactIsGuessed = targetGuessed; - - _points = []; - if (selfPoint != null) _points.add(selfPoint); - String hopLast = ''; - String hopLastLast = ''; - for (final hop in _traceData!.pathData) { - final hopKey = _hopKey(hop); - if (hopKey == hopLastLast && widget.flipPathAround) { - break; //skip duplicate hops in round-trip paths - } - final contact = _traceData!.pathContacts[hopKey]; - if (contact != null && contact.hasLocation) { - _points.add(LatLng(contact.latitude!, contact.longitude!)); - } else { - final inferred = inferredPositions[hopKey]; - if (inferred != null) _points.add(inferred); - } - hopLastLast = hopLast; - hopLast = hopKey; - } - if (targetPos != null) { - if (_targetContact != null && _targetContact!.type == advTypeChat) { - _points.add(targetPos); - } - } - _polylines = _points.length > 1 - ? [ - Polyline( - points: _points, - strokeWidth: 4, - color: kPrimaryPathColor, - ), - ] - : []; - - _initialCenter = _points.isNotEmpty - ? _points.first - : const LatLng(0, 0); - _initialZoom = _points.isNotEmpty ? 13.0 : 2.0; - _bounds = _points.length > 1 ? LatLngBounds.fromPoints(_points) : null; _mapKey = ValueKey( - '${context.l10n.pathTrace_you},${_traceData!.pathData.map(PathHelper.formatHopHex).join(',')}', - ); - _pathDistanceMeters = getPathDistanceMeters(_points); - _primaryOutboundHops = outboundHops; - _rebuildDisplayPaths( - connector, - primaryResolved: resolvedOutbound, - primaryInferred: inferredOutbound, + '${context.l10n.pathTrace_you},${pathData.map(PathHelper.formatHopHex).join(',')}', ); + _rebuildDisplayPaths(connector); }); } catch (e) { appLogger.error( @@ -801,20 +630,173 @@ class _PathTraceMapScreenState extends State return hops; } - List _mergeTraceContacts( - List? explicitContacts, - List allContacts, - ) { - if (explicitContacts == null) return allContacts; - final seenKeys = {}; - final merged = []; - for (final c in explicitContacts) { - if (seenKeys.add(c.publicKeyHex)) merged.add(c); + (LatLng?, bool) _resolveTargetContactPosition({ + required MeshCoreConnector connector, + required List pathData, + required List outboundHops, + required List resolvedOutbound, + required List inferredOutbound, + required Map pathContacts, + required Map inferredPositions, + required LatLng? selfPoint, + }) { + final tc = _targetContact; + if (tc == null) return (null, false); + if (tc.hasLocation) { + return (LatLng(tc.latitude!, tc.longitude!), false); } - for (final c in allContacts) { - if (seenKeys.add(c.publicKeyHex)) merged.add(c); + if (pathData.length <= 1 && _tracedPath.isEmpty) { + return (null, false); } - return merged; + + // Infer from the last hop: average GPS contacts sharing that hop. + // For a round-trip path (flipPathAround/reversePathAround), the target-side hop + // sits in the middle of the symmetric sequence; .last is the local side. + final tracedHops = PathHelper.splitPathBytes( + _tracedPath, + _tracedPathHashWidth, + ); + final hopsForEndpoint = tracedHops.isNotEmpty ? tracedHops : pathData; + final lastHop = widget.reversePathAround + ? hopsForEndpoint.first + : hopsForEndpoint.last; + final lastHopKey = _hopKey(lastHop); + + final rawPeers = connector.allContacts + .where( + (c) => + c.hasLocation && + c.path.isNotEmpty && + _matchesHopPrefix( + _lastHopChunk(c.path, c.pathHashWidth), + lastHop, + ), + ) + .toList(); + final (anchorPos, anchorGap) = _lastPlausibleAnchor( + outboundHops: outboundHops, + resolvedOutbound: resolvedOutbound, + inferredOutbound: inferredOutbound, + selfPoint: selfPoint, + ); + final peers = _filterPlausiblePeers( + rawPeers, + prevPos: anchorPos, + prevMaxMeters: anchorPos != null + ? anchorGap * PathHopResolver.maxSingleHopDistanceMeters + : null, + ); + const offsetDeg = 0.003; + final angle = (tc.publicKey[1] / 255.0) * 2 * pi; + if (peers.isNotEmpty) { + final lat = + peers.map((c) => c.latitude!).reduce((a, b) => a + b) / peers.length; + final lon = + peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length; + return ( + LatLng(lat + offsetDeg * cos(angle), lon + offsetDeg * sin(angle)), + true, + ); + } + if (inferredPositions.containsKey(lastHopKey)) { + final inferred = inferredPositions[lastHopKey]!; + return ( + LatLng( + inferred.latitude + offsetDeg * cos(angle), + inferred.longitude + offsetDeg * sin(angle), + ), + true, + ); + } + // As a last resort, just place it at the same position as the last hop. + final contact = pathContacts[lastHopKey]; + if (contact != null && contact.hasLocation) { + return ( + LatLng( + contact.latitude! + offsetDeg * cos(angle), + contact.longitude! + offsetDeg * sin(angle), + ), + true, + ); + } + return (null, false); + } + + void _syncPrimaryTraceState({ + required MeshCoreConnector connector, + required PathTraceData traceData, + required List resolvedOutbound, + required List inferredOutbound, + required LatLng? selfPoint, + }) { + final pathContacts = {}; + for (var i = 0; i < _primaryOutboundHops.length; i++) { + final contact = resolvedOutbound[i]; + if (contact != null) { + pathContacts[_hopKey(_primaryOutboundHops[i])] = contact; + } + } + + final inferredPositions = {}; + for (var i = 0; i < _primaryOutboundHops.length; i++) { + final inferred = inferredOutbound[i]; + if (inferred != null) { + inferredPositions[_hopKey(_primaryOutboundHops[i])] = inferred; + } + } + + _inferredHopPositions = inferredPositions; + _traceData = PathTraceData( + pathData: traceData.pathData, + snrData: traceData.snrData, + pathContacts: pathContacts, + ); + + final (targetPos, targetGuessed) = _resolveTargetContactPosition( + connector: connector, + pathData: traceData.pathData, + outboundHops: _primaryOutboundHops, + resolvedOutbound: resolvedOutbound, + inferredOutbound: inferredOutbound, + pathContacts: pathContacts, + inferredPositions: inferredPositions, + selfPoint: selfPoint, + ); + _targetContactPosition = targetPos; + _targetContactIsGuessed = targetGuessed; + + final points = [?selfPoint]; + String hopLast = ''; + String hopLastLast = ''; + for (final hop in traceData.pathData) { + final hopKey = _hopKey(hop); + if (hopKey == hopLastLast && widget.flipPathAround) { + break; //skip duplicate hops in round-trip paths + } + final contact = pathContacts[hopKey]; + if (contact != null && contact.hasLocation) { + points.add(LatLng(contact.latitude!, contact.longitude!)); + } else { + final inferred = inferredPositions[hopKey]; + if (inferred != null) points.add(inferred); + } + hopLastLast = hopLast; + hopLast = hopKey; + } + if (targetPos != null && + _targetContact != null && + _targetContact!.type == advTypeChat) { + points.add(targetPos); + } + + _points = points; + _polylines = points.length > 1 + ? [Polyline(points: points, strokeWidth: 4, color: kPrimaryPathColor)] + : []; + _initialCenter = points.isNotEmpty ? points.first : const LatLng(0, 0); + _initialZoom = points.isNotEmpty ? 13.0 : 2.0; + _bounds = points.length > 1 ? LatLngBounds.fromPoints(points) : null; + _pathDistanceMeters = getPathDistanceMeters(points); } LatLng? _contactLatLng(Contact? contact) { @@ -973,28 +955,35 @@ class _PathTraceMapScreenState extends State /// Rebuilds the renderable paths: the traced path as primary plus up to /// four distinct alternates from the target contact's path history. - void _rebuildDisplayPaths( - MeshCoreConnector connector, { - List? primaryResolved, - List? primaryInferred, - }) { + void _rebuildDisplayPaths(MeshCoreConnector connector) { final selfPoint = plausibleSelfPoint(connector); final paths = []; final resolvedMap = contacts, List inferred})>{}; - final resolvedPrimary = - primaryResolved ?? - [ - for (final hop in _primaryOutboundHops) - _traceData?.pathContacts[_hopKey(hop)], - ]; - final inferredPrimary = - primaryInferred ?? - [ - for (final hop in _primaryOutboundHops) - _inferredHopPositions[_hopKey(hop)], - ]; + final resolvedPrimary = PathHopResolver.resolveHops( + hops: _primaryOutboundHops, + preferredContacts: widget.pathContacts, + contacts: connector.allContactsUnfiltered, + endpoint: selfPoint, + contactFilter: (c) => c.type != advTypeChat, + ); + final inferredPrimary = _inferHopPositions( + hops: _primaryOutboundHops, + resolvedContacts: resolvedPrimary, + selfPoint: selfPoint, + peerContacts: connector.contacts, + ); + final traceData = _traceData; + if (traceData != null) { + _syncPrimaryTraceState( + connector: connector, + traceData: traceData, + resolvedOutbound: resolvedPrimary, + inferredOutbound: inferredPrimary, + selfPoint: selfPoint, + ); + } resolvedMap['primary'] = ( contacts: resolvedPrimary, inferred: inferredPrimary, diff --git a/test/helpers/path_hop_resolver_test.dart b/test/helpers/path_hop_resolver_test.dart index ebcbcb35..c3c230c5 100644 --- a/test/helpers/path_hop_resolver_test.dart +++ b/test/helpers/path_hop_resolver_test.dart @@ -346,4 +346,84 @@ void main() { expect(resolved.map((c) => c?.name), ['Local 2-byte', null]); }); + + test( + 'preferredContacts overrides nearer general contact with same prefix when plausible', + () { + const self = LatLng(33.4484, -112.0740); + final nearerGeneral = _contact( + prefix: 0x48, + secondByte: 0x01, + name: 'Nearer General 48', + latitude: 33.4600, + longitude: -112.0700, + lastSeen: DateTime.utc(2026, 6), + ); + final selectedPreferred = _contact( + prefix: 0x48, + secondByte: 0x02, + name: 'Selected Preferred 48', + latitude: 33.9000, + longitude: -111.7000, + lastSeen: DateTime.utc(2026, 1), + ); + final secondHopGeneral = _contact( + prefix: 0x53, + name: 'Second Hop 53', + latitude: 33.9500, + longitude: -111.6500, + ); + + final resolvedWithEndpoint = PathHopResolver.resolve( + pathBytes: const [0x48, 0x53], + contacts: [nearerGeneral, selectedPreferred, secondHopGeneral], + preferredContacts: [selectedPreferred], + endpoint: self, + ); + expect(resolvedWithEndpoint.map((c) => c?.name), [ + 'Selected Preferred 48', + 'Second Hop 53', + ]); + + final resolvedWithoutEndpoint = PathHopResolver.resolve( + pathBytes: const [0x48, 0x53], + contacts: [nearerGeneral, selectedPreferred, secondHopGeneral], + preferredContacts: [selectedPreferred], + endpoint: null, + ); + expect(resolvedWithoutEndpoint.map((c) => c?.name), [ + 'Selected Preferred 48', + 'Second Hop 53', + ]); + }, + ); + + test( + 'impossibly far preferredContact is rejected and falls back to plausible general contact', + () { + const self = LatLng(33.4484, -112.0740); + final bogusPreferred = _contact( + prefix: 0x9C, + secondByte: 0x01, + name: 'East Coast Preferred 9C', + latitude: 42.3601, + longitude: -71.0589, + ); + final localGeneral = _contact( + prefix: 0x9C, + secondByte: 0x02, + name: 'Local General 9C', + latitude: 33.60097, + longitude: -112.02457, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C], + contacts: [bogusPreferred, localGeneral], + preferredContacts: [bogusPreferred], + endpoint: self, + ); + expect(resolved.map((c) => c?.name), ['Local General 9C']); + }, + ); } diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart index 825c76d2..32c3fe9a 100644 --- a/test/screens/path_trace_test.dart +++ b/test/screens/path_trace_test.dart @@ -1,8 +1,11 @@ import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:latlong2/latlong.dart'; import 'package:provider/provider.dart'; + import 'dart:typed_data'; import 'package:meshcore_open/connector/meshcore_connector.dart'; @@ -40,6 +43,9 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { Uint8List? get selfPublicKey => Uint8List.fromList(List.generate(32, (i) => i)); + @override + bool get isConnected => _isConnected; + @override double? get selfLatitude => _selfLat; @@ -52,21 +58,44 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { @override List get contacts => _peerContacts; - final double? _selfLat; - final double? _selfLon; + final bool _isConnected; + double? _selfLat; + double? _selfLon; + double? _pendingLat; + double? _pendingLon; final List _allContacts; final List _peerContacts; _FakeMeshCoreConnector({ + bool isConnected = false, double? selfLat = 48.8566, double? selfLon = 2.3522, List allContacts = const [], List peerContacts = const [], - }) : _selfLat = selfLat, + }) : _isConnected = isConnected, + _selfLat = selfLat, _selfLon = selfLon, _allContacts = allContacts, _peerContacts = peerContacts; + @override + Future setNodeLocation({ + required double lat, + required double lon, + }) async { + _pendingLat = lat; + _pendingLon = lon; + } + + @override + Future refreshDeviceInfo() async { + if (_pendingLat != null && _pendingLon != null) { + _selfLat = _pendingLat; + _selfLon = _pendingLon; + notifyListeners(); + } + } + void emitFrame(Uint8List frame) { _receivedFramesController.add(frame); } @@ -582,4 +611,216 @@ void main() { } }, ); + + testWidgets( + 'PathTraceMapScreen preserves plausible explicit pathContacts over nearer contact with same prefix', + (tester) async { + final nearerCollision = Contact( + publicKey: Uint8List(32) + ..[0] = 0x48 + ..[1] = 0x01, + name: 'Nearer 48', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.4600, + longitude: -112.0700, + lastSeen: DateTime.utc(2026, 6), + ); + final selectedExplicit = Contact( + publicKey: Uint8List(32) + ..[0] = 0x48 + ..[1] = 0x02, + name: 'Selected 48', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.9000, + longitude: -111.7000, + lastSeen: DateTime.utc(2026, 1), + ); + final fallbackHop2 = Contact( + publicKey: Uint8List(32)..first = 0x53, + name: 'Fallback 53', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.9500, + longitude: -111.6500, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + selfLat: 33.4484, + selfLon: -112.0740, + allContacts: [nearerCollision, selectedExplicit, fallbackHop2], + ); + + final screen = PathTraceMapScreen( + title: 'Explicit Contact Priority', + path: Uint8List.fromList([0x48, 0x53]), + pathHashByteWidth: 1, + pathContacts: [selectedExplicit], + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + final sentFrame = connector.sentFrames.first; + final tag = sentFrame.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x53]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Selected 48'), findsWidgets); + expect(find.textContaining('Fallback 53'), findsWidgets); + expect(find.textContaining('Nearer 48'), findsNothing); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 3); + expect(allPoints[1].latitude, closeTo(33.9000, 1e-4)); + expect(allPoints[1].longitude, closeTo(-111.7000, 1e-4)); + expect(allPoints[2].latitude, closeTo(33.9500, 1e-4)); + expect(allPoints[2].longitude, closeTo(-111.6500, 1e-4)); + }, + ); + + testWidgets( + 'PathTraceMapScreen re-resolves primary hops when self location changes via _setMyLocation', + (tester) async { + final localHop1 = Contact( + publicKey: Uint8List(32)..first = 0x48, + name: 'Phoenix Hop 1', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.60097, + longitude: -112.02457, + lastSeen: DateTime.utc(2026), + ); + final localHop2 = Contact( + publicKey: Uint8List(32)..first = 0x53, + name: 'Phoenix Hop 2', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.46300, + longitude: -111.65000, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + isConnected: true, + // Incorrect initial self location on the East Coast causes local hops to be rejected. + selfLat: 42.3601, + selfLon: -71.0589, + allContacts: [localHop1, localHop2], + ); + + final screen = PathTraceMapScreen( + title: 'Relocate Self Trace', + path: Uint8List.fromList([0x48, 0x53]), + pathHashByteWidth: 1, + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final tag = connector.sentFrames.first.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x53]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + // Initially, both Phoenix hops are rejected as impossibly far from Boston. + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Phoenix Hop 1'), findsNothing); + expect(find.textContaining('Phoenix Hop 2'), findsNothing); + expect(find.textContaining('48: Unknown Repeater'), findsWidgets); + expect(find.textContaining('53: Unknown Repeater'), findsWidgets); + + await tester.tap(find.byIcon(Icons.close_fullscreen)); + await tester.pumpAndSettle(); + + expect(find.byType(PolylineLayer), findsNothing); + + // Update self location to Phoenix via the map's long-press action. + final flutterMap = tester.widget(find.byType(FlutterMap)); + flutterMap.options.onLongPress!( + const TapPosition(Offset.zero, Offset.zero), + const LatLng(33.4484, -112.0740), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Set location')); + await tester.pumpAndSettle(); + + // Primary hops must now be resolved without waiting for another trace packet. + expect(connector.sentFrames.length, 1); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 3); + expect(allPoints[0].latitude, closeTo(33.4484, 1e-4)); + expect(allPoints[0].longitude, closeTo(-112.0740, 1e-4)); + expect(allPoints[1].latitude, closeTo(33.60097, 1e-4)); + expect(allPoints[1].longitude, closeTo(-112.02457, 1e-4)); + expect(allPoints[2].latitude, closeTo(33.46300, 1e-4)); + expect(allPoints[2].longitude, closeTo(-111.65000, 1e-4)); + + final markerLayer = tester.widget( + find.byType(MarkerLayer).first, + ); + expect(markerLayer.markers.length, greaterThanOrEqualTo(3)); + for (final marker in markerLayer.markers) { + expect(marker.point.latitude, inInclusiveRange(33.0, 34.0)); + expect(marker.point.longitude, inInclusiveRange(-113.0, -111.0)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Phoenix Hop 1'), findsWidgets); + expect(find.textContaining('Phoenix Hop 2'), findsWidgets); + expect(find.textContaining('Unknown Repeater'), findsNothing); + }, + ); } From f45b511bcb033c8acc5a92b5137c4f803205f0e5 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:03:18 -0700 Subject: [PATCH 34/50] Add dedicated Add Contact page with manual public key entry Replace the Contacts add-contact modal sheet and separate menu shortcuts with a unified Add Contact screen supporting manual type/name/public-key entry, clipboard import (meshcore:// URIs, share tokens, and bare 64-hex keys), discovered contacts, and QR scanning. --- documentation/contacts.md | 15 +- documentation/navigation.md | 1 + lib/helpers/contact_clipboard.dart | 57 +++ lib/l10n/app_en.arb | 13 +- lib/l10n/app_localizations.dart | 66 +++ lib/l10n/app_localizations_bg.dart | 36 ++ lib/l10n/app_localizations_cs.dart | 36 ++ lib/l10n/app_localizations_de.dart | 36 ++ lib/l10n/app_localizations_en.dart | 36 ++ lib/l10n/app_localizations_es.dart | 36 ++ lib/l10n/app_localizations_fr.dart | 36 ++ lib/l10n/app_localizations_hu.dart | 36 ++ lib/l10n/app_localizations_it.dart | 36 ++ lib/l10n/app_localizations_ja.dart | 36 ++ lib/l10n/app_localizations_ko.dart | 36 ++ lib/l10n/app_localizations_nl.dart | 36 ++ lib/l10n/app_localizations_pl.dart | 36 ++ lib/l10n/app_localizations_pt.dart | 36 ++ lib/l10n/app_localizations_ru.dart | 36 ++ lib/l10n/app_localizations_sk.dart | 36 ++ lib/l10n/app_localizations_sl.dart | 36 ++ lib/l10n/app_localizations_sv.dart | 36 ++ lib/l10n/app_localizations_uk.dart | 36 ++ lib/l10n/app_localizations_zh.dart | 36 ++ lib/review_mode/review_frames.dart | 5 +- lib/review_mode/review_radio.dart | 62 +++ lib/screens/add_contact_screen.dart | 493 +++++++++++++++++++ lib/screens/contact_qr_scanner_screen.dart | 2 +- lib/screens/contacts_screen.dart | 173 +------ lib/utils/contact_qr.dart | 22 + test/screens/add_contact_screen_test.dart | 546 +++++++++++++++++++++ test/screens/offline_mode_test.dart | 2 +- test/screens/small_screen_layout_test.dart | 6 +- test/utils/contact_clipboard_test.dart | 109 ++++ untranslated.json | 247 +++++++++- 35 files changed, 2315 insertions(+), 188 deletions(-) create mode 100644 lib/helpers/contact_clipboard.dart create mode 100644 lib/screens/add_contact_screen.dart create mode 100644 test/screens/add_contact_screen_test.dart create mode 100644 test/utils/contact_clipboard_test.dart diff --git a/documentation/contacts.md b/documentation/contacts.md index fba26ed9..fca46da9 100644 --- a/documentation/contacts.md +++ b/documentation/contacts.md @@ -89,8 +89,8 @@ Groups are stored per radio identity (scoped by public key). The Contacts screen has a single **three-dot overflow menu** (`⋮`) in the app bar: +- Add Contact — opens the Add Contact page - Discovered Contacts — opens the DiscoveryScreen -- Add Contact from Clipboard — reads a `meshcore://` URI from clipboard and imports it - *(divider)* - Zero-Hop Advert — broadcasts your advertisement to immediately adjacent nodes - Flood Advert — broadcasts across the full mesh network @@ -99,15 +99,20 @@ The Contacts screen has a single **three-dot overflow menu** (`⋮`) in the app - Disconnect — disconnects from the device - Settings — opens the Settings screen -A **floating action button** (person-add icon) provides a shortcut sheet to "Add Contact from Clipboard" or "Discovered Contacts". +A **floating action button** (person-add icon) also opens the Add Contact page. ## Adding Contacts ### Automatic (Passive) When the radio hears an advertisement, the contact appears automatically if auto-add is enabled for that type (configurable in Settings → Contact Settings). -### Import from Clipboard -Overflow menu (or the FAB shortcut) → "Add Contact from Clipboard". Reads a `meshcore://` URI from clipboard and imports it to the device. +### Add Contact Page (Manual, Clipboard, Discovered, QR) +Open **Add Contact** from the Contacts overflow menu or the person-add floating action button. + +- **Manual entry**: Pick the **Contact Type** (Chat, Repeater, Room, or Sensor), enter a **Name**, paste or enter the 64-character hex **Public Key** (leading/trailing whitespace and an optional `0x` prefix are handled automatically), and tap the checkmark (`✓`) to save. +- **Add Contact from Clipboard**: Imports `meshcore://` contact URIs and `` chat share tokens directly, or detects a bare 64-hex-char public key and fills the Public Key field so you can pick the type, enter a name, and save. +- **Add from Discovered Contacts**: Opens the Discovered Contacts screen. +- **Scan QR Code**: Opens the QR scanner. ### Import from Discovered Contacts Overflow menu → "Discovered Contacts". Shows nodes heard passively that haven't been added yet. Tap to immediately import (no confirmation dialog), or long-press for more options (Copy URI, Delete). The Discovery screen has its own search bar, type filters (Users, Repeaters, Rooms), and sort options (Last Seen, A-Z). Its overflow menu has **Export discovered contacts**, **Import discovered contacts**, and "Delete All". @@ -131,7 +136,7 @@ Use the Discovered Contacts overflow menu to move the list of heard-but-not-adde ### Import from a QR Code -Choose **Scan QR Code** from the Contacts overflow menu or the add-contact sheet. Allow camera access and scan a compatible contact QR code, or use **Scan QR from Gallery** on the scanner screen to import a QR code from a saved image. Contact QR import is separate from community QR scanning; use Channels for community codes. +Choose **Scan QR Code** from the Add Contact page. Allow camera access and scan a compatible contact QR code, or use **Scan QR from Gallery** on the scanner screen to import a QR code from a saved image. Contact QR import is separate from community QR scanning; use Channels for community codes. ## Contact Sharing Format diff --git a/documentation/navigation.md b/documentation/navigation.md index 6cb0860e..6da2aac3 100644 --- a/documentation/navigation.md +++ b/documentation/navigation.md @@ -48,6 +48,7 @@ ContactsScreen (selected=0) ├─ [quick-switch 1] → pushReplacement → ChannelsScreen ├─ [quick-switch 2] → pushReplacement → MapScreen ├─ [tap contact] → push → ChatScreen + ├─ [FAB / overflow > Add Contact] → push → AddContactScreen ├─ [overflow > Settings] → push → SettingsScreen └─ [overflow > Discovered] → push → DiscoveryScreen diff --git a/lib/helpers/contact_clipboard.dart b/lib/helpers/contact_clipboard.dart new file mode 100644 index 00000000..4352bffb --- /dev/null +++ b/lib/helpers/contact_clipboard.dart @@ -0,0 +1,57 @@ +import '../helpers/contact_share_message.dart'; +import '../utils/contact_qr.dart'; + +/// Kind of content found when parsing clipboard text for adding a contact. +enum ContactClipboardKind { empty, contact, publicKey, invalid } + +/// Result of parsing clipboard text on the Add Contact screen. +class ContactClipboardParseResult { + final ContactClipboardKind kind; + final ScannedContact? contact; + final String? publicKeyHex; + + const ContactClipboardParseResult._( + this.kind, { + this.contact, + this.publicKeyHex, + }); + + const ContactClipboardParseResult.empty() + : this._(ContactClipboardKind.empty); + + const ContactClipboardParseResult.contact(ScannedContact contact) + : this._(ContactClipboardKind.contact, contact: contact); + + const ContactClipboardParseResult.publicKey(String publicKeyHex) + : this._(ContactClipboardKind.publicKey, publicKeyHex: publicKeyHex); + + const ContactClipboardParseResult.invalid() + : this._(ContactClipboardKind.invalid); +} + +/// Parses clipboard text as a `meshcore://` contact URI/advert, an embedded +/// `` contact share, or a bare 64-hex-char public key. +ContactClipboardParseResult parseContactClipboard(String? rawText) { + if (rawText == null) return const ContactClipboardParseResult.empty(); + final trimmed = rawText.trim(); + if (trimmed.isEmpty) return const ContactClipboardParseResult.empty(); + + if (trimmed.toLowerCase().startsWith('meshcore://')) { + final scanned = parseContactQr(trimmed); + return scanned != null + ? ContactClipboardParseResult.contact(scanned) + : const ContactClipboardParseResult.invalid(); + } + + final share = findContactShare(trimmed); + if (share != null) { + return ContactClipboardParseResult.contact(share.toScannedContact()); + } + + final normalizedKey = normalizeContactPublicKeyHex(trimmed); + if (normalizedKey != null) { + return ContactClipboardParseResult.publicKey(normalizedKey); + } + + return const ContactClipboardParseResult.invalid(); +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 0b88cf32..da370791 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -4423,5 +4423,16 @@ "chatCompression_profile": "Cyr2Lat profile", "chatCompression_noStorageId": "Can't change compression until this channel has synced from the radio.", "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting.", - "messageMeta_smazCompressed": "SMAZ compressed" + "messageMeta_smazCompressed": "SMAZ compressed", + "addContact_title": "Add Contact", + "addContact_infoBanner": "If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.", + "addContact_contactType": "Contact Type", + "addContact_name": "Name", + "addContact_nameRequired": "Please enter a name", + "addContact_publicKeyHex": "Public Key (hex)", + "addContact_publicKeyRequired": "Please enter a public key", + "addContact_publicKeyInvalid": "Public key must be 64 hex characters (32 bytes)", + "addContact_clipboardKeyLoaded": "Public key filled in. Choose a contact type, enter a name, and tap save.", + "addContact_fromDiscovered": "Add from Discovered Contacts", + "addContact_saveFailed": "Failed to add contact." } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 866c4d75..dca511d2 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -12867,6 +12867,72 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'SMAZ compressed'** String get messageMeta_smazCompressed; + + /// No description provided for @addContact_title. + /// + /// In en, this message translates to: + /// **'Add Contact'** + String get addContact_title; + + /// No description provided for @addContact_infoBanner. + /// + /// In en, this message translates to: + /// **'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'** + String get addContact_infoBanner; + + /// No description provided for @addContact_contactType. + /// + /// In en, this message translates to: + /// **'Contact Type'** + String get addContact_contactType; + + /// No description provided for @addContact_name. + /// + /// In en, this message translates to: + /// **'Name'** + String get addContact_name; + + /// No description provided for @addContact_nameRequired. + /// + /// In en, this message translates to: + /// **'Please enter a name'** + String get addContact_nameRequired; + + /// No description provided for @addContact_publicKeyHex. + /// + /// In en, this message translates to: + /// **'Public Key (hex)'** + String get addContact_publicKeyHex; + + /// No description provided for @addContact_publicKeyRequired. + /// + /// In en, this message translates to: + /// **'Please enter a public key'** + String get addContact_publicKeyRequired; + + /// No description provided for @addContact_publicKeyInvalid. + /// + /// In en, this message translates to: + /// **'Public key must be 64 hex characters (32 bytes)'** + String get addContact_publicKeyInvalid; + + /// No description provided for @addContact_clipboardKeyLoaded. + /// + /// In en, this message translates to: + /// **'Public key filled in. Choose a contact type, enter a name, and tap save.'** + String get addContact_clipboardKeyLoaded; + + /// No description provided for @addContact_fromDiscovered. + /// + /// In en, this message translates to: + /// **'Add from Discovered Contacts'** + String get addContact_fromDiscovered; + + /// No description provided for @addContact_saveFailed. + /// + /// In en, this message translates to: + /// **'Failed to add contact.'** + String get addContact_saveFailed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 7708cac7..9e1c6ef7 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -7726,4 +7726,40 @@ class AppLocalizationsBg extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 59cb10c7..56f031be 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -7697,4 +7697,40 @@ class AppLocalizationsCs extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index af53e427..abd76619 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -7740,4 +7740,40 @@ class AppLocalizationsDe extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 5bf8d16d..c9e4ff4b 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -7611,4 +7611,40 @@ class AppLocalizationsEn extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index ba8a796a..44d52623 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -7718,4 +7718,40 @@ class AppLocalizationsEs extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e8ffe95..591cd2ea 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -7746,4 +7746,40 @@ class AppLocalizationsFr extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index ae295359..b3995712 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -7709,4 +7709,40 @@ class AppLocalizationsHu extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 0343fc66..a4deb61e 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -7729,4 +7729,40 @@ class AppLocalizationsIt extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 9fd9ed1b..1304daee 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -7371,4 +7371,40 @@ class AppLocalizationsJa extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 9225c2e5..12214a08 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -7383,4 +7383,40 @@ class AppLocalizationsKo extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 8e29b175..4bb16a1e 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -7685,4 +7685,40 @@ class AppLocalizationsNl extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 6aad82bd..e014c568 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -7763,4 +7763,40 @@ class AppLocalizationsPl extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 2104daf9..7314687c 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -7707,6 +7707,42 @@ class AppLocalizationsPt extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index bd86537e..4f11bafc 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -7743,4 +7743,40 @@ class AppLocalizationsRu extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 1601d2d1..728f0b17 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -7708,4 +7708,40 @@ class AppLocalizationsSk extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index d8a6f87e..28a8ce98 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -7702,4 +7702,40 @@ class AppLocalizationsSl extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1dfc2df1..d570f059 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -7662,4 +7662,40 @@ class AppLocalizationsSv extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 22999628..bb609f3b 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -7755,4 +7755,40 @@ class AppLocalizationsUk extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 16432461..4d31b395 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -7213,4 +7213,40 @@ class AppLocalizationsZh extends AppLocalizations { @override String get messageMeta_smazCompressed => 'SMAZ compressed'; + + @override + String get addContact_title => 'Add Contact'; + + @override + String get addContact_infoBanner => + 'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'; + + @override + String get addContact_contactType => 'Contact Type'; + + @override + String get addContact_name => 'Name'; + + @override + String get addContact_nameRequired => 'Please enter a name'; + + @override + String get addContact_publicKeyHex => 'Public Key (hex)'; + + @override + String get addContact_publicKeyRequired => 'Please enter a public key'; + + @override + String get addContact_publicKeyInvalid => + 'Public key must be 64 hex characters (32 bytes)'; + + @override + String get addContact_clipboardKeyLoaded => + 'Public key filled in. Choose a contact type, enter a name, and tap save.'; + + @override + String get addContact_fromDiscovered => 'Add from Discovered Contacts'; + + @override + String get addContact_saveFailed => 'Failed to add contact.'; } diff --git a/lib/review_mode/review_frames.dart b/lib/review_mode/review_frames.dart index 8427e23c..bae8134f 100644 --- a/lib/review_mode/review_frames.dart +++ b/lib/review_mode/review_frames.dart @@ -84,6 +84,7 @@ class ReviewFrames { required Uint8List publicKey, required int type, required Uint8List path, + int? pathLen, required String name, required int lastAdvertSecs, required int latitudeE6, @@ -96,7 +97,9 @@ class ReviewFrames { writer.writeBytes(publicKey); writer.writeByte(type); writer.writeByte(flags); - writer.writeByte(path.length); // one-byte hashes: hop count == byte count + writer.writeByte( + pathLen ?? path.length, + ); // one-byte hashes: hop count == byte count writer.writeBytesPadded(path, maxPathSize); writer.writeCString(name, maxNameSize); writer.writeUInt32LE(lastAdvertSecs); diff --git a/lib/review_mode/review_radio.dart b/lib/review_mode/review_radio.dart index 79eb36df..91abe8a6 100644 --- a/lib/review_mode/review_radio.dart +++ b/lib/review_mode/review_radio.dart @@ -318,6 +318,9 @@ class ReviewRadio { } _emit([ReviewFrames.ok()]); break; + case cmdAddUpdateContact: + _handleAddUpdateContact(frame); + break; case cmdSendLogin: _handleLogin(frame); break; @@ -365,13 +368,68 @@ class ReviewRadio { publicKey: c.publicKey, type: c.type, path: c.path, + pathLen: c.pathLen, name: c.name, lastAdvertSecs: c.lastAdvertSecs, latitudeE6: c.latitudeE6, longitudeE6: c.longitudeE6, lastModSecs: c.lastModSecs, + flags: c.flags, ); + void _handleAddUpdateContact(Uint8List frame) { + // [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert? x4][lat? x4][lon? x4] + const minLen = 1 + pubKeySize + 3 + maxPathSize + maxNameSize; + if (frame.length < minLen) { + _emit([ReviewFrames.err()]); + return; + } + final publicKey = Uint8List.fromList(frame.sublist(1, 1 + pubKeySize)); + final type = frame[33]; + final flags = frame[34]; + final pathLen = frame[35]; + final Uint8List path; + if (pathLen == 0xFF) { + path = Uint8List(0); + } else { + final width = ((pathLen & 0xC0) >> 6) + 1; + final hops = pathLen & 0x3F; + final byteLen = (hops * width).clamp(0, maxPathSize); + path = Uint8List.fromList(frame.sublist(36, 36 + byteLen)); + } + final name = _readCString(frame, 36 + maxPathSize, maxNameSize); + final lastAdvertSecs = frame.length >= minLen + 4 + ? readUint32LE(frame, minLen) + : 0; + final latE6 = frame.length >= minLen + 12 + ? readInt32LE(frame, minLen + 4) + : 0; + final lonE6 = frame.length >= minLen + 12 + ? readInt32LE(frame, minLen + 8) + : 0; + final contact = _Contact( + publicKey: publicKey, + type: type, + flags: flags, + path: path, + pathLen: pathLen, + name: name, + lastAdvertSecs: lastAdvertSecs, + latitudeE6: latE6, + longitudeE6: lonE6, + lastModSecs: _nowSecs, + ); + final index = _contacts.indexWhere( + (c) => listEquals(c.publicKey, publicKey), + ); + if (index >= 0) { + _contacts[index] = contact; + } else { + _contacts.add(contact); + } + _emit([ReviewFrames.ok()]); + } + void _handleGetContacts(Uint8List frame) { final since = frame.length >= 5 ? readUint32LE(frame, 1) : 0; final matching = _contacts.where((c) => c.lastModSecs > since).toList(); @@ -659,7 +717,9 @@ class ReviewRadio { class _Contact { final Uint8List publicKey; final int type; + final int flags; final Uint8List path; + final int? pathLen; final String name; final int lastAdvertSecs; final int latitudeE6; @@ -669,7 +729,9 @@ class _Contact { _Contact({ required this.publicKey, required this.type, + this.flags = 0, required this.path, + this.pathLen, required this.name, required this.lastAdvertSecs, required this.latitudeE6, diff --git a/lib/screens/add_contact_screen.dart b/lib/screens/add_contact_screen.dart new file mode 100644 index 00000000..353d9ab7 --- /dev/null +++ b/lib/screens/add_contact_screen.dart @@ -0,0 +1,493 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/contact_clipboard.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../helpers/utf8_length_limiter.dart'; +import '../l10n/app_localizations.dart'; +import '../l10n/l10n.dart'; +import '../theme/mesh_theme.dart'; +import '../utils/app_logger.dart'; +import '../utils/contact_qr.dart'; +import '../utils/radio_guard.dart'; +import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/mesh_nav_tile.dart'; +import '../widgets/mesh_ui.dart'; +import 'contact_qr_scanner_screen.dart'; +import 'discovery_screen.dart'; + +/// Unified page for adding a contact manually by public key, from clipboard, +/// from discovered contacts, or by scanning a QR code. +class AddContactScreen extends StatefulWidget { + const AddContactScreen({super.key}); + + @override + State createState() => _AddContactScreenState(); +} + +class _AddContactScreenState extends State { + final _formKey = GlobalKey(); + final _publicKeyFieldKey = GlobalKey>(); + final _nameController = TextEditingController(); + final _publicKeyController = TextEditingController(); + final _nameFocusNode = FocusNode(); + final _publicKeyFocusNode = FocusNode(); + + int _selectedType = advTypeChat; + bool _isSaving = false; + bool _isImporting = false; + + bool get _isBusy => _isSaving || _isImporting; + + static const List _contactTypes = [ + advTypeChat, + advTypeRepeater, + advTypeRoom, + advTypeSensor, + ]; + + @override + void dispose() { + _nameController.dispose(); + _publicKeyController.dispose(); + _nameFocusNode.dispose(); + _publicKeyFocusNode.dispose(); + super.dispose(); + } + + String _typeLabel(AppLocalizations l10n, int type) { + switch (type) { + case advTypeChat: + return l10n.contact_typeChat; + case advTypeRepeater: + return l10n.contact_typeRepeater; + case advTypeRoom: + return l10n.contact_typeRoom; + case advTypeSensor: + return l10n.contact_typeSensor; + default: + return l10n.contact_typeUnknown; + } + } + + Future _pickContactType() async { + final chosen = await showMeshSheet( + context, + builder: (sheetContext) { + final l10n = sheetContext.l10n; + return SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader(title: l10n.addContact_contactType), + for (final type in _contactTypes) + MeshSheetOption( + label: _typeLabel(l10n, type), + selected: type == _selectedType, + onTap: () => Navigator.pop(sheetContext, type), + ), + const SizedBox(height: 8), + ], + ), + ), + ); + }, + ); + if (!mounted || chosen == null) return; + setState(() => _selectedType = chosen); + } + + Future _saveContact() async { + if (_isBusy) return; + if (!(_formKey.currentState?.validate() ?? false)) return; + if (!ensureRadioConnected(context)) return; + + final keyHex = normalizeContactPublicKeyHex(_publicKeyController.text); + final publicKeyBytes = decodeContactPublicKeyHex(_publicKeyController.text); + if (keyHex == null || publicKeyBytes == null) return; + + final connector = context.read(); + if (connector.selfPublicKeyHex.isNotEmpty && + keyHex == connector.selfPublicKeyHex.toLowerCase()) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contactShare_isYou), + ); + return; + } + + setState(() => _isSaving = true); + try { + await connector.addContactFromCard( + ScannedContact( + publicKey: publicKeyBytes, + name: _nameController.text.trim(), + type: _selectedType, + ), + ); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.discoveredContacts_contactAdded), + ); + Navigator.pop(context, true); + } catch (e) { + appLogger.warn('Manual contact add failed: $e', tag: 'AddContactScreen'); + if (!mounted) return; + setState(() => _isSaving = false); + showDismissibleSnackBar( + context, + content: Text(context.l10n.addContact_saveFailed), + ); + } + } + + Future _importFromClipboard() async { + if (_isBusy) return; + final clipboardData = await Clipboard.getData('text/plain'); + if (!mounted) return; + + final parsed = parseContactClipboard(clipboardData?.text); + switch (parsed.kind) { + case ContactClipboardKind.empty: + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_clipboardEmpty), + ); + return; + case ContactClipboardKind.invalid: + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_invalidAdvertFormat), + ); + return; + case ContactClipboardKind.publicKey: + _publicKeyController.text = parsed.publicKeyHex!; + if (_publicKeyFieldKey.currentState?.hasError == true) { + _publicKeyFieldKey.currentState?.validate(); + } + _nameFocusNode.requestFocus(); + showDismissibleSnackBar( + context, + content: Text(context.l10n.addContact_clipboardKeyLoaded), + ); + return; + case ContactClipboardKind.contact: + if (!ensureRadioConnected(context)) return; + final scanned = parsed.contact!; + final connector = context.read(); + if (scanned.publicKey != null && + connector.selfPublicKeyHex.isNotEmpty && + pubKeyToHex(scanned.publicKey!).toLowerCase() == + connector.selfPublicKeyHex.toLowerCase()) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contactShare_isYou), + ); + return; + } + setState(() => _isImporting = true); + try { + await connector.addContactFromCard(scanned); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_contactImported), + ); + Navigator.pop(context, true); + } catch (e) { + appLogger.warn( + 'Clipboard contact import failed: $e', + tag: 'AddContactScreen', + ); + if (!mounted) return; + setState(() => _isImporting = false); + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_contactImportFailed), + ); + } + return; + } + } + + void _openDiscoveredContacts() { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => const DiscoveryScreen()), + ); + } + + Future _scanQrCode() async { + if (!ensureRadioConnected(context)) return; + final imported = await Navigator.push( + context, + MaterialPageRoute(builder: (_) => const ContactQrScannerScreen()), + ); + if (imported == true && mounted) { + Navigator.pop(context, true); + } + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Scaffold( + appBar: AppBar( + title: AdaptiveAppBarTitle(l10n.addContact_title), + centerTitle: true, + actions: [ + IconButton( + tooltip: l10n.common_save, + onPressed: _isBusy ? null : _saveContact, + icon: _isSaving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.check), + ), + ], + ), + body: SafeArea( + top: false, + child: Form( + key: _formKey, + child: ListView( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 24), + children: [ + MeshCard( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.info_outline, + size: 24, + color: scheme.onSurfaceVariant, + ), + const SizedBox(width: 16), + Expanded( + child: Text( + l10n.addContact_infoBanner, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurface, + ), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + MeshCard( + padding: EdgeInsets.zero, + child: Column( + children: [ + _buildContactTypeRow(context), + const Divider(height: 1, indent: 16), + _buildNameRow(context), + const Divider(height: 1, indent: 16), + _buildPublicKeyRow(context), + ], + ), + ), + const SizedBox(height: 8), + MeshCard( + padding: EdgeInsets.zero, + child: MeshNavTile( + icon: Icons.content_paste, + title: l10n.contacts_addContactFromClipboard, + onTap: _isBusy ? null : _importFromClipboard, + ), + ), + MeshCard( + padding: EdgeInsets.zero, + child: MeshNavTile( + icon: Icons.person_add_rounded, + title: l10n.addContact_fromDiscovered, + onTap: _isBusy ? null : _openDiscoveredContacts, + ), + ), + MeshCard( + padding: EdgeInsets.zero, + child: MeshNavTile( + icon: Icons.qr_code_scanner, + title: l10n.contacts_scanQrCode, + onTap: _isBusy ? null : _scanQrCode, + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildContactTypeRow(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final label = _typeLabel(l10n, _selectedType); + + return Semantics( + button: true, + enabled: !_isBusy, + label: '${l10n.addContact_contactType}: $label', + child: InkWell( + onTap: _isBusy ? null : _pickContactType, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 48), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Icon( + Icons.info_outline, + size: 24, + color: scheme.onSurfaceVariant, + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + l10n.addContact_contactType, + style: theme.textTheme.bodySmall?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 2), + Text(label, style: theme.textTheme.bodyLarge), + ], + ), + ), + const SizedBox(width: 8), + Icon( + Icons.arrow_drop_down, + size: 24, + color: scheme.onSurfaceVariant, + ), + ], + ), + ), + ), + ), + ); + } + + Widget _buildNameRow(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + Icon(Icons.person_outline, size: 24, color: scheme.onSurfaceVariant), + const SizedBox(width: 16), + Expanded( + child: TextFormField( + controller: _nameController, + focusNode: _nameFocusNode, + enabled: !_isBusy, + textInputAction: TextInputAction.next, + onFieldSubmitted: (_) => _publicKeyFocusNode.requestFocus(), + inputFormatters: [ + Utf8LengthLimitingTextInputFormatter(maxRadioNameBytes), + ], + style: theme.textTheme.bodyLarge, + decoration: InputDecoration( + labelText: l10n.addContact_name, + filled: false, + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + errorBorder: InputBorder.none, + focusedErrorBorder: InputBorder.none, + disabledBorder: InputBorder.none, + contentPadding: const EdgeInsets.symmetric(vertical: 12), + errorMaxLines: 4, + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return l10n.addContact_nameRequired; + } + return null; + }, + ), + ), + ], + ), + ); + } + + Widget _buildPublicKeyRow(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + Icon( + Icons.vpn_key_outlined, + size: 24, + color: scheme.onSurfaceVariant, + ), + const SizedBox(width: 16), + Expanded( + child: TextFormField( + key: _publicKeyFieldKey, + controller: _publicKeyController, + focusNode: _publicKeyFocusNode, + enabled: !_isBusy, + autocorrect: false, + enableSuggestions: false, + textInputAction: TextInputAction.done, + onFieldSubmitted: (_) => _saveContact(), + minLines: 1, + maxLines: 3, + style: MeshTheme.mono(fontSize: 15, color: scheme.onSurface), + decoration: InputDecoration( + labelText: l10n.addContact_publicKeyHex, + filled: false, + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + errorBorder: InputBorder.none, + focusedErrorBorder: InputBorder.none, + disabledBorder: InputBorder.none, + contentPadding: const EdgeInsets.symmetric(vertical: 12), + errorMaxLines: 4, + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return l10n.addContact_publicKeyRequired; + } + if (decodeContactPublicKeyHex(value) == null) { + return l10n.addContact_publicKeyInvalid; + } + return null; + }, + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/contact_qr_scanner_screen.dart b/lib/screens/contact_qr_scanner_screen.dart index 722c69ca..6d8db04c 100644 --- a/lib/screens/contact_qr_scanner_screen.dart +++ b/lib/screens/contact_qr_scanner_screen.dart @@ -190,7 +190,7 @@ class _ContactQrScannerScreenState extends State { ); // Keep _isProcessing set: resetting it would restart the camera on a // closing route and let a second detection import and pop again. - Navigator.pop(context); + Navigator.pop(context, true); } catch (e) { if (mounted) { setState(() { diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 6acd9f67..614b60e5 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -34,11 +34,10 @@ import '../widgets/repeater_login_dialog.dart'; import '../widgets/room_login_dialog.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/unread_badge.dart'; -import '../helpers/contact_share_message.dart'; import '../helpers/snack_bar_builder.dart'; +import 'add_contact_screen.dart'; import 'channels_screen.dart'; import 'chat_screen.dart'; -import 'contact_qr_scanner_screen.dart'; import 'discovery_screen.dart'; import 'map_screen.dart'; import '../review_mode/review_mode_banner.dart'; @@ -48,7 +47,7 @@ import '../theme/theme_icons.dart'; enum RoomLoginDestination { chat, management } -enum ContactOperationType { import, export, zeroHopShare } +enum ContactOperationType { export, zeroHopShare } /// An export/import/share awaiting its generic OK/ERR ack. The timer drops /// it if no ack arrives, so a stuck op can't consume a later unrelated ack. @@ -159,10 +158,6 @@ class _ContactsScreenState extends State { final l10n = context.l10n; final String message; switch (type) { - case ContactOperationType.import: - message = success - ? l10n.contacts_contactImported - : l10n.contacts_contactImportFailed; case ContactOperationType.zeroHopShare: message = success ? l10n.contacts_zeroHopContactAdvertSent @@ -345,85 +340,10 @@ class _ContactsScreenState extends State { } } - Future _contactImport() async { - final connector = Provider.of(context, listen: false); - final clipboardData = await Clipboard.getData('text/plain'); - if (clipboardData == null || clipboardData.text == null) { - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_clipboardEmpty), - ); - } - return; - } - final text = clipboardData.text!.trim(); - // A contact shared in chat (``) copied from the bubble. - final share = findContactShare(text); - if (share != null && !text.startsWith('meshcore://')) { - await _importContactShare(connector, share); - return; - } - if (!text.startsWith('meshcore://')) { - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_invalidAdvertFormat), - ); - } - return; - } - final hexString = text.substring('meshcore://'.length); - final Uint8List importContactFrame; - try { - final bytes = hex2Uint8List(hexString); - importContactFrame = buildImportContactFrame(bytes); - } catch (e) { - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_invalidAdvertFormat), - ); - } - return; - } - _addPendingOperation(ContactOperationType.import); - try { - await connector.sendFrame(importContactFrame, expectsGenericAck: true); - } catch (e) { - _takePendingOperation(ContactOperationType.import); - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactImportFailed), - ); - } - } - } - - Future _importContactShare( - MeshCoreConnector connector, - ContactShare share, - ) async { - if (!mounted) return; - final l10n = context.l10n; - if (share.publicKeyHex == connector.selfPublicKeyHex) { - showDismissibleSnackBar(context, content: Text(l10n.contactShare_isYou)); - return; - } - var ok = true; - try { - await connector.addContactFromCard(share.toScannedContact()); - } catch (e) { - appLogger.warn('Contact share import failed: $e', tag: 'ContactsScreen'); - ok = false; - } - if (!mounted) return; - showDismissibleSnackBar( + void _openAddContact() { + Navigator.push( context, - content: Text( - ok ? l10n.contacts_contactImported : l10n.contacts_contactImportFailed, - ), + MaterialPageRoute(builder: (context) => const AddContactScreen()), ); } @@ -444,6 +364,14 @@ class _ContactsScreenState extends State { PopupMenuButton( tooltip: context.l10n.contacts_moreOptions, itemBuilder: (context) => >[ + PopupMenuItem( + enabled: !readOnly, + onTap: _openAddContact, + child: MeshMenuItemRow( + icon: Icons.person_add, + label: context.l10n.addContact_title, + ), + ), PopupMenuItem( child: MeshMenuItemRow( icon: Icons.person_add_rounded, @@ -456,27 +384,6 @@ class _ContactsScreenState extends State { ), ), ), - PopupMenuItem( - enabled: !readOnly, - child: MeshMenuItemRow( - icon: Icons.paste, - label: context.l10n.contacts_addContactFromClipboard, - ), - onTap: () => _contactImport(), - ), - PopupMenuItem( - enabled: !readOnly, - child: MeshMenuItemRow( - icon: Icons.qr_code_scanner, - label: context.l10n.contacts_scanQrCode, - ), - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const ContactQrScannerScreen(), - ), - ), - ), const PopupMenuDivider(), PopupMenuItem( enabled: !readOnly, @@ -538,7 +445,8 @@ class _ContactsScreenState extends State { floatingActionButton: readOnly ? null : FloatingActionButton( - onPressed: () => _showAddContactSheet(context), + tooltip: context.l10n.addContact_title, + onPressed: _openAddContact, child: const Icon(Icons.person_add), ), bottomNavigationBar: SafeArea( @@ -555,57 +463,6 @@ class _ContactsScreenState extends State { ); } - void _showAddContactSheet(BuildContext context) { - showMeshSheet( - context, - builder: (sheetContext) => SafeArea( - child: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader(title: context.l10n.contacts_title), - ListTile( - leading: const Icon(Icons.paste), - title: Text(context.l10n.contacts_addContactFromClipboard), - onTap: () { - Navigator.pop(sheetContext); - _contactImport(); - }, - ), - ListTile( - leading: const Icon(Icons.qr_code_scanner), - title: Text(context.l10n.contacts_scanQrCode), - onTap: () { - Navigator.pop(sheetContext); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const ContactQrScannerScreen(), - ), - ); - }, - ), - ListTile( - leading: const Icon(Icons.person_add_rounded), - title: Text(context.l10n.discoveredContacts_Title), - onTap: () { - Navigator.pop(sheetContext); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const DiscoveryScreen(), - ), - ); - }, - ), - const SizedBox(height: 8), - ], - ), - ), - ), - ); - } - ContactGroup? _selectedGroupForName(String selectedGroupName) { if (selectedGroupName == contactsAllGroupsValue) return null; for (final group in _groups) { diff --git a/lib/utils/contact_qr.dart b/lib/utils/contact_qr.dart index cc789926..f14932f3 100644 --- a/lib/utils/contact_qr.dart +++ b/lib/utils/contact_qr.dart @@ -78,6 +78,28 @@ ScannedContact? _parseContactCard(Uri uri) { return ScannedContact(publicKey: publicKey, name: name, type: type); } +/// Normalizes a 64-character hex public key, trimming surrounding whitespace +/// and stripping an optional `0x` prefix. Returns lowercase hex or null when +/// [input] is not a valid 32-byte hex key. +String? normalizeContactPublicKeyHex(String input) { + var trimmed = input.trim(); + if (trimmed.length >= 2 && + (trimmed.startsWith('0x') || trimmed.startsWith('0X'))) { + trimmed = trimmed.substring(2); + } + if (trimmed.length != _contactCardKeyBytes * 2) return null; + if (_tryHexDecode(trimmed) == null) return null; + return trimmed.toLowerCase(); +} + +/// Decodes a 64-character hex public key (allowing surrounding whitespace, +/// optional `0x` prefix, and mixed case) into 32 bytes, or returns null. +Uint8List? decodeContactPublicKeyHex(String input) { + final normalized = normalizeContactPublicKeyHex(input); + if (normalized == null) return null; + return _tryHexDecode(normalized); +} + /// Local hex decoder: keeps this util pure-Dart. `hex2Uint8List` in /// `connector/meshcore_protocol.dart` throws on invalid input and that file /// pulls in `package:flutter/widgets.dart` and `package:crypto`, which this diff --git a/test/screens/add_contact_screen_test.dart b/test/screens/add_contact_screen_test.dart new file mode 100644 index 00000000..3c8861d9 --- /dev/null +++ b/test/screens/add_contact_screen_test.dart @@ -0,0 +1,546 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/l10n/app_localizations_en.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/add_contact_screen.dart'; +import 'package:meshcore_open/screens/contacts_screen.dart'; +import 'package:meshcore_open/screens/discovery_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; + +final _l10n = AppLocalizationsEn(); + +MeshCoreConnector? _sharedConnector; + +Future _connectedConnector(WidgetTester tester) async { + if (_sharedConnector != null) { + return _sharedConnector!; + } + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(milliseconds: 50), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while (!connector.hasLoadedContacts && DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + _sharedConnector = connector; + return connector; +} + +Widget _wrapApp({ + required MeshCoreConnector connector, + required Widget home, + ThemeData? theme, + Locale locale = const Locale('en'), + double textScale = 1.0, +}) { + final storage = StorageService(); + final settings = AppSettingsService(); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider(create: (_) => MessageRetryService()), + ChangeNotifierProvider(create: (_) => PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider(create: (_) => BleDebugLogService()), + ChangeNotifierProvider(create: (_) => AppDebugLogService()), + ChangeNotifierProvider(create: (_) => ChatTextScaleService()), + ChangeNotifierProvider(create: (_) => TranslationService(settings)), + ChangeNotifierProvider(create: (_) => UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider( + create: (_) => MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider(create: (_) => TimeoutPredictionService(storage)), + ChangeNotifierProvider(create: (_) => ImageCodecService(settings)), + ChangeNotifierProvider(create: (_) => ReceivedImageStore()), + ChangeNotifierProvider( + create: (_) => + NetworkMapUploadService(connector: connector, settings: settings), + ), + ], + child: MaterialApp( + theme: theme ?? MeshTheme.dark(), + locale: locale, + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: home, + ), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('add_contact_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDownAll(() { + _sharedConnector?.dispose(); + _sharedConnector = null; + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + testWidgets('validates empty fields and invalid public key', (tester) async { + final connector = await _connectedConnector(tester); + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const AddContactScreen()), + ); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.addContact_title), findsOneWidget); + expect(find.text(_l10n.addContact_infoBanner), findsOneWidget); + expect(find.text(_l10n.contacts_addContactFromClipboard), findsOneWidget); + expect(find.text(_l10n.addContact_fromDiscovered), findsOneWidget); + expect(find.text(_l10n.contacts_scanQrCode), findsOneWidget); + + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.addContact_nameRequired), findsOneWidget); + expect(find.text(_l10n.addContact_publicKeyRequired), findsOneWidget); + + await tester.enterText(find.byType(TextFormField).first, 'Repeater One'); + await tester.enterText(find.byType(TextFormField).last, 'abcd'); + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.addContact_publicKeyInvalid), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('selects contact type and submits manual contact', ( + tester, + ) async { + final connector = await _connectedConnector(tester); + + final keyHex = List.generate( + 32, + (i) => (i + 1).toRadixString(16).padLeft(2, '0'), + ).join(); + + await tester.pumpWidget( + _wrapApp( + connector: connector, + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: FilledButton( + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const AddContactScreen()), + ), + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + // Change Contact Type from Chat to Repeater. + expect(find.text(_l10n.contact_typeChat), findsOneWidget); + await tester.tap(find.text(_l10n.contact_typeChat)); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.contact_typeRepeater), findsOneWidget); + expect(find.text(_l10n.contact_typeRoom), findsOneWidget); + expect(find.text(_l10n.contact_typeSensor), findsOneWidget); + + await tester.tap(find.text(_l10n.contact_typeRepeater)); + await tester.pumpAndSettle(); + expect(find.text(_l10n.contact_typeRepeater), findsOneWidget); + + await tester.enterText(find.byType(TextFormField).first, ' North Ridge '); + await tester.enterText( + find.byType(TextFormField).last, + ' 0x${keyHex.toUpperCase()} ', + ); + + await tester.runAsync(() async { + await tester.tap(find.byIcon(Icons.check)); + final end = DateTime.now().add(const Duration(seconds: 5)); + while (!connector.contacts.any((c) => c.publicKeyHex == keyHex) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + await tester.pumpAndSettle(); + + final added = connector.contacts.firstWhere( + (c) => c.publicKeyHex == keyHex, + ); + expect(added.name, 'North Ridge'); + expect(added.type, advTypeRepeater); + expect(find.byType(AddContactScreen), findsNothing); + expect(find.text(_l10n.discoveredContacts_contactAdded), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('bare hex key in clipboard fills Public Key and focuses Name', ( + tester, + ) async { + final connector = await _connectedConnector(tester); + + final keyHex = 'ab' * 32; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.getData') { + return {'text': ' 0x${keyHex.toUpperCase()} \n'}; + } + return null; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const AddContactScreen()), + ); + await tester.pumpAndSettle(); + + // Trigger empty validation error first, then ensure pasting a bare key clears it. + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + expect(find.text(_l10n.addContact_publicKeyRequired), findsOneWidget); + + await tester.tap(find.text(_l10n.contacts_addContactFromClipboard)); + await tester.pumpAndSettle(); + + final nameField = tester.widget(find.byType(TextField).first); + final keyField = tester.widget(find.byType(TextField).last); + expect(keyField.controller!.text, keyHex); + expect(nameField.focusNode!.hasFocus, isTrue); + expect(find.text(_l10n.addContact_publicKeyRequired), findsNothing); + expect(find.text(_l10n.addContact_clipboardKeyLoaded), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('empty and invalid clipboard show feedback snackbars', ( + tester, + ) async { + final connector = await _connectedConnector(tester); + + String? clipboardText; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.getData') { + return clipboardText == null + ? null + : {'text': clipboardText}; + } + return null; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const AddContactScreen()), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(_l10n.contacts_addContactFromClipboard)); + await tester.pumpAndSettle(); + expect(find.text(_l10n.contacts_clipboardEmpty), findsOneWidget); + + clipboardText = 'not-a-valid-key-or-uri'; + await tester.tap(find.text(_l10n.contacts_addContactFromClipboard)); + await tester.pumpAndSettle(); + expect(find.text(_l10n.contacts_invalidAdvertFormat), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('rejects adding own public key manually', (tester) async { + final connector = await _connectedConnector(tester); + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const AddContactScreen()), + ); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextFormField).first, 'Self'); + await tester.enterText( + find.byType(TextFormField).last, + connector.selfPublicKeyHex, + ); + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.contactShare_isYou), findsOneWidget); + expect(find.byType(AddContactScreen), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('meshcore:// contact URI in clipboard imports contact', ( + tester, + ) async { + final connector = await _connectedConnector(tester); + + final keyHex = 'cd' * 32; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.getData') { + return { + 'text': 'meshcore://contact/add?name=UriPeer&public_key=$keyHex', + }; + } + return null; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + + await tester.pumpWidget( + _wrapApp( + connector: connector, + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: FilledButton( + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const AddContactScreen()), + ), + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + await tester.runAsync(() async { + await tester.tap(find.text(_l10n.contacts_addContactFromClipboard)); + final end = DateTime.now().add(const Duration(seconds: 5)); + while (!connector.contacts.any((c) => c.publicKeyHex == keyHex) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + await tester.pumpAndSettle(); + + expect(connector.contacts.any((c) => c.name == 'UriPeer'), isTrue); + expect(find.byType(AddContactScreen), findsNothing); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('Contacts FAB and menu item both open AddContactScreen', ( + tester, + ) async { + final connector = await _connectedConnector(tester); + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const ContactsScreen()), + ); + await tester.pumpAndSettle(); + + // Entry point 1: Contacts FAB. + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + expect(find.byType(AddContactScreen), findsOneWidget); + + await tester.pageBack(); + await tester.pumpAndSettle(); + expect(find.byType(AddContactScreen), findsNothing); + + // Entry point 2: Overflow menu item. + await tester.tap(find.byIcon(Icons.more_vert)); + await tester.pumpAndSettle(); + await tester.tap(find.text(_l10n.addContact_title)); + await tester.pumpAndSettle(); + expect(find.byType(AddContactScreen), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('navigates to Discovered Contacts and adds a discovered node', ( + tester, + ) async { + final connector = await _connectedConnector(tester); + + final discoveredKey = Uint8List.fromList(List.filled(32, 0x5E)); + final discoveredKeyHex = pubKeyToHex(discoveredKey); + const name = 'Discovered Node'; + final frameData = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12); + final frame = frameData.buffer.asUint8List(); + frame[0] = pushCodeNewAdvert; + frame.setRange(1, 33, discoveredKey); + frame[33] = advTypeChat; + frame[35] = 0xFF; + frame.setRange(100, 100 + name.length, name.codeUnits); + frameData.setUint32(132, 1700000000, Endian.little); + connector.handleFrameForTest(frame); + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const AddContactScreen()), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(_l10n.addContact_fromDiscovered)); + await tester.pumpAndSettle(); + + expect(find.byType(DiscoveryScreen), findsOneWidget); + expect(find.text(name), findsOneWidget); + + await tester.runAsync(() async { + await tester.tap(find.byIcon(Icons.person_add_alt_1)); + final end = DateTime.now().add(const Duration(seconds: 5)); + while (!connector.contacts.any( + (c) => c.publicKeyHex == discoveredKeyHex, + ) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + await tester.pumpAndSettle(); + + expect( + connector.contacts.any((c) => c.publicKeyHex == discoveredKeyHex), + isTrue, + ); + expect(find.text(_l10n.discoveredContacts_contactAdded), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('disconnected manual submit shows offline error snackbar', ( + tester, + ) async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + final keyHex = 'ef' * 32; + + await tester.pumpWidget( + _wrapApp(connector: connector, home: const AddContactScreen()), + ); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextFormField).first, 'Offline Node'); + await tester.enterText(find.byType(TextFormField).last, keyHex); + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + + expect(find.text(_l10n.settings_notConnectedError), findsOneWidget); + expect(find.byType(AddContactScreen), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + for (final (label, theme, locale) in [ + ('light en', MeshTheme.light(), const Locale('en')), + ('dark en', MeshTheme.dark(), const Locale('en')), + ('dark de', MeshTheme.dark(), const Locale('de')), + ]) { + for (final scale in [1.3, 2.0]) { + testWidgets('fits 320dp width at ${scale}x in $label', (tester) async { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final connector = await _connectedConnector(tester); + + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (text.contains('overflowed')) { + overflows.add(text.split('\n').first); + } else { + previous?.call(details); + } + }; + addTearDown(() => FlutterError.onError = previous); + + await tester.pumpWidget( + _wrapApp( + connector: connector, + home: const AddContactScreen(), + theme: theme, + locale: locale, + textScale: scale, + ), + ); + await tester.pumpAndSettle(); + + FlutterError.onError = previous; + expect(overflows, isEmpty, reason: overflows.join('\n')); + await tester.pumpWidget(const SizedBox()); + }); + } + } +} diff --git a/test/screens/offline_mode_test.dart b/test/screens/offline_mode_test.dart index fb827588..11469c44 100644 --- a/test/screens/offline_mode_test.dart +++ b/test/screens/offline_mode_test.dart @@ -251,7 +251,7 @@ void main() { await _settle(tester); expect(_menuItem(_l10n.contacts_floodAdvert).enabled, isFalse); expect(_menuItem(_l10n.contacts_zeroHopAdvert).enabled, isFalse); - expect(_menuItem(_l10n.contacts_addContactFromClipboard).enabled, isFalse); + expect(_menuItem(_l10n.addContact_title).enabled, isFalse); expect(_menuItem(_l10n.common_connect).enabled, isTrue); await tester.pumpWidget(const SizedBox()); }); diff --git a/test/screens/small_screen_layout_test.dart b/test/screens/small_screen_layout_test.dart index 4f02ff36..1d4e40d9 100644 --- a/test/screens/small_screen_layout_test.dart +++ b/test/screens/small_screen_layout_test.dart @@ -15,6 +15,7 @@ import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/models/contact.dart'; import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/add_contact_screen.dart'; import 'package:meshcore_open/screens/app_debug_log_screen.dart'; import 'package:meshcore_open/screens/app_settings_screen.dart'; import 'package:meshcore_open/screens/ble_debug_log_screen.dart'; @@ -145,7 +146,7 @@ _interactions = { .first, ); }, - 'Contacts add sheet': (t, _) async { + 'Contacts add page': (t, _) async { await t.tap(find.byType(FloatingActionButton)); }, // Four routing modes (Auto, Flood, Direct, Manual) share one row. @@ -161,7 +162,8 @@ _interactions = { final Map _screens = { 'Contacts options sheet': (_) => const ContactsScreen(), - 'Contacts add sheet': (_) => const ContactsScreen(), + 'Contacts add page': (_) => const ContactsScreen(), + 'AddContact': (_) => const AddContactScreen(), 'Routing sheet': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)), 'Scanner': (_) => const ScannerScreen(), 'Tcp': (_) => const TcpScreen(), diff --git a/test/utils/contact_clipboard_test.dart b/test/utils/contact_clipboard_test.dart new file mode 100644 index 00000000..2322b0f1 --- /dev/null +++ b/test/utils/contact_clipboard_test.dart @@ -0,0 +1,109 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/contact_clipboard.dart'; +import 'package:meshcore_open/utils/contact_qr.dart'; + +void main() { + final validLowerHex = List.generate( + 32, + (i) => i.toRadixString(16).padLeft(2, '0'), + ).join(); + final validUpperHex = validLowerHex.toUpperCase(); + + group('normalizeContactPublicKeyHex & decodeContactPublicKeyHex', () { + test('accepts lowercase 64-char hex', () { + expect(normalizeContactPublicKeyHex(validLowerHex), validLowerHex); + final bytes = decodeContactPublicKeyHex(validLowerHex); + expect(bytes, isNotNull); + expect(bytes!.length, 32); + expect(bytes[0], 0x00); + expect(bytes[31], 0x1f); + }); + + test('trims whitespace, strips 0x/0X prefix, and normalizes case', () { + expect( + normalizeContactPublicKeyHex(' 0x$validUpperHex \n\t '), + validLowerHex, + ); + expect(normalizeContactPublicKeyHex('0X$validUpperHex'), validLowerHex); + }); + + test( + 'rejects invalid lengths, non-hex characters, and internal spaces', + () { + expect(normalizeContactPublicKeyHex(''), isNull); + expect(normalizeContactPublicKeyHex(' '), isNull); + expect( + normalizeContactPublicKeyHex(validLowerHex.substring(0, 63)), + isNull, + ); + expect(normalizeContactPublicKeyHex('${validLowerHex}aa'), isNull); + expect(normalizeContactPublicKeyHex('0x $validLowerHex'), isNull); + expect(normalizeContactPublicKeyHex('zz' * 32), isNull); + expect(decodeContactPublicKeyHex('zz' * 32), isNull); + }, + ); + }); + + group('parseContactClipboard', () { + test('parses official meshcore://contact/add URI', () { + final result = parseContactClipboard( + ' meshcore://contact/add?name=Alice&public_key=$validLowerHex&type=2 ', + ); + expect(result.kind, ContactClipboardKind.contact); + expect(result.contact, isNotNull); + expect(result.contact!.name, 'Alice'); + expect(result.contact!.type, 2); + expect(result.contact!.publicKey!.length, 32); + }); + + test('parses legacy meshcore:// URI', () { + final advertHex = '0a' * 98; + final result = parseContactClipboard('meshcore://$advertHex'); + expect(result.kind, ContactClipboardKind.contact); + expect(result.contact!.isAdvertPacket, isTrue); + expect(result.contact!.advertPacket!.length, 98); + }); + + test('parses contact share token', () { + final result = parseContactClipboard('Bob: <$validUpperHex:3:Bob Node>'); + expect(result.kind, ContactClipboardKind.contact); + expect(result.contact!.name, 'Bob Node'); + expect(result.contact!.type, 3); + expect(result.contact!.publicKey!.length, 32); + }); + + test('parses bare 64-char hex key with whitespace, 0x, and uppercase', () { + final result = parseContactClipboard('\n 0x$validUpperHex '); + expect(result.kind, ContactClipboardKind.publicKey); + expect(result.publicKeyHex, validLowerHex); + expect(result.contact, isNull); + }); + + test('returns empty for null or whitespace-only text', () { + expect(parseContactClipboard(null).kind, ContactClipboardKind.empty); + expect(parseContactClipboard('').kind, ContactClipboardKind.empty); + expect(parseContactClipboard(' \n\t ').kind, ContactClipboardKind.empty); + }); + + test('returns invalid for malformed URIs, short keys, and random text', () { + expect( + parseContactClipboard('meshcore://not-valid').kind, + ContactClipboardKind.invalid, + ); + expect( + parseContactClipboard( + 'meshcore://channel/add?name=Public&secret=abcd', + ).kind, + ContactClipboardKind.invalid, + ); + expect( + parseContactClipboard(validLowerHex.substring(0, 62)).kind, + ContactClipboardKind.invalid, + ); + expect( + parseContactClipboard('hello world').kind, + ContactClipboardKind.invalid, + ); + }); + }); +} diff --git a/untranslated.json b/untranslated.json index 24f3cb93..6c13c89f 100644 --- a/untranslated.json +++ b/untranslated.json @@ -36,7 +36,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "cs": [ @@ -76,7 +87,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "de": [ @@ -116,7 +138,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "es": [ @@ -156,7 +189,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "fr": [ @@ -196,7 +240,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "hu": [ @@ -236,7 +291,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "it": [ @@ -276,7 +342,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "ja": [ @@ -316,7 +393,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "ko": [ @@ -356,7 +444,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "nl": [ @@ -396,7 +495,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "pl": [ @@ -436,7 +546,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "pt": [ @@ -476,7 +597,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "pt_PT": [ @@ -516,7 +648,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "ru": [ @@ -556,7 +699,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "sk": [ @@ -596,7 +750,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "sl": [ @@ -636,7 +801,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "sv": [ @@ -676,7 +852,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "uk": [ @@ -716,7 +903,18 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ], "zh": [ @@ -756,6 +954,17 @@ "chatCompression_profile", "chatCompression_noStorageId", "chatCompression_saveFailed", - "messageMeta_smazCompressed" + "messageMeta_smazCompressed", + "addContact_title", + "addContact_infoBanner", + "addContact_contactType", + "addContact_name", + "addContact_nameRequired", + "addContact_publicKeyHex", + "addContact_publicKeyRequired", + "addContact_publicKeyInvalid", + "addContact_clipboardKeyLoaded", + "addContact_fromDiscovered", + "addContact_saveFailed" ] } From 05b47a037b62bf1e5132a9d55159d3b21154e440 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:50:29 -0700 Subject: [PATCH 35/50] Add interactive GPS coordinates in messages --- lib/helpers/coordinate_parser.dart | 277 ++++++++++ lib/helpers/link_handler.dart | 356 +++++++++++-- lib/l10n/app_en.arb | 6 +- lib/l10n/app_localizations.dart | 24 + lib/l10n/app_localizations_bg.dart | 12 + lib/l10n/app_localizations_cs.dart | 12 + lib/l10n/app_localizations_de.dart | 12 + lib/l10n/app_localizations_en.dart | 12 + lib/l10n/app_localizations_es.dart | 12 + lib/l10n/app_localizations_fr.dart | 12 + lib/l10n/app_localizations_hu.dart | 12 + lib/l10n/app_localizations_it.dart | 12 + lib/l10n/app_localizations_ja.dart | 12 + lib/l10n/app_localizations_ko.dart | 12 + lib/l10n/app_localizations_nl.dart | 12 + lib/l10n/app_localizations_pl.dart | 12 + lib/l10n/app_localizations_pt.dart | 12 + lib/l10n/app_localizations_ru.dart | 12 + lib/l10n/app_localizations_sk.dart | 12 + lib/l10n/app_localizations_sl.dart | 12 + lib/l10n/app_localizations_sv.dart | 12 + lib/l10n/app_localizations_uk.dart | 12 + lib/l10n/app_localizations_zh.dart | 12 + lib/screens/bookmarks_screen.dart | 3 + lib/screens/channel_chat_screen.dart | 2 + lib/screens/chat_screen.dart | 2 + lib/screens/coordinate_map_screen.dart | 260 ++++++++++ lib/widgets/translated_message_content.dart | 4 + test/helpers/coordinate_parser_test.dart | 219 ++++++++ test/screens/coordinate_messages_test.dart | 484 ++++++++++++++++++ test/screens/small_screen_layout_test.dart | 6 + .../translated_message_content_test.dart | 84 ++- untranslated.json | 114 ++++- 33 files changed, 1985 insertions(+), 84 deletions(-) create mode 100644 lib/helpers/coordinate_parser.dart create mode 100644 lib/screens/coordinate_map_screen.dart create mode 100644 test/helpers/coordinate_parser_test.dart create mode 100644 test/screens/coordinate_messages_test.dart diff --git a/lib/helpers/coordinate_parser.dart b/lib/helpers/coordinate_parser.dart new file mode 100644 index 00000000..2fc30033 --- /dev/null +++ b/lib/helpers/coordinate_parser.dart @@ -0,0 +1,277 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_linkify/flutter_linkify.dart'; + +import '../utils/platform_info.dart'; + +/// A parsed WGS84 decimal coordinate pair (`latitude, longitude`) found in text. +@immutable +class ParsedCoordinate { + final double latitude; + final double longitude; + final String rawText; + final int start; + final int end; + + const ParsedCoordinate({ + required this.latitude, + required this.longitude, + required this.rawText, + required this.start, + required this.end, + }); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is ParsedCoordinate && + latitude == other.latitude && + longitude == other.longitude && + rawText == other.rawText && + start == other.start && + end == other.end; + + @override + int get hashCode => Object.hash(latitude, longitude, rawText, start, end); + + @override + String toString() => + 'ParsedCoordinate($latitude, $longitude, "$rawText", $start..$end)'; +} + +/// Linkify element representing a detected GPS coordinate pair. +class CoordinateElement extends LinkableElement { + final double latitude; + final double longitude; + + CoordinateElement({ + required this.latitude, + required this.longitude, + required String rawText, + }) : super( + rawText, + buildExternalMapUri(latitude, longitude).toString(), + rawText, + ); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CoordinateElement && + super.equals(other) && + latitude == other.latitude && + longitude == other.longitude; + + @override + int get hashCode => Object.hash(super.hashCode, latitude, longitude); + + @override + String toString() => "CoordinateElement: '$text' ($latitude, $longitude)"; +} + +/// Builds a platform-appropriate external maps URI for [latitude] and [longitude]. +Uri buildExternalMapUri( + double latitude, + double longitude, { + TargetPlatform? platform, + bool? isWeb, +}) { + final normalizedLat = latitude == 0 ? 0.0 : latitude; + final normalizedLon = longitude == 0 ? 0.0 : longitude; + final latStr = normalizedLat.toString(); + final lonStr = normalizedLon.toString(); + + final web = isWeb ?? PlatformInfo.isWeb; + if (web) { + return Uri.parse( + 'https://www.openstreetmap.org/?mlat=$latStr&mlon=$lonStr#map=16/$latStr/$lonStr', + ); + } + + final targetPlatform = platform ?? defaultTargetPlatform; + return switch (targetPlatform) { + TargetPlatform.android => Uri.parse( + 'geo:$latStr,$lonStr?q=$latStr,$lonStr', + ), + TargetPlatform.iOS || TargetPlatform.macOS => Uri.parse( + 'https://maps.apple.com/?ll=$latStr,$lonStr&q=$latStr,$lonStr', + ), + TargetPlatform.linux || + TargetPlatform.windows || + TargetPlatform.fuchsia => Uri.parse( + 'https://www.openstreetmap.org/?mlat=$latStr&mlon=$lonStr#map=16/$latStr/$lonStr', + ), + }; +} + +/// Detects decimal `latitude, longitude` GPS coordinates inside [TextElement]s +/// while avoiding URLs, version numbers, integer pairs, and embedded identifiers. +class CoordinateLinkifier extends Linkifier { + const CoordinateLinkifier(); + + static final RegExp _candidateRegex = RegExp( + r'([+-]?\d+\.\d+),[ \t]*([+-]?\d+\.\d+)', + ); + + // Covers URI schemes and bare domain/path strings that UrlLinkifier leaves + // as plain text (e.g. geo:..., ftp://..., maps.google.com/?q=...). + static final RegExp _nonLinkifiedUrlRegex = RegExp( + r'(?:[a-zA-Z][a-zA-Z0-9+.-]*://|geo:|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/)[^\s]*', + ); + + static final RegExp _disallowedBoundaryChar = RegExp(r'[A-Za-z0-9_+-]'); + static final RegExp _asciiDigit = RegExp(r'[0-9]'); + + @override + List parse( + List elements, + LinkifyOptions options, + ) { + final result = []; + for (final element in elements) { + if (element is! TextElement) { + result.add(element); + continue; + } + result.addAll(_parseSegment(element.text)); + } + return result; + } + + static List _parseSegment(String text) { + final blockedRanges = <({int start, int end})>[ + for (final m in _nonLinkifiedUrlRegex.allMatches(text)) + (start: m.start, end: m.end), + ]; + + final elements = []; + var cursor = 0; + + for (final match in _candidateRegex.allMatches(text)) { + if (_isInsideRanges(match.start, match.end, blockedRanges)) { + continue; + } + if (!_hasValidBoundaries(text, match.start, match.end)) { + continue; + } + + final lat = double.tryParse(match.group(1)!); + final lon = double.tryParse(match.group(2)!); + if (lat == null || lon == null || !lat.isFinite || !lon.isFinite) { + continue; + } + if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0) { + continue; + } + + if (match.start > cursor) { + elements.add(TextElement(text.substring(cursor, match.start))); + } + elements.add( + CoordinateElement( + latitude: lat == 0 ? 0.0 : lat, + longitude: lon == 0 ? 0.0 : lon, + rawText: match.group(0)!, + ), + ); + cursor = match.end; + } + + if (elements.isEmpty) { + return [TextElement(text)]; + } + if (cursor < text.length) { + elements.add(TextElement(text.substring(cursor))); + } + return elements; + } + + static bool _isInsideRanges( + int start, + int end, + List<({int start, int end})> ranges, + ) { + for (final range in ranges) { + if (start < range.end && end > range.start) { + return true; + } + } + return false; + } + + static bool _hasValidBoundaries(String text, int start, int end) { + if (start > 0) { + final prev = text[start - 1]; + if (prev == '.' || _disallowedBoundaryChar.hasMatch(prev)) { + return false; + } + } + if (end < text.length) { + final next = text[end]; + if (_disallowedBoundaryChar.hasMatch(next)) { + return false; + } + // Reject version-like continuations (e.g. "1.2,3.4.5"), while allowing + // trailing sentence periods (e.g. "38.722,-9.139."). + if (next == '.' && + end + 1 < text.length && + _asciiDigit.hasMatch(text[end + 1])) { + return false; + } + } + return true; + } +} + +/// Shared parser returning linkified elements and extracted [ParsedCoordinate]s. +class CoordinateParser { + CoordinateParser._(); + + static const LinkifyOptions linkifyOptions = LinkifyOptions( + humanize: false, + defaultToHttps: false, + ); + + static const List linkifiers = [ + UrlLinkifier(), + EmailLinkifier(), + CoordinateLinkifier(), + ]; + + /// Splits [text] into URL, email, coordinate, and plain-text elements. + static List linkifyWithCoordinates(String text) { + if (text.isEmpty) return const []; + var elements = [TextElement(text)]; + for (final linkifier in linkifiers) { + elements = linkifier.parse(elements, linkifyOptions); + } + return elements; + } + + /// Extracts all valid WGS84 decimal coordinates in [text]. + static List parse(String text) { + if (text.isEmpty) return const []; + final elements = linkifyWithCoordinates(text); + final results = []; + var offset = 0; + + for (final element in elements) { + final raw = element.originText; + final index = text.indexOf(raw, offset); + final start = index >= 0 ? index : offset; + final end = start + raw.length; + if (element is CoordinateElement) { + results.add( + ParsedCoordinate( + latitude: element.latitude, + longitude: element.longitude, + rawText: element.text, + start: start, + end: end, + ), + ); + } + offset = end; + } + return results; + } +} diff --git a/lib/helpers/link_handler.dart b/lib/helpers/link_handler.dart index 8a4752d7..ba109649 100644 --- a/lib/helpers/link_handler.dart +++ b/lib/helpers/link_handler.dart @@ -1,10 +1,16 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_linkify/flutter_linkify.dart'; import 'package:url_launcher/url_launcher.dart'; -import '../l10n/l10n.dart'; -import '../utils/platform_info.dart'; + +import '../helpers/coordinate_parser.dart'; import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../screens/coordinate_map_screen.dart'; +import '../theme/mesh_theme.dart'; +import '../utils/platform_info.dart'; +import '../widgets/mesh_ui.dart'; class LinkHandler { static TextStyle defaultLinkStyle(BuildContext context, TextStyle base) { @@ -15,60 +21,153 @@ class LinkHandler { return base.copyWith(color: orange, decoration: TextDecoration.underline); } - /// The system text scale as a linear factor for [style]'s size. - /// - /// flutter_linkify only takes a `textScaleFactor` (default 1.0, which - /// ignores the system font size), so the ambient [TextScaler] is sampled - /// at the style's font size to keep Android's nonlinear scaling. The - /// in-app chat text scale is already part of `style.fontSize`. - static double systemTextScaleFactor(BuildContext context, TextStyle style) { - final fontSize = - style.fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14; - if (fontSize <= 0) return 1.0; - return MediaQuery.textScalerOf(context).scale(fontSize) / fontSize; + static Color _inferBackground(BuildContext context, TextStyle base) { + final textColor = base.color; + if (textColor != null) { + return textColor.computeLuminance() > 0.5 + ? MeshPalette.bg2 + : Colors.white; + } + return Theme.of(context).colorScheme.surfaceContainerLow; } - /// Returns a [SelectableLinkify] on desktop or a [Linkify] on mobile. + static TextStyle defaultCoordinateStyle( + BuildContext context, + TextStyle base, { + Color? backgroundColor, + }) { + final scheme = Theme.of(context).colorScheme; + final effectiveBg = backgroundColor ?? _inferBackground(context, base); + final accent = readableAccent( + scheme.primary, + effectiveBg, + minContrast: 4.5, + ); + return base.copyWith( + color: accent, + decoration: TextDecoration.underline, + decorationColor: accent, + fontWeight: FontWeight.w600, + ); + } + + /// Returns an interactive rich-text widget (selectable on desktop) with URL, + /// email, and GPS coordinate detection. static Widget buildLinkifyText({ required BuildContext context, required String text, required TextStyle style, TextStyle? linkStyle, + TextStyle? coordinateStyle, + Color? backgroundColor, VoidCallback? onSecondaryTap, }) { - final effectiveLinkStyle = linkStyle ?? defaultLinkStyle(context, style); - const options = LinkifyOptions(humanize: false, defaultToHttps: false); - const linkifiers = [UrlLinkifier(), EmailLinkifier()]; - void onOpen(LinkableElement link) => handleLinkTap(context, link.url); - final textScaleFactor = systemTextScaleFactor(context, style); - - if (PlatformInfo.isDesktop) { - final linkify = SelectableLinkify( - text: text, - style: style, - linkStyle: effectiveLinkStyle, - options: options, - linkifiers: linkifiers, - onOpen: onOpen, - textScaleFactor: textScaleFactor, - ); - if (onSecondaryTap == null) return linkify; - return Listener( - onPointerDown: (event) { - if (event.buttons & kSecondaryMouseButton != 0) onSecondaryTap(); - }, - behavior: HitTestBehavior.translucent, - child: linkify, - ); - } - return Linkify( + return _InteractiveMessageText( text: text, style: style, - linkStyle: effectiveLinkStyle, - options: options, - linkifiers: linkifiers, - onOpen: onOpen, - textScaleFactor: textScaleFactor, + linkStyle: linkStyle, + coordinateStyle: coordinateStyle, + backgroundColor: backgroundColor, + onSecondaryTap: onSecondaryTap, + ); + } + + static void openCoordinateMap( + BuildContext context, + CoordinateElement coordinate, + ) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => CoordinateMapScreen( + latitude: coordinate.latitude, + longitude: coordinate.longitude, + label: coordinate.text, + ), + ), + ); + } + + static Future copyCoordinateLocation( + BuildContext context, + String text, + ) async { + await Clipboard.setData(ClipboardData(text: text)); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.coordinate_copied), + ); + } + + static Future openCoordinateInExternalMaps( + BuildContext context, + double latitude, + double longitude, + ) async { + final uri = buildExternalMapUri(latitude, longitude); + try { + if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) { + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_couldNotOpenLink(uri.toString())), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } + } + } catch (_) { + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_couldNotOpenLink(uri.toString())), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } + } + } + + static Future showCoordinateActionSheet( + BuildContext context, + CoordinateElement coordinate, + ) { + return showMeshSheet( + context, + builder: (sheetContext) { + final l10n = sheetContext.l10n; + return SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: coordinate.text, + subtitle: l10n.chat_location, + ), + ListTile( + leading: const Icon(Icons.copy), + title: Text(l10n.coordinate_copyLocation), + onTap: () { + Navigator.pop(sheetContext); + copyCoordinateLocation(context, coordinate.text); + }, + ), + ListTile( + leading: const Icon(Icons.open_in_new), + title: Text(l10n.coordinate_openInMaps), + onTap: () { + Navigator.pop(sheetContext); + openCoordinateInExternalMaps( + context, + coordinate.latitude, + coordinate.longitude, + ); + }, + ), + ], + ), + ), + ); + }, ); } @@ -139,3 +238,170 @@ class LinkHandler { } } } + +/// Extends [TapGestureRecognizer] so Flutter's paragraph/editable semantics +/// recognize it as a tappable link while also forwarding pointers to an owned +/// [LongPressGestureRecognizer] in the same gesture arena. +class _CoordinateGestureRecognizer extends TapGestureRecognizer { + final LongPressGestureRecognizer _longPress; + + _CoordinateGestureRecognizer({ + required VoidCallback onTap, + required VoidCallback onLongPress, + }) : _longPress = LongPressGestureRecognizer()..onLongPress = onLongPress { + this.onTap = onTap; + } + + @override + void addPointer(PointerDownEvent event) { + super.addPointer(event); + _longPress.addPointer(event); + } + + @override + void dispose() { + _longPress.dispose(); + super.dispose(); + } +} + +class _InteractiveMessageText extends StatefulWidget { + final String text; + final TextStyle style; + final TextStyle? linkStyle; + final TextStyle? coordinateStyle; + final Color? backgroundColor; + final VoidCallback? onSecondaryTap; + + const _InteractiveMessageText({ + required this.text, + required this.style, + this.linkStyle, + this.coordinateStyle, + this.backgroundColor, + this.onSecondaryTap, + }); + + @override + State<_InteractiveMessageText> createState() => + _InteractiveMessageTextState(); +} + +class _InteractiveMessageTextState extends State<_InteractiveMessageText> { + late List _elements; + final List _recognizers = []; + + @override + void initState() { + super.initState(); + _rebuildSpans(); + } + + @override + void didUpdateWidget(covariant _InteractiveMessageText oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.text != widget.text) { + _disposeRecognizers(); + _rebuildSpans(); + } + } + + @override + void dispose() { + _disposeRecognizers(); + super.dispose(); + } + + void _disposeRecognizers() { + for (final recognizer in _recognizers) { + recognizer.dispose(); + } + _recognizers.clear(); + } + + void _rebuildSpans() { + _elements = CoordinateParser.linkifyWithCoordinates(widget.text); + } + + InlineSpan _buildElementSpan( + LinkifyElement element, + TextStyle effectiveLinkStyle, + TextStyle effectiveCoordinateStyle, + ) { + if (element is CoordinateElement) { + final recognizer = _CoordinateGestureRecognizer( + onTap: () { + if (!mounted) return; + LinkHandler.openCoordinateMap(context, element); + }, + onLongPress: () { + if (!mounted) return; + LinkHandler.showCoordinateActionSheet(context, element); + }, + ); + _recognizers.add(recognizer); + return TextSpan( + text: element.text, + style: effectiveCoordinateStyle, + recognizer: recognizer, + mouseCursor: SystemMouseCursors.click, + ); + } + if (element is LinkableElement) { + final recognizer = TapGestureRecognizer() + ..onTap = () { + if (!mounted) return; + LinkHandler.handleLinkTap(context, element.url); + }; + _recognizers.add(recognizer); + return TextSpan( + text: element.text, + style: effectiveLinkStyle, + recognizer: recognizer, + mouseCursor: SystemMouseCursors.click, + ); + } + return TextSpan(text: element.text, style: widget.style); + } + + @override + Widget build(BuildContext context) { + _disposeRecognizers(); + final effectiveLinkStyle = + widget.linkStyle ?? LinkHandler.defaultLinkStyle(context, widget.style); + final effectiveCoordinateStyle = + widget.coordinateStyle ?? + LinkHandler.defaultCoordinateStyle( + context, + widget.style, + backgroundColor: widget.backgroundColor, + ); + final span = TextSpan( + style: widget.style, + children: [ + for (final element in _elements) + _buildElementSpan( + element, + effectiveLinkStyle, + effectiveCoordinateStyle, + ), + ], + ); + + if (PlatformInfo.isDesktop) { + final selectable = SelectableText.rich(span); + if (widget.onSecondaryTap == null) return selectable; + return Listener( + onPointerDown: (event) { + if (event.buttons & kSecondaryMouseButton != 0) { + widget.onSecondaryTap!(); + } + }, + behavior: HitTestBehavior.translucent, + child: selectable, + ); + } + + return Text.rich(span); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 9fdab531..fb372f12 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -4459,5 +4459,9 @@ "addContact_publicKeyInvalid": "Public key must be 64 hex characters (32 bytes)", "addContact_clipboardKeyLoaded": "Public key filled in. Choose a contact type, enter a name, and tap save.", "addContact_fromDiscovered": "Add from Discovered Contacts", - "addContact_saveFailed": "Failed to add contact." + "addContact_saveFailed": "Failed to add contact.", + "coordinateMap_title": "Location", + "coordinate_copyLocation": "Copy location", + "coordinate_openInMaps": "Open in maps", + "coordinate_copied": "Location copied" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 1a95b947..91f0e099 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -12957,6 +12957,30 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Failed to add contact.'** String get addContact_saveFailed; + + /// No description provided for @coordinateMap_title. + /// + /// In en, this message translates to: + /// **'Location'** + String get coordinateMap_title; + + /// No description provided for @coordinate_copyLocation. + /// + /// In en, this message translates to: + /// **'Copy location'** + String get coordinate_copyLocation; + + /// No description provided for @coordinate_openInMaps. + /// + /// In en, this message translates to: + /// **'Open in maps'** + String get coordinate_openInMaps; + + /// No description provided for @coordinate_copied. + /// + /// In en, this message translates to: + /// **'Location copied'** + String get coordinate_copied; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index a25835a8..c34ce131 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -7780,4 +7780,16 @@ class AppLocalizationsBg extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 3c21b58f..dd1c2f0e 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -7751,4 +7751,16 @@ class AppLocalizationsCs extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 9c2fc3d7..6ba0bdc1 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -7794,4 +7794,16 @@ class AppLocalizationsDe extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 5dc6ebe2..73403d34 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -7665,4 +7665,16 @@ class AppLocalizationsEn extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 13157491..d6decaeb 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -7772,4 +7772,16 @@ class AppLocalizationsEs extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 3412c216..3dc856b8 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -7800,4 +7800,16 @@ class AppLocalizationsFr extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 36b2559f..1b79ee96 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -7763,4 +7763,16 @@ class AppLocalizationsHu extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 85e42b74..b947fd5b 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -7783,4 +7783,16 @@ class AppLocalizationsIt extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 4000f470..2e4fb87e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -7425,4 +7425,16 @@ class AppLocalizationsJa extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index f6158ab6..0e8f68e0 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -7437,4 +7437,16 @@ class AppLocalizationsKo extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 460168ad..bab90146 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -7739,4 +7739,16 @@ class AppLocalizationsNl extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 36d2c8b8..8ff2a74f 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -7817,4 +7817,16 @@ class AppLocalizationsPl extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 7e8aa53b..df59f378 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -7761,6 +7761,18 @@ class AppLocalizationsPt extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index ebc850d1..87c33317 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -7797,4 +7797,16 @@ class AppLocalizationsRu extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index b5fee2ba..f8d13492 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -7762,4 +7762,16 @@ class AppLocalizationsSk extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 7e60528f..2c807d71 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -7756,4 +7756,16 @@ class AppLocalizationsSl extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9b4b635c..64008f62 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -7716,4 +7716,16 @@ class AppLocalizationsSv extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index e2bbcf5f..552aeaae 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -7809,4 +7809,16 @@ class AppLocalizationsUk extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index dbc9d3b1..50dd22f5 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -7267,4 +7267,16 @@ class AppLocalizationsZh extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dart index 3ae89ce9..2001db4a 100644 --- a/lib/screens/bookmarks_screen.dart +++ b/lib/screens/bookmarks_screen.dart @@ -96,6 +96,9 @@ class _BookmarksScreenState extends State { : bookmark.text, style: textStyle, originalStyle: textStyle.copyWith(fontStyle: FontStyle.italic), + backgroundColor: + Theme.of(context).cardTheme.color ?? + Theme.of(context).colorScheme.surfaceContainerLow, ); return Card( margin: const EdgeInsets.only(bottom: 10), diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 4daf7613..82641df4 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1204,6 +1204,7 @@ class _ChannelChatScreenState extends State fontStyle: FontStyle.italic, color: textColor.withValues(alpha: 0.72), ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? () => _showMessageActions(message) : null, @@ -1356,6 +1357,7 @@ class _ChannelChatScreenState extends State alpha: 0.72, ), ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? () => _showMessageActions(message) : null, diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 1276a95a..e8d3eba2 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -1686,6 +1686,7 @@ class _MessageBubble extends StatelessWidget { color: textColor.withValues(alpha: 0.72), fontSize: bodyFontSize * textScale, ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? onLongPress : null, ), ), @@ -1820,6 +1821,7 @@ class _MessageBubble extends StatelessWidget { ), fontSize: bodyFontSize * textScale, ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? onLongPress : null, diff --git a/lib/screens/coordinate_map_screen.dart b/lib/screens/coordinate_map_screen.dart new file mode 100644 index 00000000..da3240c1 --- /dev/null +++ b/lib/screens/coordinate_map_screen.dart @@ -0,0 +1,260 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +import '../helpers/link_handler.dart'; +import '../l10n/l10n.dart'; +import '../services/map_tile_cache_service.dart'; +import '../theme/mesh_theme.dart'; +import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/mesh_ui.dart'; + +/// Dedicated full-screen map centered on a tapped GPS coordinate. +class CoordinateMapScreen extends StatefulWidget { + final double latitude; + final double longitude; + final String? label; + + const CoordinateMapScreen({ + super.key, + required this.latitude, + required this.longitude, + this.label, + }); + + @override + State createState() => _CoordinateMapScreenState(); +} + +class _CoordinateMapScreenState extends State { + static const double _initialZoom = 15.0; + static const double _minZoom = 2.0; + static const double _maxZoom = 18.0; + + final MapController _mapController = MapController(); + + LatLng get _position => LatLng(widget.latitude, widget.longitude); + + String get _coordinateText => widget.label?.trim().isNotEmpty == true + ? widget.label!.trim() + : '${widget.latitude}, ${widget.longitude}'; + + @override + void dispose() { + _mapController.dispose(); + super.dispose(); + } + + void _zoomBy(double delta) { + final camera = _mapController.camera; + final nextZoom = (camera.zoom + delta).clamp(_minZoom, _maxZoom).toDouble(); + _mapController.move(camera.center, nextZoom); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final mapTheme = MeshMapTheme.of(context); + final tileCache = context.read(); + final isDesktop = + defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.macOS; + final labelSurface = scheme.surfaceContainerLow; + final iconAccent = readableAccent( + scheme.primary, + labelSurface, + minContrast: 3, + ); + + return Scaffold( + appBar: AppBar( + centerTitle: true, + title: AdaptiveAppBarTitle(l10n.coordinateMap_title), + actions: [ + IconButton( + icon: const Icon(Icons.copy), + tooltip: l10n.coordinate_copyLocation, + onPressed: () => + LinkHandler.copyCoordinateLocation(context, _coordinateText), + ), + IconButton( + icon: const Icon(Icons.open_in_new), + tooltip: l10n.coordinate_openInMaps, + onPressed: () => LinkHandler.openCoordinateInExternalMaps( + context, + widget.latitude, + widget.longitude, + ), + ), + ], + ), + body: Stack( + children: [ + FlutterMap( + mapController: _mapController, + options: MapOptions( + initialCenter: _position, + initialZoom: _initialZoom, + minZoom: _minZoom, + maxZoom: _maxZoom, + interactionOptions: InteractionOptions( + flags: ~InteractiveFlag.rotate, + scrollWheelVelocity: isDesktop ? 0.012 : 0.005, + cursorKeyboardRotationOptions: + CursorKeyboardRotationOptions.disabled(), + keyboardOptions: isDesktop + ? const KeyboardOptions( + enableArrowKeysPanning: true, + enableWASDPanning: true, + enableRFZooming: true, + ) + : const KeyboardOptions.disabled(), + ), + ), + children: [ + tileCache.buildTileLayer(context), + MarkerLayer( + markers: [ + Marker( + point: _position, + width: 48, + height: 48, + child: IgnorePointer( + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: mapTheme.followsTheme + ? mapTheme.accent + : MapPalette.batteryLow, + border: Border.all( + color: MapPalette.markerOutline, + width: 3, + ), + boxShadow: const [ + BoxShadow( + color: MapPalette.markerShadow, + blurRadius: 8, + offset: Offset(0, 3), + ), + ], + ), + child: const Icon( + Icons.location_on, + color: MapPalette.markerOutline, + size: 26, + ), + ), + ), + ), + ], + ), + ], + ), + Positioned( + top: 12, + right: 12, + child: Column( + children: [ + _CoordinateMapControlButton( + icon: Icons.add, + tooltip: l10n.map_zoomIn, + onPressed: () => _zoomBy(1), + ), + const SizedBox(height: 8), + _CoordinateMapControlButton( + icon: Icons.remove, + tooltip: l10n.map_zoomOut, + onPressed: () => _zoomBy(-1), + ), + const SizedBox(height: 8), + _CoordinateMapControlButton( + icon: Icons.my_location, + tooltip: l10n.map_centerMap, + onPressed: () => _mapController.move(_position, _initialZoom), + ), + ], + ), + ), + Positioned( + left: 16, + right: 16, + bottom: 16, + child: SafeArea( + top: false, + child: Material( + color: labelSurface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + side: BorderSide(color: scheme.outlineVariant), + ), + elevation: 2, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 10, + ), + child: Row( + children: [ + Icon( + Icons.location_on_outlined, + color: iconAccent, + size: 22, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + _coordinateText, + style: MeshTheme.mono( + fontSize: 14, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class _CoordinateMapControlButton extends StatelessWidget { + final IconData icon; + final String tooltip; + final VoidCallback onPressed; + + const _CoordinateMapControlButton({ + required this.icon, + required this.tooltip, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Material( + color: scheme.surfaceContainerLow, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + side: BorderSide(color: scheme.outlineVariant), + ), + clipBehavior: Clip.antiAlias, + child: IconButton( + icon: Icon(icon), + tooltip: tooltip, + onPressed: onPressed, + iconSize: 22, + ), + ); + } +} diff --git a/lib/widgets/translated_message_content.dart b/lib/widgets/translated_message_content.dart index a40bacf8..c015585e 100644 --- a/lib/widgets/translated_message_content.dart +++ b/lib/widgets/translated_message_content.dart @@ -7,6 +7,7 @@ class TranslatedMessageContent extends StatelessWidget { final String? originalText; final TextStyle style; final TextStyle? originalStyle; + final Color? backgroundColor; final bool showOriginalFirst; final VoidCallback? onSecondaryTap; @@ -16,6 +17,7 @@ class TranslatedMessageContent extends StatelessWidget { required this.style, this.originalText, this.originalStyle, + this.backgroundColor, this.showOriginalFirst = true, this.onSecondaryTap, }); @@ -38,6 +40,7 @@ class TranslatedMessageContent extends StatelessWidget { fontStyle: FontStyle.italic, fontSize: style.fontSize, ), + backgroundColor: backgroundColor, onSecondaryTap: onSecondaryTap, ) : null; @@ -45,6 +48,7 @@ class TranslatedMessageContent extends StatelessWidget { context: context, text: trimmedDisplay, style: style, + backgroundColor: backgroundColor, onSecondaryTap: onSecondaryTap, ); diff --git a/test/helpers/coordinate_parser_test.dart b/test/helpers/coordinate_parser_test.dart new file mode 100644 index 00000000..75e5caeb --- /dev/null +++ b/test/helpers/coordinate_parser_test.dart @@ -0,0 +1,219 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/coordinate_parser.dart'; + +void main() { + group('CoordinateParser.parse', () { + test('parses positive and negative decimal pairs', () { + const inputs = [ + ('37.7749,-122.4194', 37.7749, -122.4194), + ('38.722,-9.139', 38.722, -9.139), + ('-33.86882, 151.20929', -33.86882, 151.20929), + ('51.5074, -0.1278', 51.5074, -0.1278), + ('0.0, 0.0', 0.0, 0.0), + ('45.515232, -122.678385', 45.515232, -122.678385), + ('37.77491234, -122.41945678', 37.77491234, -122.41945678), + ]; + + for (final (text, expectedLat, expectedLon) in inputs) { + final parsed = CoordinateParser.parse(text); + expect(parsed, hasLength(1), reason: 'Failed for "$text"'); + expect(parsed.first.latitude, closeTo(expectedLat, 1e-12)); + expect(parsed.first.longitude, closeTo(expectedLon, 1e-12)); + expect(parsed.first.rawText, text); + expect(parsed.first.start, 0); + expect(parsed.first.end, text.length); + } + }); + + test('parses explicit + signs and optional whitespace after comma', () { + final parsed = CoordinateParser.parse( + 'Meet at +37.7749,+122.4194 or +45.5152,\t-122.6784', + ); + expect(parsed, hasLength(2)); + expect(parsed[0].rawText, '+37.7749,+122.4194'); + expect(parsed[0].latitude, 37.7749); + expect(parsed[0].longitude, 122.4194); + expect(parsed[1].rawText, '+45.5152,\t-122.6784'); + expect(parsed[1].latitude, 45.5152); + expect(parsed[1].longitude, -122.6784); + }); + + test('accepts WGS84 boundary coordinates and rejects out-of-range', () { + final validBounds = CoordinateParser.parse( + '90.0, 180.0 and -90.0, -180.0', + ); + expect(validBounds, hasLength(2)); + expect(validBounds[0].latitude, 90.0); + expect(validBounds[0].longitude, 180.0); + expect(validBounds[1].latitude, -90.0); + expect(validBounds[1].longitude, -180.0); + + const invalidBounds = [ + '90.0001, 0.0', + '-90.1, 0.0', + '0.0, 180.0001', + '0.0, -180.1', + '990.0, -180.0', + '123.45, 67.89', + ]; + for (final text in invalidBounds) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should reject "$text"', + ); + } + }); + + test('rejects plain integer pairs and mixed integer/decimal pairs', () { + const invalid = [ + '1,2', + '10, 20', + '-45, 122', + '37,-122.4194', + '37.7749,-122', + ]; + for (final text in invalid) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should reject "$text"', + ); + } + }); + + test('rejects version numbers and digits inside words or identifiers', () { + const invalid = [ + '1.2.3,4.5', + '1.2,3.4.5', + '1.2, 3.4.5', + '1.2.3, 4.5.6', + 'v1.2,3.4', + 'foo37.7749,-122.4194', + '37.7749,-122.4194bar', + 'id_37.7749,-122.4194', + '37.7749,-122.4194_end', + '--37.7749,-122.4194', + '+-37.7749,-122.4194', + '1.2,3.4-5', + ]; + for (final text in invalid) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should reject "$text"', + ); + } + }); + + test('handles punctuation boundaries around coordinates', () { + const text = + 'Camp (37.7749, -122.4194), ridge [45.5152,-122.6784], end 38.722,-9.139.'; + final parsed = CoordinateParser.parse(text); + expect(parsed, hasLength(3)); + expect(parsed[0].rawText, '37.7749, -122.4194'); + expect(text.substring(parsed[0].start, parsed[0].end), parsed[0].rawText); + expect(parsed[1].rawText, '45.5152,-122.6784'); + expect(text.substring(parsed[1].start, parsed[1].end), parsed[1].rawText); + expect(parsed[2].rawText, '38.722,-9.139'); + expect(text.substring(parsed[2].start, parsed[2].end), parsed[2].rawText); + }); + + test('parses multiple coordinates and #wardriving messages', () { + const wardriving = + '#wardriving 37.7749,-122.4194 SNR: 8.5dB -> (37.7812, -122.4111) ' + 'and 38.722,-9.139, 51.5074, -0.1278'; + final parsed = CoordinateParser.parse(wardriving); + expect(parsed, hasLength(4)); + expect(parsed.map((c) => c.rawText).toList(), [ + '37.7749,-122.4194', + '37.7812, -122.4111', + '38.722,-9.139', + '51.5074, -0.1278', + ]); + }); + + test('does not misparse coordinates inside URLs or emails', () { + const urlOnly = [ + 'https://maps.google.com/?q=37.7749,-122.4194', + 'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194', + 'https://example.com/@37.7749,-122.4194,15z', + 'geo:37.7749,-122.4194', + 'maps.google.com/?q=37.7749,-122.4194', + ]; + for (final text in urlOnly) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should not parse coordinate inside "$text"', + ); + } + + const mixed = + 'Route https://maps.google.com/?q=10.0,20.0 meet at 37.7749, -122.4194'; + final parsed = CoordinateParser.parse(mixed); + expect(parsed, hasLength(1)); + expect(parsed.first.rawText, '37.7749, -122.4194'); + + final elements = CoordinateParser.linkifyWithCoordinates(mixed); + expect(elements.whereType(), hasLength(1)); + expect(elements.whereType(), hasLength(1)); + }); + }); + + group('buildExternalMapUri', () { + test('builds platform-appropriate map URIs', () { + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.android, + isWeb: false, + ).toString(), + 'geo:37.7749,-122.4194?q=37.7749,-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.iOS, + isWeb: false, + ).toString(), + 'https://maps.apple.com/?ll=37.7749,-122.4194&q=37.7749,-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.macOS, + isWeb: false, + ).toString(), + 'https://maps.apple.com/?ll=37.7749,-122.4194&q=37.7749,-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.linux, + isWeb: false, + ).toString(), + 'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.windows, + isWeb: false, + ).toString(), + 'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194', + ); + expect( + buildExternalMapUri(-0.0, -0.0, isWeb: true).toString(), + 'https://www.openstreetmap.org/?mlat=0.0&mlon=0.0#map=16/0.0/0.0', + ); + }); + }); +} diff --git a/test/screens/coordinate_messages_test.dart b/test/screens/coordinate_messages_test.dart new file mode 100644 index 00000000..2d5958ef --- /dev/null +++ b/test/screens/coordinate_messages_test.dart @@ -0,0 +1,484 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/screens/coordinate_map_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/utils/platform_info.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +(MeshCoreConnector, List)? _shared; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync( + 'coordinate_messages_test', + ); + String? copiedText; + final launchedUrls = []; + + setUpAll(() async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + copiedText = + (call.arguments as Map)['text'] as String?; + } + return null; + }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/url_launcher'), + (call) async { + if (call.method == 'launch' || call.method == 'launchUrl') { + final args = call.arguments as Map; + launchedUrls.add(args['url'] as String); + return true; + } + if (call.method == 'canLaunch') { + return true; + } + return true; + }, + ); + + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDownAll(() { + _shared = null; + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + setUp(() { + copiedText = null; + launchedUrls.clear(); + }); + + /// Finds the global center of the first substring matching [target] inside + /// a [RenderParagraph] (mobile) or [RenderEditable] (desktop). + Offset findSpanOffset(WidgetTester tester, String target) { + for (final render in tester.renderObjectList( + find.byType(RichText), + )) { + final plain = render.text.toPlainText(); + final idx = plain.indexOf(target); + if (idx < 0) continue; + final boxes = render.getBoxesForSelection( + TextSelection(baseOffset: idx, extentOffset: idx + target.length), + ); + if (boxes.isNotEmpty) { + final localCenter = boxes.first.toRect().center; + return render.localToGlobal(localCenter); + } + } + for (final state in tester.stateList( + find.byType(EditableText), + )) { + final editable = state.renderEditable; + final plain = editable.plainText; + final idx = plain.indexOf(target); + if (idx < 0) continue; + final boxes = editable.getEndpointsForSelection( + TextSelection(baseOffset: idx, extentOffset: idx + target.length), + ); + if (boxes.isNotEmpty) { + final first = boxes.first.point; + final last = boxes.last.point; + final localCenter = Offset((first.dx + last.dx) / 2, first.dy - 6); + return editable.localToGlobal(localCenter); + } + } + fail('Could not locate rendered span for "$target"'); + } + + for (final isDesktop in [false, true]) { + final platformLabel = isDesktop ? 'desktop' : 'phone'; + + testWidgets( + 'DM message with URL and coordinate: tap opens map, Back preserves scroll, ' + 'long-press shows menu, non-coordinate gestures preserved ($platformLabel)', + (tester) async { + PlatformInfo.debugIsDesktopOverride = isDesktop; + addTearDown(() => PlatformInfo.debugIsDesktopOverride = null); + + final (connector, providers) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere( + (c) => c.type == advTypeChat, + ); + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + const coord = '37.7749, -122.4194'; + const url = 'https://example.com/trail'; + const messageText = 'Check $url and meet at $coord soon'; + + await tester.runAsync(() async { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: messageText, + timestampSecs: nowSecs - 60, + ), + ); + for (var i = 0; i < 18; i++) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Filler message #$i', + timestampSecs: nowSecs - 30 + i, + ), + ); + } + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Reply sent at 45.5152, -122.6784', + timestampSecs: nowSecs, + ), + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + await _pumpApp(tester, providers, ChatScreen(contact: contact)); + + final scrollable = tester.widget( + find.byType(Scrollable).first, + ); + final controller = scrollable.controller!; + final targetFinder = find.textContaining(coord, findRichText: true); + if (targetFinder.evaluate().isEmpty) { + await tester.dragUntilVisible( + targetFinder, + find.byType(Scrollable).first, + const Offset(0, 200), + maxIteration: 30, + ); + } + await Scrollable.ensureVisible( + tester.element(targetFinder.first), + alignment: 0.5, + ); + await _settle(tester); + final savedOffset = controller.offset; + expect(savedOffset, greaterThan(0)); + + // 1. Tap coordinate -> opens CoordinateMapScreen with pin + label + centered AppBar. + final coordCenter = findSpanOffset(tester, coord); + await tester.tapAt(coordCenter); + await _settle(tester); + + expect(find.byType(CoordinateMapScreen), findsOneWidget); + expect(find.text(coord), findsOneWidget); + final appBar = tester.widget(find.byType(AppBar)); + expect(appBar.centerTitle, isTrue); + final flutterMap = tester.widget(find.byType(FlutterMap)); + expect( + flutterMap.options.initialCenter.latitude, + closeTo(37.7749, 1e-6), + ); + expect( + flutterMap.options.initialCenter.longitude, + closeTo(-122.4194, 1e-6), + ); + expect(find.byIcon(Icons.location_on), findsOneWidget); + + // 2. Pressing Back returns to exact same chat and scroll position. + await tester.pageBack(); + await _settle(tester); + expect(find.byType(CoordinateMapScreen), findsNothing); + expect(find.byType(ChatScreen), findsOneWidget); + expect(controller.offset, closeTo(savedOffset, 1.0)); + + // 3. Long-press coordinate -> opens Copy & Open in maps sheet (NOT bubble menu). + await tester.longPressAt(findSpanOffset(tester, coord)); + await _settle(tester); + expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget); + expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget); + expect(find.text(_l10n.chat_reply), findsNothing); + + // Copy location writes to clipboard and shows snackbar. + await tester.tap(find.text(_l10n.coordinate_copyLocation)); + await _settle(tester); + expect(copiedText, coord); + expect(find.text(_l10n.coordinate_copied), findsOneWidget); + + // Re-open long-press sheet and tap Open in maps. + await tester.longPressAt(findSpanOffset(tester, coord)); + await _settle(tester); + await tester.tap(find.text(_l10n.coordinate_openInMaps)); + await _settle(tester); + expect(launchedUrls, isNotEmpty); + expect(launchedUrls.last, contains('37.7749')); + expect(launchedUrls.last, contains('-122.4194')); + + // 4. Tapping URL still opens existing URL confirmation dialog. + await tester.tapAt(findSpanOffset(tester, url)); + await _settle(tester); + expect(find.text(_l10n.chat_openLink), findsOneWidget); + await tester.tap(find.text(_l10n.common_cancel)); + await _settle(tester); + + // 5. Long-pressing non-coordinate text in same message opens bubble actions. + if (!isDesktop) { + await tester.longPressAt(findSpanOffset(tester, 'Check')); + await _settle(tester); + expect(find.text(_l10n.chat_addReaction), findsOneWidget); + Navigator.of(tester.element(find.text(_l10n.chat_addReaction))).pop(); + await _settle(tester); + } + + await _tearDown(tester); + }, + ); + } + + testWidgets( + 'Channel messages render coordinates, support tap/long-press, and fit 320dp @ 1.3x & 2.0x', + (tester) async { + PlatformInfo.debugIsDesktopOverride = false; + addTearDown(() => PlatformInfo.debugIsDesktopOverride = null); + + final (connector, providers) = _shared ??= await _connect(tester); + final channel = connector.channels.first; + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + const channelCoord = '-33.86882, 151.20929'; + const channelMsg = + '#wardriving https://meshcore.co.uk at ($channelCoord) SNR 7.5dB'; + + await tester.runAsync(() async { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: channelMsg, + timestampSecs: nowSecs - 30, + ), + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + final customTheme = MeshTheme.fromCustom( + CustomTheme( + id: 'test-forest', + name: 'Forest', + background: const Color(0xFF0E1A13), + accent: const Color(0xFF4ADE80), + ), + ); + + for (final scale in [1.3, 2.0]) { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final overflows = []; + final previousError = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (text.contains('overflowed')) { + overflows.add(text.split('\n').first); + } else { + previousError?.call(details); + } + }; + addTearDown(() => FlutterError.onError = previousError); + + await _pumpApp( + tester, + providers, + ChannelChatScreen(channel: channel), + theme: customTheme, + textScaler: TextScaler.linear(scale), + ); + + final coordFinder = find.textContaining( + channelCoord, + findRichText: true, + ); + if (coordFinder.evaluate().isEmpty) { + await tester.dragUntilVisible( + coordFinder, + find.byType(Scrollable).first, + const Offset(0, 200), + maxIteration: 30, + ); + } + await Scrollable.ensureVisible( + tester.element(coordFinder.first), + alignment: 0.5, + ); + await _settle(tester); + + // Long-press coordinate in channel message -> bottom sheet fits 320dp without overflow. + await tester.longPressAt(findSpanOffset(tester, channelCoord)); + await _settle(tester); + expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget); + expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget); + Navigator.of( + tester.element(find.text(_l10n.coordinate_copyLocation)), + ).pop(); + await _settle(tester); + + // Tap coordinate -> CoordinateMapScreen fits 320dp without overflow. + await tester.tapAt(findSpanOffset(tester, channelCoord)); + await _settle(tester); + expect(find.byType(CoordinateMapScreen), findsOneWidget); + + // Verify 48dp touch targets on CoordinateMapScreen controls & AppBar buttons. + for (final iconButton in tester.widgetList( + find.byType(IconButton), + )) { + final box = tester.renderObject(find.byWidget(iconButton)); + expect(box.size.width, greaterThanOrEqualTo(48)); + expect(box.size.height, greaterThanOrEqualTo(48)); + } + + await tester.pageBack(); + await _settle(tester); + FlutterError.onError = previousError; + expect(overflows, isEmpty); + } + + await _tearDown(tester); + }, + ); +} + +Future _pumpApp( + WidgetTester tester, + List providers, + Widget home, { + ThemeData? theme, + TextScaler textScaler = TextScaler.noScaling, +}) async { + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: theme ?? MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + home: home, + ), + ), + ); + await _settle(tester); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || + connector.channels.isEmpty || + !connector.channelMapConfirmed) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/screens/small_screen_layout_test.dart b/test/screens/small_screen_layout_test.dart index 1d4e40d9..e85b541e 100644 --- a/test/screens/small_screen_layout_test.dart +++ b/test/screens/small_screen_layout_test.dart @@ -26,6 +26,7 @@ import 'package:meshcore_open/screens/chat_screen.dart'; import 'package:meshcore_open/screens/chrome_required_screen.dart'; import 'package:meshcore_open/screens/companion_radio_stats_screen.dart'; import 'package:meshcore_open/screens/contacts_screen.dart'; +import 'package:meshcore_open/screens/coordinate_map_screen.dart'; import 'package:meshcore_open/screens/discovery_screen.dart'; import 'package:meshcore_open/screens/line_of_sight_map_screen.dart'; import 'package:meshcore_open/screens/map_cache_screen.dart'; @@ -223,6 +224,11 @@ final Map _screens = { LineOfSightEndpoint(label: 'B', point: LatLng(45.6, -122.7)), ], ), + 'CoordinateMap': (_) => const CoordinateMapScreen( + latitude: 45.515232, + longitude: -122.678385, + label: '45.515232, -122.678385', + ), }; void main() { diff --git a/test/widgets/translated_message_content_test.dart b/test/widgets/translated_message_content_test.dart index 118a194e..4af6feb4 100644 --- a/test/widgets/translated_message_content_test.dart +++ b/test/widgets/translated_message_content_test.dart @@ -1,16 +1,23 @@ import 'package:flutter/material.dart'; -import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/link_handler.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/mesh_ui.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; import 'package:meshcore_open/widgets/translated_message_content.dart'; -double _renderedScaleFactor(WidgetTester tester) { - final linkify = find.byType(Linkify); - if (linkify.evaluate().isNotEmpty) { - return tester.widget(linkify.first).textScaleFactor; - } +List _renderedScaleFactors(WidgetTester tester) { + final editables = tester + .stateList(find.byType(EditableText)) + .map((s) => s.renderEditable.textScaler.scale(16) / 16) + .toList(); + if (editables.isNotEmpty) return editables; return tester - .widget(find.byType(SelectableLinkify).first) - .textScaleFactor; + .renderObjectList(find.byType(RichText)) + .map((p) => p.textScaler.scale(16) / 16) + .toList(); } Future _pump(WidgetTester tester, TextScaler scaler) { @@ -20,7 +27,7 @@ Future _pump(WidgetTester tester, TextScaler scaler) { data: MediaQueryData(textScaler: scaler), child: const Scaffold( body: TranslatedMessageContent( - displayText: 'hello https://example.com', + displayText: 'hello https://example.com at 37.7749, -122.4194', originalText: 'bonjour', style: TextStyle(fontSize: 16), ), @@ -33,23 +40,62 @@ Future _pump(WidgetTester tester, TextScaler scaler) { void main() { testWidgets('message body follows the system text scale', (tester) async { await _pump(tester, TextScaler.noScaling); - expect(_renderedScaleFactor(tester), 1.0); + expect(_renderedScaleFactors(tester), everyElement(1.0)); await _pump(tester, const TextScaler.linear(2)); - expect(_renderedScaleFactor(tester), 2.0); + expect(_renderedScaleFactors(tester), everyElement(2.0)); }); testWidgets('original and translated text both scale', (tester) async { await _pump(tester, const TextScaler.linear(1.5)); - final factors = [ - ...tester - .widgetList(find.byType(Linkify)) - .map((w) => w.textScaleFactor), - ...tester - .widgetList(find.byType(SelectableLinkify)) - .map((w) => w.textScaleFactor), - ]; + final factors = _renderedScaleFactors(tester); expect(factors, hasLength(2)); expect(factors, everyElement(1.5)); }); + + testWidgets( + 'coordinate style meets WCAG AA contrast across light, dark, and custom themes', + (tester) async { + final customForest = CustomTheme( + id: 'forest', + name: 'Forest', + background: const Color(0xFF0E1A13), + accent: const Color(0xFF4ADE80), + ); + final themes = [ + MeshTheme.light(), + MeshTheme.dark(), + MeshTheme.fromCustom(customForest), + ]; + + for (final theme in themes) { + for (final isOutgoing in [false, true]) { + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Builder( + builder: (context) { + final colors = MessageBubbleColors.of( + context, + isOutgoing: isOutgoing, + ); + final coordStyle = LinkHandler.defaultCoordinateStyle( + context, + TextStyle(color: colors.text, fontSize: 14), + backgroundColor: colors.background, + ); + expect(coordStyle.decoration, TextDecoration.underline); + expect( + meshContrastRatio(coordStyle.color!, colors.background), + greaterThanOrEqualTo(4.5), + ); + return const SizedBox.shrink(); + }, + ), + ), + ); + } + } + }, + ); } diff --git a/untranslated.json b/untranslated.json index 943fa85a..c7d4d570 100644 --- a/untranslated.json +++ b/untranslated.json @@ -51,7 +51,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "cs": [ @@ -106,7 +110,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "de": [ @@ -161,7 +169,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "es": [ @@ -216,7 +228,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "fr": [ @@ -271,7 +287,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "hu": [ @@ -326,7 +346,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "it": [ @@ -381,7 +405,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "ja": [ @@ -436,7 +464,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "ko": [ @@ -491,7 +523,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "nl": [ @@ -546,7 +582,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "pl": [ @@ -601,7 +641,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "pt": [ @@ -656,7 +700,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "pt_PT": [ @@ -711,7 +759,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "ru": [ @@ -766,7 +818,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "sk": [ @@ -821,7 +877,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "sl": [ @@ -876,7 +936,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "sv": [ @@ -931,7 +995,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "uk": [ @@ -986,7 +1054,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "zh": [ @@ -1041,6 +1113,10 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ] } From 11345d3bba9a4e988949f1d131c0b04544c3d183 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:14:33 -0700 Subject: [PATCH 36/50] Preserve link recognizers across rebuilds and document coordinates --- documentation/channels.md | 4 +- documentation/chat-and-messaging.md | 34 ++++- documentation/map-and-location.md | 6 +- lib/helpers/link_handler.dart | 69 +++++---- test/screens/coordinate_messages_test.dart | 165 +++++++++++++++++++++ 5 files changed, 242 insertions(+), 36 deletions(-) diff --git a/documentation/channels.md b/documentation/channels.md index bc6994f7..6f324f7d 100644 --- a/documentation/channels.md +++ b/documentation/channels.md @@ -101,7 +101,7 @@ Messages also show a region label when known, independently of message tracing. ### Message Types in Chat -- **Plain text** with linkified URLs +- **Plain text** with linkified URLs and interactive decimal GPS coordinates (tap to open the **Location** map, long-press for **Copy location** / **Open in maps**; see [Inline GPS Coordinates](chat-and-messaging.md#inline-gps-coordinates)) - **GIFs** (`g:{gifId}`) rendered inline via Giphy CDN - **Location pins** (`m:{lat},{lon}|{label}|`) shown as tappable location cards - **Mesh images** sent as GRP_DATA chunks and reconstructed locally ([setup and limitations](image-messages.md)) @@ -144,6 +144,8 @@ Where your radio only hears nearby repeaters, turn on **Also count different nea | Mark as Unread | Incoming messages only | Marks this message and all subsequent incoming messages as unread | | Delete | All messages | Removes locally (not from mesh) | +Long-pressing directly on a detected GPS coordinate opens the coordinate action sheet (**Copy location** and **Open in maps**) instead of this message menu; long-press non-coordinate text in the message (or right-click on desktop) for channel message actions. + ## Communities Communities are a layer above channels that provide a private namespace. diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 175eaabb..40826682 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -35,7 +35,7 @@ Below the app bar, above the messages, a strip shows **Compression: Off**, **SMA - **Incoming messages**: Left-aligned, grey background with a colored avatar (initial letter or first emoji of sender name; color is deterministic from a hash of the sender name) - Long-press a message and choose **Bookmark** to show a yellow bookmark on the bubble. **Show bookmarks** in the chat menu toggles a filter for bookmarked messages; use **Bookmarks** in the Channels screen menu to browse saved messages, including those from deleted contacts or channels. From the bookmarks list, copy a message with its copy button. It is ordered oldest-to-newest and opens at the newest message. The Export screen can save or share a dated Markdown file, grouped by contact and then channel, with linked URLs and URL-image embeds. Links remain tappable, and supported URL-image previews are shown when **Load images from links** is enabled in App Settings. - Bubble width capped at 72% of screen width -- Hyperlinks rendered as tappable green underlined text +- Hyperlinks rendered as tappable underlined text; inline decimal GPS coordinates are rendered as bold underlined links (see [Inline GPS Coordinates](#inline-gps-coordinates)) - Message text follows the system font size (Android/iOS accessibility text size); pinch-to-zoom scales on top of it - **Pinch-to-zoom**: Two-finger zoom (0.8x–1.8x) and double-tap to reset - **Jump to bottom**: Floating button appears when scrolled away from the bottom @@ -61,12 +61,40 @@ The composer is a rounded bubble at the bottom of the chat with one round button | Type | Wire Format | Display | |---|---|---| -| Plain text | Raw UTF-8 string | Inline text with link detection | +| Plain text | Raw UTF-8 string | Inline text with URL and decimal coordinate detection | | URL image preview | Image URL in text (per-contact opt-in; requires internet) | Downloaded inline preview | | GIF | `g:` | Inline GIF image from Giphy CDN | | Location pin | `m:,\|