From 7bb9def62804de81217a23dd989d97d77ef7e5c1 Mon Sep 17 00:00:00 2001 From: Juraj Bednar Date: Wed, 18 Nov 2026 14:31:35 +0100 Subject: [PATCH 01/14] 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/14] 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/14] 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/14] 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/14] 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/14] 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 ffbb61bc3d443cccb33c594840249a3d3cccdc23 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Fri, 20 Nov 2026 16:04:50 -0700 Subject: [PATCH 07/14] 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 9ffdbaae09e19f7bb019c47e2fe6f0b2995cb84b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 21 Nov 2026 00:05:39 +0000 Subject: [PATCH 08/14] 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 09/14] 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 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 10/14] 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 11/14] 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 12/14] 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 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 13/14] 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 14/14] 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')); + }); +}