From 25c65bd2b1b84ec6db77f6505d86084dda355036 Mon Sep 17 00:00:00 2001 From: ericz Date: Fri, 10 Apr 2026 22:58:57 +0200 Subject: [PATCH 01/28] Cherry-Pick of first commit of PR #373 --- lib/connector/meshcore_connector.dart | 20 ++ lib/l10n/app_bg.arb | 35 ++++ lib/l10n/app_de.arb | 35 ++++ lib/l10n/app_en.arb | 35 ++++ lib/l10n/app_es.arb | 35 ++++ lib/l10n/app_fr.arb | 35 ++++ lib/l10n/app_hu.arb | 35 ++++ lib/l10n/app_it.arb | 35 ++++ lib/l10n/app_ja.arb | 35 ++++ lib/l10n/app_ko.arb | 35 ++++ lib/l10n/app_localizations.dart | 42 ++++ lib/l10n/app_localizations_bg.dart | 30 +++ lib/l10n/app_localizations_de.dart | 30 +++ lib/l10n/app_localizations_en.dart | 30 +++ lib/l10n/app_localizations_es.dart | 30 +++ lib/l10n/app_localizations_fr.dart | 30 +++ lib/l10n/app_localizations_hu.dart | 30 +++ lib/l10n/app_localizations_it.dart | 30 +++ lib/l10n/app_localizations_ja.dart | 29 +++ lib/l10n/app_localizations_ko.dart | 29 +++ lib/l10n/app_localizations_nl.dart | 30 +++ lib/l10n/app_localizations_pl.dart | 30 +++ lib/l10n/app_localizations_pt.dart | 30 +++ lib/l10n/app_localizations_ru.dart | 31 +++ lib/l10n/app_localizations_sk.dart | 30 +++ lib/l10n/app_localizations_sl.dart | 30 +++ lib/l10n/app_localizations_sv.dart | 30 +++ lib/l10n/app_localizations_uk.dart | 30 +++ lib/l10n/app_localizations_zh.dart | 29 +++ lib/l10n/app_nl.arb | 35 ++++ lib/l10n/app_pl.arb | 41 +++- lib/l10n/app_pt.arb | 35 ++++ lib/l10n/app_ru.arb | 41 +++- lib/l10n/app_sk.arb | 35 ++++ lib/l10n/app_sl.arb | 35 ++++ lib/l10n/app_sv.arb | 41 +++- lib/l10n/app_uk.arb | 35 ++++ lib/l10n/app_zh.arb | 35 ++++ lib/models/contact.dart | 2 - lib/screens/discovery_screen.dart | 187 +++++++++++++++++- lib/storage/contact_discovery_store.dart | 50 +++++ linux/flutter/generated_plugin_registrant.cc | 4 + linux/flutter/generated_plugins.cmake | 2 + macos/Flutter/GeneratedPluginRegistrant.swift | 2 + pubspec.yaml | 1 + .../flutter/generated_plugin_registrant.cc | 3 + windows/flutter/generated_plugins.cmake | 2 + 47 files changed, 1475 insertions(+), 26 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 538ee38a..2cf6abca 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -368,6 +368,26 @@ class MeshCoreConnector extends ChangeNotifier { return List.unmodifiable(_discoveredContacts); } + String exportDiscoveredContactsJson() { + return _discoveryContactStore.exportContactsJson(_discoveredContacts); + } + + Future importDiscoveredContactsJson(String json) async { + final newCount = _discoveryContactStore.importContactsJson( + json: json, + existingContacts: _discoveredContacts, + knownContactKeys: _knownContactKeys, + ); + + if (newCount == 0 && _discoveredContacts.isEmpty) { + return 0; + } + + await _persistDiscoveredContacts(); + notifyListeners(); + return newCount; + } + List get channels => List.unmodifiable(_channels); bool get isConnected => _state == MeshCoreConnectionState.connected; bool get isLoadingContacts => _isLoadingContacts; diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 45536cf6..6bf82db7 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_copyContact": "Копирай контакт в клипборда", "discoveredContacts_deleteContact": "Изтрий контакт", "discoveredContacts_addContact": "Добави контакт", + "discoveredContacts_export": "Експортирай откритите контакти", + "discoveredContacts_import": "Импортирай откритите контакти", + "discoveredContacts_exported": "Откритите контакти са експортирани в {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Неуспешно експортиране на откритите контакти: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Импортирани са {count} открити контакта.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Във файла за импортиране не са намерени контакти.", + "discoveredContacts_importFailed": "Неуспешно импортиране на откритите контакти: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Когато списъкът с контакти е пълен, най-старият неключов контакт ще бъде заменен.", "discoveredContacts_deleteContactAll": "Изтриване на Всички Открити Контакти", "discoveredContacts_deleteContactAllContent": "Сигурни ли сте, че искате да изтриете всички открити контакти?", diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 7f491d4f..2ffd399b 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1944,6 +1944,41 @@ "common_deleteAll": "Alles löschen", "discoveredContacts_deleteContactAllContent": "Sind Sie sicher, dass Sie alle gefundenen Kontakte löschen möchten?", "discoveredContacts_deleteContactAll": "Alle entdeckten Kontakte löschen", + "discoveredContacts_export": "Entdeckte Kontakte exportieren", + "discoveredContacts_import": "Entdeckte Kontakte importieren", + "discoveredContacts_exported": "Entdeckte Kontakte exportiert nach {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Export von entdeckten Kontakten fehlgeschlagen: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} entdeckte Kontakte importiert.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Keine Kontakte in Importdatei gefunden.", + "discoveredContacts_importFailed": "Import von entdeckten Kontakten fehlgeschlagen: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "map_showGuessedLocations": "Zeige die vermuteten Knotenpositionen", "map_guessedLocation": "Geschätzter Ort", "usbScreenSubtitle": "Wählen Sie ein erkannten serielles Gerät aus und verbinden Sie es direkt mit Ihrem MeshCore-Knoten.", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 456fab56..af2fd917 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2137,6 +2137,41 @@ "contacts_invalidAdvertFormat": "Invalid contact data", "contacts_contactImported": "Contact has been imported.", "contacts_contactImportFailed": "Failed to import contact.", + "discoveredContacts_export": "Export discovered contacts", + "discoveredContacts_import": "Import discovered contacts", + "discoveredContacts_exported": "Exported discovered contacts to {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Failed to export discovered contacts: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Imported {count} discovered contacts.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "No contacts found in import file.", + "discoveredContacts_importFailed": "Failed to import discovered contacts: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contacts_zeroHopAdvert": "Zero Hop Advert", "contacts_floodAdvert": "Flood Advert", "contacts_copyAdvertToClipboard": "Copy Advert to Clipboard", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index d4cf27da..d43f9248 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1944,6 +1944,41 @@ "common_deleteAll": "Eliminar todo", "discoveredContacts_deleteContactAll": "Eliminar Todos los Contactos Descubiertos", "discoveredContacts_deleteContactAllContent": "¿Está seguro de que desea eliminar todos los contactos descubiertos!", + "discoveredContacts_export": "Exportar contactos descubiertos", + "discoveredContacts_import": "Importar contactos descubiertos", + "discoveredContacts_exported": "Contactos descubiertos exportados a {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Error al exportar contactos descubiertos: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} contactos descubiertos importados.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "No se encontraron contactos en el archivo de importación.", + "discoveredContacts_importFailed": "Error al importar contactos descubiertos: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "map_guessedLocation": "Ubicación estimada", "map_showGuessedLocations": "Mostrar las ubicaciones estimadas de los nodos.", "usbScreenTitle": "Conecte mediante USB", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 7817c20d..73a2fce0 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1916,6 +1916,41 @@ "common_deleteAll": "Supprimer tout", "discoveredContacts_deleteContactAll": "Supprimer tous les contacts découverts", "discoveredContacts_deleteContactAllContent": "Êtes-vous sûr de vouloir supprimer tous les contacts découverts ?", + "discoveredContacts_export": "Exporter les contacts découverts", + "discoveredContacts_import": "Importer les contacts découverts", + "discoveredContacts_exported": "Contacts découverts exportés vers {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Impossible d'exporter les contacts découverts: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} contacts découverts importés.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Aucun contact trouvé dans le fichier d'importation.", + "discoveredContacts_importFailed": "Impossible d'importer les contacts découverts: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "map_showGuessedLocations": "Afficher les emplacements des nœuds estimés", "map_guessedLocation": "Lieu deviné", "connectionChoiceUsbLabel": "USB", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 97426183..9c767398 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -2037,6 +2037,41 @@ "discoveredContacts_deleteContact": "Törölj a feltalált kapcsolatot", "discoveredContacts_deleteContactAll": "Törölj minden megtalált kapcsolatot", "discoveredContacts_deleteContactAllContent": "Biztos, hogy szeretné törölni az összes eddig megtalált kapcsolatot?", + "discoveredContacts_export": "Felfedezett kapcsolatok exportálása", + "discoveredContacts_import": "Felfedezett kapcsolatok importálása", + "discoveredContacts_exported": "A felfedezett kapcsolatok exportálva ide: {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "A felfedezett kapcsolatok exportálása nem sikerült: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} felfedezett kapcsolat importálva.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Az importfájlban nem találhatók kapcsolatok.", + "discoveredContacts_importFailed": "A felfedezett kapcsolatok importálása nem sikerült: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "chat_sendCooldown": "Kérjük, várjon egy pillanatot, mielőtt újra elküldené.", "appSettings_jumpToOldestUnread": "Jelentkezzen az legörebb, olvasatlan üzenetre", "appSettings_jumpToOldestUnreadSubtitle": "Amikor egy új csevet indítunk, amelyben vannak olvashatatlan üzenetek, görgessük a listát, hogy a legelső, olvashatatlan üzenet megjelenjen, nem pedig az utolsó.", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 664bceef..abb67295 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_contactAdded": "Contatto aggiunto", "discoveredContacts_deleteContact": "Elimina Contatto", "discoveredContacts_copyContact": "Copia contatto negli appunti", + "discoveredContacts_export": "Esporta contatti scoperti", + "discoveredContacts_import": "Importa contatti scoperti", + "discoveredContacts_exported": "Contatti scoperti esportati in {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Esportazione dei contatti scoperti non riuscita: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Importati {count} contatti scoperti.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Nessun contatto trovato nel file di importazione.", + "discoveredContacts_importFailed": "Importazione dei contatti scoperti non riuscita: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Quando l'elenco dei contatti è pieno, il contatto più vecchio non tra i preferiti verrà sostituito.", "common_deleteAll": "Elimina tutto", "discoveredContacts_deleteContactAllContent": "Sei sicuro di voler eliminare tutti i contatti scoperti?", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 9d2cef21..f6ab75ca 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -2037,6 +2037,41 @@ "discoveredContacts_deleteContact": "発見された連絡先を削除", "discoveredContacts_deleteContactAll": "発見されたすべての連絡先を削除", "discoveredContacts_deleteContactAllContent": "本当に、見つけたすべての連絡先を削除してもよろしいですか?", + "discoveredContacts_export": "発見済みの連絡先をエクスポート", + "discoveredContacts_import": "発見済みの連絡先をインポート", + "discoveredContacts_exported": "発見済みの連絡先を {path} にエクスポートしました。", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "発見済みの連絡先のエクスポートに失敗しました: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} 件の発見済み連絡先をインポートしました。", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "インポートファイルに連絡先が見つかりませんでした。", + "discoveredContacts_importFailed": "発見済みの連絡先のインポートに失敗しました: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "chat_sendCooldown": "再度送信する前に、しばらくお待ちください。", "appSettings_jumpToOldestUnread": "最も古い未読のメッセージへ移動", "appSettings_jumpToOldestUnreadSubtitle": "未読メッセージがあるチャットを開く際、「最新のメッセージ」ではなく、最初に未読のメッセージまでスクロールしてください。", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index d778429b..c85019f6 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -2037,6 +2037,41 @@ "discoveredContacts_deleteContact": "발견된 연락처 삭제", "discoveredContacts_deleteContactAll": "발견된 모든 연락처 삭제", "discoveredContacts_deleteContactAllContent": "정말로 모든 검색된 연락처를 삭제하시겠습니까?", + "discoveredContacts_export": "발견된 연락처 내보내기", + "discoveredContacts_import": "발견된 연락처 가져오기", + "discoveredContacts_exported": "발견된 연락처를 {path}(으)로 내보냈습니다.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "발견된 연락처 내보내기에 실패했습니다: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "발견된 연락처 {count}개를 가져왔습니다.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "가져오기 파일에서 연락처를 찾을 수 없습니다.", + "discoveredContacts_importFailed": "발견된 연락처 가져오기에 실패했습니다: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "chat_sendCooldown": "다시 보내기 전에 잠시 기다려 주시기 바랍니다.", "appSettings_jumpToOldestUnread": "가장 오래된, 아직 읽지 않은 항목으로 이동", "appSettings_jumpToOldestUnreadSubtitle": "새로운 메시지가 없는 채팅을 열 때, 최신 메시지가 아닌 첫 번째 읽지 않은 메시지로 스크롤하세요.", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 159d755c..84baa5ea 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -6628,6 +6628,48 @@ abstract class AppLocalizations { /// **'Failed to import contact.'** String get contacts_contactImportFailed; + /// No description provided for @discoveredContacts_export. + /// + /// In en, this message translates to: + /// **'Export discovered contacts'** + String get discoveredContacts_export; + + /// No description provided for @discoveredContacts_import. + /// + /// In en, this message translates to: + /// **'Import discovered contacts'** + String get discoveredContacts_import; + + /// No description provided for @discoveredContacts_exported. + /// + /// In en, this message translates to: + /// **'Exported discovered contacts to {path}.'** + String discoveredContacts_exported(String path); + + /// No description provided for @discoveredContacts_exportFailed. + /// + /// In en, this message translates to: + /// **'Failed to export discovered contacts: {error}'** + String discoveredContacts_exportFailed(String error); + + /// No description provided for @discoveredContacts_imported. + /// + /// In en, this message translates to: + /// **'Imported {count} discovered contacts.'** + String discoveredContacts_imported(int count); + + /// No description provided for @discoveredContacts_importNoContacts. + /// + /// In en, this message translates to: + /// **'No contacts found in import file.'** + String get discoveredContacts_importNoContacts; + + /// No description provided for @discoveredContacts_importFailed. + /// + /// In en, this message translates to: + /// **'Failed to import discovered contacts: {error}'** + String discoveredContacts_importFailed(String error); + /// No description provided for @contacts_zeroHopAdvert. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 409803b2..95434f11 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -3846,6 +3846,36 @@ class AppLocalizationsBg extends AppLocalizations { String get contacts_contactImportFailed => 'Контактът не е успешно импортиран.'; + @override + String get discoveredContacts_export => 'Експортирай откритите контакти'; + + @override + String get discoveredContacts_import => 'Импортирай откритите контакти'; + + @override + String discoveredContacts_exported(String path) { + return 'Откритите контакти са експортирани в $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Неуспешно експортиране на откритите контакти: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Импортирани са $count открити контакта.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Във файла за импортиране не са намерени контакти.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Неуспешно импортиране на откритите контакти: $error'; + } + @override String get contacts_zeroHopAdvert => 'Реклама без скок'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 9f06906d..fb634e34 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -3857,6 +3857,36 @@ class AppLocalizationsDe extends AppLocalizations { String get contacts_contactImportFailed => 'Kontakt konnte nicht importiert werden'; + @override + String get discoveredContacts_export => 'Entdeckte Kontakte exportieren'; + + @override + String get discoveredContacts_import => 'Entdeckte Kontakte importieren'; + + @override + String discoveredContacts_exported(String path) { + return 'Entdeckte Kontakte exportiert nach $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Export von entdeckten Kontakten fehlgeschlagen: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count entdeckte Kontakte importiert.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Keine Kontakte in Importdatei gefunden.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Import von entdeckten Kontakten fehlgeschlagen: $error'; + } + @override String get contacts_zeroHopAdvert => 'Zero-Hop-Ankündigung'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 6def06b7..366dc315 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -3780,6 +3780,36 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_contactImportFailed => 'Failed to import contact.'; + @override + String get discoveredContacts_export => 'Export discovered contacts'; + + @override + String get discoveredContacts_import => 'Import discovered contacts'; + + @override + String discoveredContacts_exported(String path) { + return 'Exported discovered contacts to $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Failed to export discovered contacts: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Imported $count discovered contacts.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'No contacts found in import file.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Failed to import discovered contacts: $error'; + } + @override String get contacts_zeroHopAdvert => 'Zero Hop Advert'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index bb4f40e8..b9d61e9e 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -3846,6 +3846,36 @@ class AppLocalizationsEs extends AppLocalizations { String get contacts_contactImportFailed => 'Contacto no se importó correctamente.'; + @override + String get discoveredContacts_export => 'Exportar contactos descubiertos'; + + @override + String get discoveredContacts_import => 'Importar contactos descubiertos'; + + @override + String discoveredContacts_exported(String path) { + return 'Contactos descubiertos exportados a $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Error al exportar contactos descubiertos: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count contactos descubiertos importados.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'No se encontraron contactos en el archivo de importación.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Error al importar contactos descubiertos: $error'; + } + @override String get contacts_zeroHopAdvert => 'Anuncio de Zero Hop'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 44e40657..1872f459 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -3868,6 +3868,36 @@ class AppLocalizationsFr extends AppLocalizations { String get contacts_contactImportFailed => 'Échec de l\'importation du contact.'; + @override + String get discoveredContacts_export => 'Exporter les contacts découverts'; + + @override + String get discoveredContacts_import => 'Importer les contacts découverts'; + + @override + String discoveredContacts_exported(String path) { + return 'Contacts découverts exportés vers $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Impossible d\'exporter les contacts découverts: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count contacts découverts importés.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Aucun contact trouvé dans le fichier d\'importation.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Impossible d\'importer les contacts découverts: $error'; + } + @override String get contacts_zeroHopAdvert => 'Annonce Zero saut'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 298a6fd6..bc58482f 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -3861,6 +3861,36 @@ class AppLocalizationsHu extends AppLocalizations { String get contacts_contactImportFailed => 'Nem sikerült a kapcsolatot importálni.'; + @override + String get discoveredContacts_export => 'Felfedezett kapcsolatok exportálása'; + + @override + String get discoveredContacts_import => 'Felfedezett kapcsolatok importálása'; + + @override + String discoveredContacts_exported(String path) { + return 'A felfedezett kapcsolatok exportálva ide: $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'A felfedezett kapcsolatok exportálása nem sikerült: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count felfedezett kapcsolat importálva.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Az importfájlban nem találhatók kapcsolatok.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'A felfedezett kapcsolatok importálása nem sikerült: $error'; + } + @override String get contacts_zeroHopAdvert => 'Zero Hop reklám'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index e3f7ee58..f37b2c34 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -3851,6 +3851,36 @@ class AppLocalizationsIt extends AppLocalizations { String get contacts_contactImportFailed => 'Contatto non importato con successo.'; + @override + String get discoveredContacts_export => 'Esporta contatti scoperti'; + + @override + String get discoveredContacts_import => 'Importa contatti scoperti'; + + @override + String discoveredContacts_exported(String path) { + return 'Contatti scoperti esportati in $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Esportazione dei contatti scoperti non riuscita: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Importati $count contatti scoperti.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Nessun contatto trovato nel file di importazione.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Importazione dei contatti scoperti non riuscita: $error'; + } + @override String get contacts_zeroHopAdvert => 'Annuncio Zero Hop'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 263a906e..0002ee7b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -3648,6 +3648,35 @@ class AppLocalizationsJa extends AppLocalizations { @override String get contacts_contactImportFailed => '連絡先のインポートに失敗しました。'; + @override + String get discoveredContacts_export => '発見済みの連絡先をエクスポート'; + + @override + String get discoveredContacts_import => '発見済みの連絡先をインポート'; + + @override + String discoveredContacts_exported(String path) { + return '発見済みの連絡先を $path にエクスポートしました。'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return '発見済みの連絡先のエクスポートに失敗しました: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count 件の発見済み連絡先をインポートしました。'; + } + + @override + String get discoveredContacts_importNoContacts => 'インポートファイルに連絡先が見つかりませんでした。'; + + @override + String discoveredContacts_importFailed(String error) { + return '発見済みの連絡先のインポートに失敗しました: $error'; + } + @override String get contacts_zeroHopAdvert => 'ゼロホップ広告'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index f9c0d760..79aad394 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -3650,6 +3650,35 @@ class AppLocalizationsKo extends AppLocalizations { @override String get contacts_contactImportFailed => '연락처를 가져오지 못했습니다.'; + @override + String get discoveredContacts_export => '발견된 연락처 내보내기'; + + @override + String get discoveredContacts_import => '발견된 연락처 가져오기'; + + @override + String discoveredContacts_exported(String path) { + return '발견된 연락처를 $path(으)로 내보냈습니다.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return '발견된 연락처 내보내기에 실패했습니다: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '발견된 연락처 $count개를 가져왔습니다.'; + } + + @override + String get discoveredContacts_importNoContacts => '가져오기 파일에서 연락처를 찾을 수 없습니다.'; + + @override + String discoveredContacts_importFailed(String error) { + return '발견된 연락처 가져오기에 실패했습니다: $error'; + } + @override String get contacts_zeroHopAdvert => '제로 홉 광고'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index ad140bf3..8e173e70 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -3831,6 +3831,36 @@ class AppLocalizationsNl extends AppLocalizations { String get contacts_contactImportFailed => 'Contact kon niet geïmporteerd worden.'; + @override + String get discoveredContacts_export => 'Ontdekte contacten exporteren'; + + @override + String get discoveredContacts_import => 'Ontdekte contacten importeren'; + + @override + String discoveredContacts_exported(String path) { + return 'Ontdekte contacten geëxporteerd naar $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Exporteren van ontdekte contacten mislukt: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count ontdekte contacten geïmporteerd.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Geen contacten gevonden in het importbestand.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Importeren van ontdekte contacten mislukt: $error'; + } + @override String get contacts_zeroHopAdvert => 'Zero Hop Reclame'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 6c7c3696..74721fbb 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -3862,6 +3862,36 @@ class AppLocalizationsPl extends AppLocalizations { String get contacts_contactImportFailed => 'Kontakt nie został zaimportowany.'; + @override + String get discoveredContacts_export => 'Eksportuj odkryte kontakty'; + + @override + String get discoveredContacts_import => 'Importuj odkryte kontakty'; + + @override + String discoveredContacts_exported(String path) { + return 'Wyeksportowano odkryte kontakty do $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Nie udało się wyeksportować odkrytych kontaktów: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Zaimportowano $count odkrytych kontaktów.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Nie znaleziono kontaktów w pliku importu.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Nie udało się zaimportować odkrytych kontaktów: $error'; + } + @override String get contacts_zeroHopAdvert => 'Rozgłoszenie zero-hop'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index e6fd49e3..ab7d83d9 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -3842,6 +3842,36 @@ class AppLocalizationsPt extends AppLocalizations { @override String get contacts_contactImportFailed => 'Contato falhou ao ser importado.'; + @override + String get discoveredContacts_export => 'Exportar contatos descobertos'; + + @override + String get discoveredContacts_import => 'Importar contatos descobertos'; + + @override + String discoveredContacts_exported(String path) { + return 'Contatos descobertos exportados para $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Falha ao exportar contatos descobertos: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return '$count contatos descobertos importados.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Nenhum contato encontrado no arquivo de importação.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Falha ao importar contatos descobertos: $error'; + } + @override String get contacts_zeroHopAdvert => 'Anúncio Zero Hop'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 25452003..0534902c 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -3852,6 +3852,37 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contacts_contactImportFailed => 'Контакт не удалось импортировать'; + @override + String get discoveredContacts_export => + 'Экспортировать обнаруженные контакты'; + + @override + String get discoveredContacts_import => 'Импортировать обнаруженные контакты'; + + @override + String discoveredContacts_exported(String path) { + return 'Обнаруженные контакты экспортированы в $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Не удалось экспортировать обнаруженные контакты: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Импортировано $count обнаруженных контактов.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'В файле импорта не найдены контакты.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Не удалось импортировать обнаруженные контакты: $error'; + } + @override String get contacts_zeroHopAdvert => 'Реклама Zero Hop'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 91461385..95f4de35 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -3827,6 +3827,36 @@ class AppLocalizationsSk extends AppLocalizations { String get contacts_contactImportFailed => 'Kontakt sa nepodarilo importovať.'; + @override + String get discoveredContacts_export => 'Exportovať objavené kontakty'; + + @override + String get discoveredContacts_import => 'Importovať objavené kontakty'; + + @override + String discoveredContacts_exported(String path) { + return 'Objavené kontakty boli exportované do $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Export objavených kontaktov zlyhal: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Bolo importovaných $count objavených kontaktov.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'V importovanom súbore sa nenašli žiadne kontakty.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Import objavených kontaktov zlyhal: $error'; + } + @override String get contacts_zeroHopAdvert => 'Inzerát Zero Hop'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 48103647..896bfb6d 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -3821,6 +3821,36 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_contactImportFailed => 'Kontakt ni bil uspešno uvožen.'; + @override + String get discoveredContacts_export => 'Izvozi odkrite stike'; + + @override + String get discoveredContacts_import => 'Uvozi odkrite stike'; + + @override + String discoveredContacts_exported(String path) { + return 'Odkriti stiki so izvoženi v $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Izvoz odkritih stikov ni uspel: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Uvoženih je bilo $count odkritih stikov.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'V uvozni datoteki ni bilo najdenih stikov.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Uvoz odkritih stikov ni uspel: $error'; + } + @override String get contacts_zeroHopAdvert => 'Reklama brez posrednikov'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 7453c18f..8660b1cb 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -3799,6 +3799,36 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contacts_contactImportFailed => 'Kontakt kunde inte importeras.'; + @override + String get discoveredContacts_export => 'Exportera upptäckta kontakter'; + + @override + String get discoveredContacts_import => 'Importera upptäckta kontakter'; + + @override + String discoveredContacts_exported(String path) { + return 'Upptäckta kontakter exporterades till $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Det gick inte att exportera upptäckta kontakter: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Importerade $count upptäckta kontakter.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'Inga kontakter hittades i importfilen.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Det gick inte att importera upptäckta kontakter: $error'; + } + @override String get contacts_zeroHopAdvert => 'Reklam med nollhopp'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 9c30fd8e..8f58d664 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -3853,6 +3853,36 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_contactImportFailed => 'Контакт не вдалось імпортувати'; + @override + String get discoveredContacts_export => 'Експортувати виявлені контакти'; + + @override + String get discoveredContacts_import => 'Імпортувати виявлені контакти'; + + @override + String discoveredContacts_exported(String path) { + return 'Виявлені контакти експортовано до $path.'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return 'Не вдалося експортувати виявлені контакти: $error'; + } + + @override + String discoveredContacts_imported(int count) { + return 'Імпортовано $count виявлених контактів.'; + } + + @override + String get discoveredContacts_importNoContacts => + 'У файлі імпорту не знайдено контактів.'; + + @override + String discoveredContacts_importFailed(String error) { + return 'Не вдалося імпортувати виявлені контакти: $error'; + } + @override String get contacts_zeroHopAdvert => 'Оголошення без ретрансляції'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d2304a66..b4c18286 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -3551,6 +3551,35 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_contactImportFailed => '导入联系人失败。'; + @override + String get discoveredContacts_export => '导出已发现的联系人'; + + @override + String get discoveredContacts_import => '导入已发现的联系人'; + + @override + String discoveredContacts_exported(String path) { + return '已将已发现的联系人导出到$path。'; + } + + @override + String discoveredContacts_exportFailed(String error) { + return '导出已发现的联系人失败:$error'; + } + + @override + String discoveredContacts_imported(int count) { + return '已导入$count个已发现的联系人。'; + } + + @override + String get discoveredContacts_importNoContacts => '在导入文件中未找到联系人。'; + + @override + String discoveredContacts_importFailed(String error) { + return '导入已发现的联系人失败:$error'; + } + @override String get contacts_zeroHopAdvert => '发送零跳广播'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 7e83215b..3b6d7196 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_Title": "Ontdekte contacten", "discoveredContacts_contactAdded": "Contact toegevoegd", "discoveredContacts_searchHint": "Ontdekte contacten zoeken", + "discoveredContacts_export": "Ontdekte contacten exporteren", + "discoveredContacts_import": "Ontdekte contacten importeren", + "discoveredContacts_exported": "Ontdekte contacten geëxporteerd naar {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Exporteren van ontdekte contacten mislukt: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} ontdekte contacten geïmporteerd.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Geen contacten gevonden in het importbestand.", + "discoveredContacts_importFailed": "Importeren van ontdekte contacten mislukt: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Wanneer de contactenlijst vol is, wordt de oudste niet-favoriete contactpersoon vervangen.", "common_deleteAll": "Alles verwijderen", "discoveredContacts_deleteContactAll": "Verwijder alle ontdekte contacten", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index 4366e273..c25c7856 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -1950,6 +1950,41 @@ "contactsSettings_autoAddSensorsSubtitle": "Zezwól towarzyszowi na automatyczne dodawanie wykrytych czujników.", "discoveredContacts_noMatching": "Brak pasujących kontaktów", "discoveredContacts_deleteContact": "Usuń kontakt", + "discoveredContacts_export": "Eksportuj odkryte kontakty", + "discoveredContacts_import": "Importuj odkryte kontakty", + "discoveredContacts_exported": "Wyeksportowano odkryte kontakty do {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Nie udało się wyeksportować odkrytych kontaktów: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Zaimportowano {count} odkrytych kontaktów.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Nie znaleziono kontaktów w pliku importu.", + "discoveredContacts_importFailed": "Nie udało się zaimportować odkrytych kontaktów: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Gdy lista kontaktów jest pełna, najstarszy nieulubiony kontakt zostanie zastąpiony.", "common_deleteAll": "Usuń wszystko", "discoveredContacts_deleteContactAllContent": "Czy na pewno chcesz usunąć wszystkie znalezione kontakty?", @@ -2180,12 +2215,6 @@ "scanner_linuxPairingPinTitle": "Kod PIN parowania Bluetooth", "repeater_cliQuickClockSync": "Synchronizacja zegara", "repeater_cliQuickDiscovery": "Odkryj Sąsiadów", - "@repeater_clockSyncAfterLogin": { - "description": "Repeater setting: auto sync device clock after successful login" - }, - "@repeater_clockSyncAfterLoginSubtitle": { - "description": "Repeater setting subtitle: describes the clock sync after login behavior" - }, "repeater_clockSyncAfterLogin": "Synchronizacja zegara po zalogowaniu", "repeater_clockSyncAfterLoginSubtitle": "Automatycznie wysyłaj powiadomienie \"synchronizacja zegara\" po pomyślnym zalogowaniu.", "chat_sendMessage": "Wyślij wiadomość", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 6b8abbbc..7efa6fbe 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_deleteContact": "Excluir Contato", "discoveredContacts_contactAdded": "Contato adicionado", "discoveredContacts_addContact": "Adicionar Contato", + "discoveredContacts_export": "Exportar contatos descobertos", + "discoveredContacts_import": "Importar contatos descobertos", + "discoveredContacts_exported": "Contatos descobertos exportados para {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Falha ao exportar contatos descobertos: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "{count} contatos descobertos importados.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Nenhum contato encontrado no arquivo de importação.", + "discoveredContacts_importFailed": "Falha ao importar contatos descobertos: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Quando a lista de contatos estiver cheia, o contato mais antigo não favoritado será substituído.", "common_deleteAll": "Excluir Tudo", "discoveredContacts_deleteContactAll": "Excluir Todos os Contatos Descobertos", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 5d5bcfc3..25b0d75f 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -1081,6 +1081,41 @@ "discoveredContacts_addContact": "Добавить контакт", "discoveredContacts_Title": "Обнаруженные контакты", "discoveredContacts_deleteContact": "Удалить контакт", + "discoveredContacts_export": "Экспортировать обнаруженные контакты", + "discoveredContacts_import": "Импортировать обнаруженные контакты", + "discoveredContacts_exported": "Обнаруженные контакты экспортированы в {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Не удалось экспортировать обнаруженные контакты: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Импортировано {count} обнаруженных контактов.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "В файле импорта не найдены контакты.", + "discoveredContacts_importFailed": "Не удалось импортировать обнаруженные контакты: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Когда список контактов заполнен, будет заменен самый старый контакт, который не находится в избранном.", "common_deleteAll": "Удалить все", "discoveredContacts_deleteContactAllContent": "Вы уверены, что хотите удалить все обнаруженные контакты?", @@ -1311,12 +1346,6 @@ "scanner_linuxPairingPinTitle": "PIN‑код сопряжения Bluetooth", "repeater_cliQuickDiscovery": "Обнаружить Соседей", "repeater_cliQuickClockSync": "Синхронизация часов", - "@repeater_clockSyncAfterLogin": { - "description": "Repeater setting: auto sync device clock after successful login" - }, - "@repeater_clockSyncAfterLoginSubtitle": { - "description": "Repeater setting subtitle: describes the clock sync after login behavior" - }, "repeater_clockSyncAfterLogin": "Синхронизация часов после входа в систему", "repeater_clockSyncAfterLoginSubtitle": "Автоматически отправлять сообщение \"синхронизация времени\" после успешной авторизации.", "chat_sendMessage": "Отправить сообщение", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index 713c3976..b050f9dd 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_Title": "Objavené kontakty", "contactsSettings_overwriteOldestTitle": "Prepísať najstaršie", "discoveredContacts_addContact": "Pridať kontakt", + "discoveredContacts_export": "Exportovať objavené kontakty", + "discoveredContacts_import": "Importovať objavené kontakty", + "discoveredContacts_exported": "Objavené kontakty boli exportované do {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Export objavených kontaktov zlyhal: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Bolo importovaných {count} objavených kontaktov.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "V importovanom súbore sa nenašli žiadne kontakty.", + "discoveredContacts_importFailed": "Import objavených kontaktov zlyhal: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Keď je zoznam kontaktov plný, bude nahradený najstarší neoznačený kontakt.", "discoveredContacts_deleteContactAll": "Zmazať všetky objavené kontakty", "common_deleteAll": "Zmazať všetko", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 00930c85..b1031465 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_Title": "Odkriti stiki", "discoveredContacts_searchHint": "Najdeni stiki po iskanju", "discoveredContacts_deleteContact": "Izbriši stik", + "discoveredContacts_export": "Izvozi odkrite stike", + "discoveredContacts_import": "Uvozi odkrite stike", + "discoveredContacts_exported": "Odkriti stiki so izvoženi v {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Izvoz odkritih stikov ni uspel: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Uvoženih je bilo {count} odkritih stikov.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "V uvozni datoteki ni bilo najdenih stikov.", + "discoveredContacts_importFailed": "Uvoz odkritih stikov ni uspel: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Ko je seznam stikov poln, bo najstarejši nestarševski stik zamenjan.", "common_deleteAll": "Izbriši vse", "discoveredContacts_deleteContactAllContent": "Ste prepričani, da želite izbrisati vse odkrite kontakte?", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 00fd3b08..71254b2b 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -1912,6 +1912,41 @@ "discoveredContacts_contactAdded": "Kontakt tillagd", "discoveredContacts_addContact": "Lägg till kontakt", "discoveredContacts_copyContact": "Kopiera kontakt till urklipp", + "discoveredContacts_export": "Exportera upptäckta kontakter", + "discoveredContacts_import": "Importera upptäckta kontakter", + "discoveredContacts_exported": "Upptäckta kontakter exporterades till {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Det gick inte att exportera upptäckta kontakter: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Importerade {count} upptäckta kontakter.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "Inga kontakter hittades i importfilen.", + "discoveredContacts_importFailed": "Det gick inte att importera upptäckta kontakter: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "När kontaktlistan är full ersätts den äldsta icke-favoriterade kontakten.", "common_deleteAll": "Ta bort alla", "discoveredContacts_deleteContactAllContent": "Är du säker på att du vill ta bort alla upptäckta kontakter?", @@ -2143,12 +2178,6 @@ "scanner_linuxPairingHidePin": "Dölj PIN", "repeater_cliQuickDiscovery": "Upptäck grannar", "repeater_cliQuickClockSync": "Synkronisera klocka", - "@repeater_clockSyncAfterLogin": { - "description": "Repeater setting: auto sync device clock after successful login" - }, - "@repeater_clockSyncAfterLoginSubtitle": { - "description": "Repeater setting subtitle: describes the clock sync after login behavior" - }, "repeater_clockSyncAfterLoginSubtitle": "Automatiskt skicka \"klocksynkronisering\" efter en lyckad inloggning.", "repeater_clockSyncAfterLogin": "Synkronisera klockan efter inloggning", "repeater_guest": "Information om repetorer", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 8330d364..106f2353 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -1922,6 +1922,41 @@ "discoveredContacts_deleteContact": "Видалити контакт", "discoveredContacts_copyContact": "Копіювати контакт у буфер обміну", "discoveredContacts_addContact": "Додати контакт", + "discoveredContacts_export": "Експортувати виявлені контакти", + "discoveredContacts_import": "Імпортувати виявлені контакти", + "discoveredContacts_exported": "Виявлені контакти експортовано до {path}.", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "Не вдалося експортувати виявлені контакти: {error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "Імпортовано {count} виявлених контактів.", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "У файлі імпорту не знайдено контактів.", + "discoveredContacts_importFailed": "Не вдалося імпортувати виявлені контакти: {error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "Коли список контактів заповнений, найстарший контакт без позначки улюбленого буде замінений.", "common_deleteAll": "Видалити все", "discoveredContacts_deleteContactAll": "Видалити всі виявлені контакти", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 1e289315..0cbb3f97 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1917,6 +1917,41 @@ "discoveredContacts_noMatching": "没有匹配的联系人", "discoveredContacts_Title": "已发现的联系人", "discoveredContacts_copyContact": "复制联系人到剪贴板", + "discoveredContacts_export": "导出已发现的联系人", + "discoveredContacts_import": "导入已发现的联系人", + "discoveredContacts_exported": "已将已发现的联系人导出到{path}。", + "@discoveredContacts_exported": { + "placeholders": { + "path": { + "type": "String" + } + } + }, + "discoveredContacts_exportFailed": "导出已发现的联系人失败:{error}", + "@discoveredContacts_exportFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "discoveredContacts_imported": "已导入{count}个已发现的联系人。", + "@discoveredContacts_imported": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "discoveredContacts_importNoContacts": "在导入文件中未找到联系人。", + "discoveredContacts_importFailed": "导入已发现的联系人失败:{error}", + "@discoveredContacts_importFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, "contactsSettings_overwriteOldestSubtitle": "当联系人列表已满时,将替换最老的非收藏联系人。", "common_deleteAll": "删除全部", "discoveredContacts_deleteContactAllContent": "您确定要删除所有发现的联系人吗?", diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 01d10a9c..74f0cd31 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -19,7 +19,6 @@ class Contact { final DateTime lastMessageAt; final DateTime? lastModified; final bool isActive; - final bool wasPulled; final Uint8List? rawPacket; Contact({ @@ -37,7 +36,6 @@ class Contact { this.lastModified, DateTime? lastMessageAt, this.isActive = true, - this.wasPulled = false, this.rawPacket, }) : lastMessageAt = lastMessageAt ?? lastSeen; diff --git a/lib/screens/discovery_screen.dart b/lib/screens/discovery_screen.dart index f9f0e07e..5859f60f 100644 --- a/lib/screens/discovery_screen.dart +++ b/lib/screens/discovery_screen.dart @@ -1,8 +1,13 @@ import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:file_selector/file_selector.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; +import 'package:share_plus/share_plus.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; @@ -66,9 +71,44 @@ class _DiscoveryScreenState extends State { ), centerTitle: true, actions: [ - PopupMenuButton( - itemBuilder: (context) => [ - PopupMenuItem( + PopupMenuButton( + onSelected: (value) { + switch (value) { + case 'export': + unawaited(_exportDiscoveredContacts(context, connector)); + break; + case 'import': + unawaited(_importDiscoveredContacts(context, connector)); + break; + case 'delete_all': + _deleteContacts(context, connector); + break; + } + }, + itemBuilder: (context) => >[ + PopupMenuItem( + value: 'export', + child: Row( + children: [ + const Icon(Icons.upload_file), + const SizedBox(width: 8), + Text(l10n.discoveredContacts_export), + ], + ), + ), + PopupMenuItem( + value: 'import', + child: Row( + children: [ + const Icon(Icons.download), + const SizedBox(width: 8), + Text(l10n.discoveredContacts_import), + ], + ), + ), + const PopupMenuDivider(), + PopupMenuItem( + value: 'delete_all', child: Row( children: [ const Icon(Icons.delete, color: Colors.red), @@ -76,9 +116,6 @@ class _DiscoveryScreenState extends State { Text(context.l10n.discoveredContacts_deleteContactAll), ], ), - onTap: () { - _deleteContacts(context, connector); - }, ), ], icon: const Icon(Icons.more_vert), @@ -270,6 +307,144 @@ class _DiscoveryScreenState extends State { ); } + Future _exportDiscoveredContacts( + BuildContext context, + MeshCoreConnector connector, + ) async { + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + final json = connector.exportDiscoveredContactsJson(); + + try { + const filename = 'meshcore_discovered_contacts.json'; + final bytes = Uint8List.fromList(utf8.encode(json)); + + if (PlatformInfo.isDesktop) { + final location = await getSaveLocation( + suggestedName: filename, + acceptedTypeGroups: [ + const XTypeGroup(label: 'JSON', extensions: ['json']), + ], + ); + if (!mounted) return; + if (location == null) return; + final exportFile = XFile.fromData( + bytes, + mimeType: 'application/json', + name: filename, + ); + await exportFile.saveTo(location.path); + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + content: Text(l10n.discoveredContacts_exported(location.path)), + ), + ); + return; + } + + final tempDir = await getTemporaryDirectory(); + final exportPath = '${tempDir.path}/$filename'; + final exportFile = File(exportPath); + await exportFile.writeAsBytes(bytes, flush: true); + + try { + final result = await SharePlus.instance.share( + ShareParams(subject: filename, files: [XFile(exportPath)]), + ); + + if (!mounted) return; + if (result.status == ShareResultStatus.success) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.discoveredContacts_exported(filename))), + ); + } + } finally { + if (await exportFile.exists()) { + await exportFile.delete(); + } + } + } catch (e) { + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + content: Text(l10n.discoveredContacts_exportFailed(e.toString())), + ), + ); + } + } + + Future _importDiscoveredContacts( + BuildContext context, + MeshCoreConnector connector, + ) async { + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + try { + final json = await _resolveImportJson(context); + if (json == null) { + // User cancelled the file picker — nothing to do. + return; + } + final foundCount = _countContactsInImportJson(json); + if (foundCount == 0) { + if (!mounted) return; + messenger.showSnackBar( + SnackBar(content: Text(l10n.discoveredContacts_importNoContacts)), + ); + return; + } + + final importedCount = await connector.importDiscoveredContactsJson(json); + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + content: Text(l10n.discoveredContacts_imported(importedCount)), + ), + ); + } catch (e) { + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + content: Text(l10n.discoveredContacts_importFailed(e.toString())), + ), + ); + } + } + + Future _resolveImportJson(BuildContext context) async { + final file = await openFile( + acceptedTypeGroups: [ + const XTypeGroup(label: 'JSON', extensions: ['json']), + ], + ); + if (file == null) return null; + final bytes = await file.readAsBytes(); + + if (bytes.isEmpty) return ''; + + // Try UTF-8 first (handles BOM automatically) + try { + final text = utf8.decode(bytes, allowMalformed: true); + // Remove BOM if present + return text.startsWith('\ufeff') ? text.substring(1) : text; + } catch (_) { + return ''; + } + } + + int _countContactsInImportJson(String json) { + try { + final decoded = jsonDecode(json); + if (decoded is List) { + return decoded.length; + } + return 0; + } catch (_) { + return 0; + } + } + Widget _buildFilters( List filteredAndSorted, MeshCoreConnector connector, diff --git a/lib/storage/contact_discovery_store.dart b/lib/storage/contact_discovery_store.dart index 3f6f1718..40b7ba90 100644 --- a/lib/storage/contact_discovery_store.dart +++ b/lib/storage/contact_discovery_store.dart @@ -28,6 +28,55 @@ class ContactDiscoveryStore { await prefs.setString(_keyPrefix, jsonEncode(jsonList)); } + String exportContactsJson(List contacts) { + final jsonList = contacts.map(_toJson).toList(); + return jsonEncode(jsonList); + } + + int importContactsJson({ + required String json, + required List existingContacts, + required Set knownContactKeys, + }) { + try { + final jsonList = jsonDecode(json) as List; + final importedContacts = jsonList + .map((entry) => _fromJson(entry as Map)) + .toList(); + + int newCount = 0; + + // Create a set of existing discovered contact keys for deduplication + final existingKeySet = {}; + for (final contact in existingContacts) { + existingKeySet.add(contact.publicKeyHex); + } + + // Process imported contacts + for (final imported in importedContacts) { + final keyHex = imported.publicKeyHex; + + // Skip if already in device's contact list + if (knownContactKeys.contains(keyHex)) { + continue; + } + + // Skip if already in discovered contacts (existing is always fresher) + if (existingKeySet.contains(keyHex)) { + continue; + } + + // Add as new discovered contact + existingContacts.add(imported); + newCount++; + } + + return newCount; + } catch (_) { + return 0; + } + } + Map _toJson(Contact contact) { return { 'publicKey': base64Encode(contact.publicKey), @@ -45,6 +94,7 @@ class ContactDiscoveryStore { 'lastSeen': contact.lastSeen.millisecondsSinceEpoch, 'lastModified': contact.lastModified?.millisecondsSinceEpoch, 'lastMessageAt': contact.lastMessageAt.millisecondsSinceEpoch, + 'isActive': contact.isActive, 'rawPacket': contact.rawPacket != null ? base64Encode(contact.rawPacket!) : null, diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index f6f23bfe..7299b5cf 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,9 +6,13 @@ #include "generated_plugin_registrant.h" +#include #include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 379e36fa..3893a6f8 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,11 +3,13 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST flserial + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index ffc8c590..380c924f 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,7 @@ import FlutterMacOS import Foundation +import file_selector_macos import flutter_blue_plus_darwin import flutter_local_notifications import mobile_scanner @@ -15,6 +16,7 @@ import sqflite_darwin import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin")) FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) diff --git a/pubspec.yaml b/pubspec.yaml index 7b43dded..8b7c0e71 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -64,6 +64,7 @@ dependencies: gpx: ^2.3.0 path_provider: ^2.1.5 share_plus: ^12.0.1 + file_selector: ^1.0.3 build_pipe: ^0.3.1 material_symbols_icons: ^4.2906.0 web: ^1.1.1 diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index cd4fc19b..62722cb9 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,11 +6,14 @@ #include "generated_plugin_registrant.h" +#include #include #include #include void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); FlutterBluePlusPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FlutterBluePlusPlugin")); SharePlusWindowsPluginCApiRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index f02857f4..456b758e 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows flutter_blue_plus_winrt share_plus url_launcher_windows @@ -11,6 +12,7 @@ list(APPEND FLUTTER_PLUGIN_LIST list(APPEND FLUTTER_FFI_PLUGIN_LIST flserial flutter_local_notifications_windows + jni ) set(PLUGIN_BUNDLED_LIBRARIES) From 5c612b9a4668f5137d6e1a437c787bb6b20351ca Mon Sep 17 00:00:00 2001 From: ericz Date: Sat, 13 Jun 2026 13:22:15 +0200 Subject: [PATCH 02/28] fix onReorder deprication --- lib/screens/channels_screen.dart | 5 +---- lib/theme/mesh_theme.dart | 2 +- lib/widgets/path_editor_sheet.dart | 5 +---- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 6c227686..dce3dfc3 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -281,10 +281,7 @@ class _ChannelsScreenState extends State ), buildDefaultDragHandles: false, itemCount: filteredChannels.length, - onReorder: (oldIndex, newIndex) { - if (oldIndex < newIndex) { - newIndex -= 1; - } + onReorderItem: (oldIndex, newIndex) { final reordered = List.from( filteredChannels, ); diff --git a/lib/theme/mesh_theme.dart b/lib/theme/mesh_theme.dart index 39c8381f..883ea2a2 100644 --- a/lib/theme/mesh_theme.dart +++ b/lib/theme/mesh_theme.dart @@ -447,7 +447,7 @@ class MeshTheme { pageTransitionsTheme: const PageTransitionsTheme( builders: { TargetPlatform.android: FadeForwardsPageTransitionsBuilder(), - TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.iOS: FadeForwardsPageTransitionsBuilder(), TargetPlatform.linux: FadeForwardsPageTransitionsBuilder(), TargetPlatform.macOS: FadeForwardsPageTransitionsBuilder(), TargetPlatform.windows: FadeForwardsPageTransitionsBuilder(), diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 2eebc1bb..ee6ba006 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -142,9 +142,6 @@ class _PathEditorSheetState extends State { void _reorderHop(int oldIndex, int newIndex) { setState(() { - if (oldIndex < newIndex) { - newIndex -= 1; - } final hop = _hops.removeAt(oldIndex); _hops.insert(newIndex, hop); _syncHexFromHops(); @@ -287,7 +284,7 @@ class _PathEditorSheetState extends State { physics: const NeverScrollableScrollPhysics(), buildDefaultDragHandles: false, itemCount: _hops.length, - onReorder: _reorderHop, + onReorderItem: _reorderHop, itemBuilder: _hopTile, ), const Divider(), From 9db2307ea050419e05a20dd0c134477fdfb6353a Mon Sep 17 00:00:00 2001 From: ZIER Date: Mon, 3 Aug 2026 09:04:36 +0200 Subject: [PATCH 03/28] add setting to enable eviction of discovered contacts in settings --- lib/connector/meshcore_connector.dart | 6 ++- lib/l10n/app_de.arb | 4 +- lib/l10n/app_en.arb | 2 + lib/l10n/app_localizations.dart | 12 +++++ lib/l10n/app_localizations_bg.dart | 8 ++++ lib/l10n/app_localizations_de.dart | 8 ++++ lib/l10n/app_localizations_en.dart | 8 ++++ lib/l10n/app_localizations_es.dart | 8 ++++ lib/l10n/app_localizations_fr.dart | 8 ++++ lib/l10n/app_localizations_hu.dart | 8 ++++ lib/l10n/app_localizations_it.dart | 8 ++++ lib/l10n/app_localizations_ja.dart | 8 ++++ lib/l10n/app_localizations_ko.dart | 8 ++++ lib/l10n/app_localizations_nl.dart | 8 ++++ lib/l10n/app_localizations_pl.dart | 8 ++++ lib/l10n/app_localizations_pt.dart | 8 ++++ lib/l10n/app_localizations_ru.dart | 8 ++++ lib/l10n/app_localizations_sk.dart | 8 ++++ lib/l10n/app_localizations_sl.dart | 8 ++++ lib/l10n/app_localizations_sv.dart | 8 ++++ lib/l10n/app_localizations_uk.dart | 8 ++++ lib/l10n/app_localizations_zh.dart | 8 ++++ lib/models/app_settings.dart | 14 ++++-- lib/screens/app_settings_screen.dart | 4 +- lib/screens/channel_chat_screen.dart | 18 +++----- lib/screens/channels_screen.dart | 3 +- lib/screens/settings_screen.dart | 18 +++++++- lib/services/app_settings_service.dart | 6 +++ test/models/model_changes_test.dart | 5 ++ untranslated.json | 64 +++++++++++++++++++------- 30 files changed, 260 insertions(+), 40 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 4e3ac7d8..34b4ac9c 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -1077,7 +1077,8 @@ class MeshCoreConnector extends ChangeNotifier { final cached = await _discoveryContactStore.loadContacts(); // Trim a previously-saved oversized list down to the freshest entries so a // device that grew unbounded before the cap existed recovers on load. - if (cached.length > _maxDiscoveredContacts) { + if (_appSettingsService?.settings.evictDiscoveredContactsEnabled == true && + cached.length > _maxDiscoveredContacts) { cached.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); cached.removeRange(_maxDiscoveredContacts, cached.length); unawaited(_discoveryContactStore.saveContacts(cached)); @@ -7201,7 +7202,8 @@ class MeshCoreConnector extends ChangeNotifier { flags: 0, ); - if (_discoveredContacts.length >= _maxDiscoveredContacts) { + if (_appSettingsService?.settings.evictDiscoveredContactsEnabled == true && + _discoveredContacts.length >= _maxDiscoveredContacts) { _evictStalestDiscoveredContact(); } _discoveredContacts.add(disContact); diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index f5cc3685..3a34e388 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -2129,6 +2129,7 @@ "contactsSettings_autoAddUsersTitle": "Automatische Hinzufügung von Benutzern", "settings_contactSettingsSubtitle": "Einstellungen für das Hinzufügen von Kontakten", "contactsSettings_autoAddSensorsTitle": "Automatisch Sensoren hinzufügen", + "contactsSettings_autoAddSensorsSubtitle": "Ermöglichen Sie dem Begleiter, automatisch entdeckte Sensoren hinzuzufügen", "contactsSettings_autoAddUsersSubtitle": "Ermöglichen Sie dem Begleiter, automatisch entdeckte Benutzer hinzuzufügen", "contactsSettings_autoAddRoomServersTitle": "Automatisch Raumservers hinzufügen", "contactsSettings_autoAddRoomServersSubtitle": "Ermöglichen Sie dem Begleiter, entdeckte Raumserver automatisch hinzuzufügen", @@ -2142,8 +2143,9 @@ "discoveredContacts_Title": "Entdeckte Kontakte", "discoveredContacts_copyContact": "Kontakt in die Zwischenablage kopieren", "contactsSettings_overwriteOldestTitle": "Überschreiben des Ältesten", - "contactsSettings_autoAddSensorsSubtitle": "Ermöglichen Sie dem Begleiter, automatisch entdeckte Sensoren hinzuzufügen", "contactsSettings_overwriteOldestSubtitle": "Wenn die Kontaktliste voll ist, wird der älteste nicht favorisierte Kontakt ersetzt.", + "contactsSettings_evictDiscoveredContactsTitle": "Kürze entdeckte Kontakte Liste", + "contactsSettings_evictDiscoveredContactsSubtitle": "Wenn aktiviert, wird die Liste der entdeckten Kontackte auf 500 Kontakten begrenzt.", "common_deleteAll": "Alles löschen", "discoveredContacts_deleteContactAllContent": "Sind Sie sicher, dass Sie alle gefundenen Kontakte löschen möchten?", "discoveredContacts_deleteContactAll": "Alle entdeckten Kontakte löschen", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 9c9c8286..aa6419da 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2459,6 +2459,8 @@ "contactsSettings_autoAddSensorsSubtitle": "Allow the companion to automatically add discovered sensors.", "contactsSettings_overwriteOldestTitle": "Overwrite Oldest", "contactsSettings_overwriteOldestSubtitle": "When the contact list is full, the oldest non-favorited contact will be replaced.", + "contactsSettings_evictDiscoveredContactsTitle": "Evict discovered contacts", + "contactsSettings_evictDiscoveredContactsSubtitle": "When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.", "discoveredContacts_Title": "Discovered Contacts", "discoveredContacts_noMatching": "No matching contacts", "discoveredContacts_searchHint": "Search discovered contacts", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 2ad4638e..f0c60357 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -7564,6 +7564,18 @@ abstract class AppLocalizations { /// **'When the contact list is full, the oldest non-favorited contact will be replaced.'** String get contactsSettings_overwriteOldestSubtitle; + /// No description provided for @contactsSettings_evictDiscoveredContactsTitle. + /// + /// In en, this message translates to: + /// **'Evict discovered contacts'** + String get contactsSettings_evictDiscoveredContactsTitle; + + /// No description provided for @contactsSettings_evictDiscoveredContactsSubtitle. + /// + /// In en, this message translates to: + /// **'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'** + String get contactsSettings_evictDiscoveredContactsSubtitle; + /// No description provided for @discoveredContacts_Title. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 41c11438..3eafc324 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4393,6 +4393,14 @@ class AppLocalizationsBg extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Когато списъкът с контакти е пълен, най-старият неключов контакт ще бъде заменен.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Открити контакти'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 5da89506..e95aeb98 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4402,6 +4402,14 @@ class AppLocalizationsDe extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Wenn die Kontaktliste voll ist, wird der älteste nicht favorisierte Kontakt ersetzt.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Kürze entdeckte Kontakte Liste'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'Wenn aktiviert, wird die Liste der entdeckten Kontackte auf 500 Kontakten begrenzt.'; + @override String get discoveredContacts_Title => 'Entdeckte Kontakte'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ccdd9ed0..c92fd833 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4325,6 +4325,14 @@ class AppLocalizationsEn extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'When the contact list is full, the oldest non-favorited contact will be replaced.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Discovered Contacts'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index da679126..7cfabee9 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4396,6 +4396,14 @@ class AppLocalizationsEs extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Cuando la lista de contactos esté llena, se reemplazará el contacto no favorito más antiguo.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Contactos descubiertos'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 29022552..4fae0b8a 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4415,6 +4415,14 @@ class AppLocalizationsFr extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Lorsque la liste de contacts est pleine, le contact le plus ancien non favori sera remplacé.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Contacts découverts'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 7fa5c541..4ff5a1bc 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4391,6 +4391,14 @@ class AppLocalizationsHu extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Amikor a névjegylista megtelik, a legrégebbi, nem kedvenc névjegy lecserélődik.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Felfedezett kapcsolatok'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 0e01ff91..4fb7cfe9 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4402,6 +4402,14 @@ class AppLocalizationsIt extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Quando l\'elenco dei contatti è pieno, il contatto più vecchio non tra i preferiti verrà sostituito.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Contatti scoperti'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index e16d6419..0b1e71b8 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4177,6 +4177,14 @@ class AppLocalizationsJa extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => '連絡先リストが満杯になった場合、最も古いかつ「お気に入り」ではない連絡先が削除されます。'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => '連絡先が見つかった'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 209867fe..36d9a6ce 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4185,6 +4185,14 @@ class AppLocalizationsKo extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => '연락처 목록이 가득 차면, 가장 오래된 (선호하지 않은) 연락처가 대체됩니다.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => '연락처 찾기'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index bf33733a..643e8d7d 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4380,6 +4380,14 @@ class AppLocalizationsNl extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Wanneer de contactenlijst vol is, wordt de oudste niet-favoriete contactpersoon vervangen.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Ontdekte contacten'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index f0f57506..64d5a6df 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4419,6 +4419,14 @@ class AppLocalizationsPl extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Gdy lista kontaktów jest pełna, najstarszy nieulubiony kontakt zostanie zastąpiony.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Odkryte Kontakty'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 55c2fa48..c44c2b60 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4396,6 +4396,14 @@ class AppLocalizationsPt extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Quando a lista de contatos estiver cheia, o contato mais antigo não favoritado será substituído.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Contatos Descobertos'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index d32b69a4..9a571fa4 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4412,6 +4412,14 @@ class AppLocalizationsRu extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Когда список контактов заполнен, будет заменен самый старый контакт, который не находится в избранном.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Обнаруженные контакты'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 5ee8ec33..86a3ce04 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4380,6 +4380,14 @@ class AppLocalizationsSk extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Keď je zoznam kontaktov plný, bude nahradený najstarší neoznačený kontakt.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Objavené kontakty'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 07d1bd4f..119c8def 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4377,6 +4377,14 @@ class AppLocalizationsSl extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Ko je seznam stikov poln, bo najstarejši nestarševski stik zamenjan.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Odkriti stiki'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 8bdd20f9..23ec6bf9 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4350,6 +4350,14 @@ class AppLocalizationsSv extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'När kontaktlistan är full ersätts den äldsta icke-favoriterade kontakten.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Upptäckta kontakter'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 2e87ba8d..d0b51c2e 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4408,6 +4408,14 @@ class AppLocalizationsUk extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => 'Коли список контактів заповнений, найстарший контакт без позначки улюбленого буде замінений.'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => 'Виявлені контакти'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index fa2813c3..0b422596 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4075,6 +4075,14 @@ class AppLocalizationsZh extends AppLocalizations { String get contactsSettings_overwriteOldestSubtitle => '当联系人列表已满时,将替换最老的非收藏联系人。'; + @override + String get contactsSettings_evictDiscoveredContactsTitle => + 'Evict discovered contacts'; + + @override + String get contactsSettings_evictDiscoveredContactsSubtitle => + 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + @override String get discoveredContacts_Title => '已发现的联系人'; diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index a6f82100..6c076cff 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -76,8 +76,7 @@ class Cyr2LatProfile { class AppSettings { static const Object _unset = Object(); - static const String stadiaDemo = - '51bd0381-4685-4666-bae8-48940f6d77c0'; + static const String stadiaDemo = '51bd0381-4685-4666-bae8-48940f6d77c0'; final bool clearPathOnMaxRetry; final bool mapShowRepeaters; @@ -116,6 +115,7 @@ class AppSettings { final UnitSystem unitSystem; final Set mutedChannels; final bool mapShowDiscoveryContacts; + final bool evictDiscoveredContactsEnabled; final String tcpServerAddress; final int tcpServerPort; final bool jumpToOldestUnread; @@ -137,8 +137,7 @@ class AppSettings { return apiKey; } - bool get usesstadiaDemo => - effectiveMapTileApiKey == stadiaDemo; + bool get usesstadiaDemo => effectiveMapTileApiKey == stadiaDemo; Map get cyr2latCharMap { final profile = cyr2latProfiles.firstWhere( @@ -186,6 +185,7 @@ class AppSettings { this.unitSystem = UnitSystem.metric, Set? mutedChannels, this.mapShowDiscoveryContacts = true, + this.evictDiscoveredContactsEnabled = false, this.tcpServerAddress = '', this.tcpServerPort = 0, this.jumpToOldestUnread = false, @@ -253,6 +253,7 @@ class AppSettings { 'unit_system': unitSystem.value, 'muted_channels': mutedChannels.toList(), 'map_show_discovery_contacts': mapShowDiscoveryContacts, + 'evict_discovered_contacts_enabled': evictDiscoveredContactsEnabled, 'tcp_server_address': tcpServerAddress, 'tcp_server_port': tcpServerPort, 'jump_to_oldest_unread': jumpToOldestUnread, @@ -342,6 +343,8 @@ class AppSettings { {}, mapShowDiscoveryContacts: json['map_show_discovery_contacts'] as bool? ?? true, + evictDiscoveredContactsEnabled: + json['evict_discovered_contacts_enabled'] as bool? ?? false, tcpServerAddress: json['tcp_server_address'] as String? ?? '', tcpServerPort: json['tcp_server_port'] as int? ?? 0, jumpToOldestUnread: json['jump_to_oldest_unread'] as bool? ?? false, @@ -438,6 +441,7 @@ class AppSettings { UnitSystem? unitSystem, Set? mutedChannels, bool? mapShowDiscoveryContacts, + bool? evictDiscoveredContactsEnabled, String? tcpServerAddress, int? tcpServerPort, bool? jumpToOldestUnread, @@ -505,6 +509,8 @@ class AppSettings { mutedChannels: mutedChannels ?? this.mutedChannels, mapShowDiscoveryContacts: mapShowDiscoveryContacts ?? this.mapShowDiscoveryContacts, + evictDiscoveredContactsEnabled: + evictDiscoveredContactsEnabled ?? this.evictDiscoveredContactsEnabled, tcpServerAddress: tcpServerAddress ?? this.tcpServerAddress, tcpServerPort: tcpServerPort ?? this.tcpServerPort, jumpToOldestUnread: jumpToOldestUnread ?? this.jumpToOldestUnread, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 90a0a132..8405beca 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -1153,9 +1153,7 @@ class AppSettingsScreen extends StatelessWidget { ) { final currentApiKey = settingsService.settings.mapTileApiKey?.trim() ?? ''; final maskedApiKey = _maskApiKey( - currentApiKey.isEmpty - ? AppSettings.stadiaDemo - : currentApiKey, + currentApiKey.isEmpty ? AppSettings.stadiaDemo : currentApiKey, ); final controller = TextEditingController(text: maskedApiKey); showDialog( diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index ce170aed..2e7c3b68 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -700,9 +700,9 @@ class _ChannelChatScreenState extends State { child: Text( context.l10n.channels_via( _formatPathPrefixes( - displayPath, - displayPathHashWidth, - ), + displayPath, + displayPathHashWidth, + ), ), style: MeshTheme.mono( fontSize: 9.5 * textScale, @@ -1214,25 +1214,19 @@ class _ChannelChatScreenState extends State { decoration: InputDecoration( hintText: context.l10n.chat_typeMessage, border: OutlineInputBorder( - borderRadius: BorderRadius.circular( - MeshRadii.md, - ), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.outlineVariant, ), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular( - MeshRadii.md, - ), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.outlineVariant, ), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular( - MeshRadii.md, - ), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.primary, width: 1.5, diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index fb5039d2..1867f5de 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -412,7 +412,8 @@ class _ChannelsScreenState extends State final messages = connector.getChannelMessages(channel); final lastMessage = messages.isNotEmpty ? messages.last : null; final lastMessageText = lastMessage?.text ?? ''; - final lastPreview = lastMessageText.isNotEmpty && + final lastPreview = + lastMessageText.isNotEmpty && GifHelper.parseGif(lastMessageText) != null ? context.l10n.chat_receivedGif : lastMessageText; diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 17cca639..55c64c32 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1168,6 +1168,9 @@ class _SettingsScreenState extends State { bool autoAddRoomServer = false; bool autoAddSensor = false; bool overwriteOldest = false; + final appSettingsService = context.read(); + bool evictDiscoveredContactsEnabled = + appSettingsService.settings.evictDiscoveredContactsEnabled; final connector = context.read(); autoAddChat = connector.autoAddUsers ?? false; @@ -1229,6 +1232,15 @@ class _SettingsScreenState extends State { setDialogState(() => overwriteOldest = value); }, ), + const Divider(height: 4), + FeatureToggleRow( + title: l10n.contactsSettings_evictDiscoveredContactsTitle, + subtitle: l10n.contactsSettings_evictDiscoveredContactsSubtitle, + value: evictDiscoveredContactsEnabled, + onChanged: (value) { + setDialogState(() => evictDiscoveredContactsEnabled = value); + }, + ), ], ), ), @@ -1238,7 +1250,10 @@ class _SettingsScreenState extends State { child: Text(l10n.common_cancel), ), TextButton( - onPressed: () { + onPressed: () async { + await appSettingsService.setEvictDiscoveredContactsEnabled( + evictDiscoveredContactsEnabled, + ); _sendSettings( connector, autoAddChat, @@ -1247,6 +1262,7 @@ class _SettingsScreenState extends State { autoAddSensor, overwriteOldest, ); + if (!mounted) return; Navigator.pop(context); }, child: Text(l10n.common_save), diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index e695ba99..cd5dc8ab 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -223,6 +223,12 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(mapShowDiscoveryContacts: value)); } + Future setEvictDiscoveredContactsEnabled(bool value) async { + await updateSettings( + _settings.copyWith(evictDiscoveredContactsEnabled: value), + ); + } + Future setBatteryChemistryForDevice( String deviceId, String chemistry, diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index cc218c95..dbce1d39 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -385,6 +385,7 @@ void main() { expect(settings.routeWeightSuccessIncrement, equals(0.5)); expect(settings.routeWeightFailureDecrement, equals(0.2)); expect(settings.maxMessageRetries, equals(5)); + expect(settings.evictDiscoveredContactsEnabled, isFalse); }); test('toJson includes all new fields', () { @@ -395,11 +396,13 @@ void main() { expect(json.containsKey('route_weight_success_increment'), isTrue); expect(json.containsKey('route_weight_failure_decrement'), isTrue); expect(json.containsKey('max_message_retries'), isTrue); + expect(json.containsKey('evict_discovered_contacts_enabled'), isFalse); expect(json['max_route_weight'], equals(5.0)); expect(json['initial_route_weight'], equals(3.0)); expect(json['route_weight_success_increment'], equals(0.5)); expect(json['route_weight_failure_decrement'], equals(0.2)); expect(json['max_message_retries'], equals(5)); + expect(json['evict_discovered_contacts_enabled'], isFalse); }); test('fromJson reads all new fields', () { @@ -409,6 +412,7 @@ void main() { 'route_weight_success_increment': 1.0, 'route_weight_failure_decrement': 1.5, 'max_message_retries': 8, + 'evict_discovered_contacts_enabled': false, }; final settings = AppSettings.fromJson(json); expect(settings.maxRouteWeight, equals(10.0)); @@ -416,6 +420,7 @@ void main() { expect(settings.routeWeightSuccessIncrement, equals(1.0)); expect(settings.routeWeightFailureDecrement, equals(1.5)); expect(settings.maxMessageRetries, equals(8)); + expect(settings.evictDiscoveredContactsEnabled, isFalse); }); test( diff --git a/untranslated.json b/untranslated.json index 14f7f7cc..dc0e7883 100644 --- a/untranslated.json +++ b/untranslated.json @@ -30,7 +30,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "de": [ @@ -85,7 +87,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "fr": [ @@ -119,7 +123,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "hu": [ @@ -153,7 +159,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "it": [ @@ -187,7 +195,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "ja": [ @@ -221,7 +231,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "ko": [ @@ -255,7 +267,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "nl": [ @@ -289,7 +303,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "pl": [ @@ -323,7 +339,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "pt": [ @@ -357,7 +375,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "ru": [ @@ -391,7 +411,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "sk": [ @@ -425,7 +447,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "sl": [ @@ -459,7 +483,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "sv": [ @@ -493,7 +519,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "uk": [ @@ -527,7 +555,9 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ], "zh": [ @@ -561,6 +591,8 @@ "repeater_pubKey", "repeater_pubKeyHelper", "repeater_pubKeyPrefix", - "repeater_pubKeyPrefixHelper" + "repeater_pubKeyPrefixHelper", + "contactsSettings_evictDiscoveredContactsTitle", + "contactsSettings_evictDiscoveredContactsSubtitle" ] } From 8cd7016cba68c847bae2b0bfe8c9015e0b8f9fe4 Mon Sep 17 00:00:00 2001 From: ericz Date: Tue, 4 Aug 2026 17:31:06 +0200 Subject: [PATCH 04/28] dart format and fix test/screens/path_trace_test.dart --- lib/screens/settings_screen.dart | 7 +++++-- test/models/model_changes_test.dart | 1 - test/screens/path_trace_test.dart | 14 ++++++++++---- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 55c64c32..27bbed0f 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1235,10 +1235,13 @@ class _SettingsScreenState extends State { const Divider(height: 4), FeatureToggleRow( title: l10n.contactsSettings_evictDiscoveredContactsTitle, - subtitle: l10n.contactsSettings_evictDiscoveredContactsSubtitle, + subtitle: + l10n.contactsSettings_evictDiscoveredContactsSubtitle, value: evictDiscoveredContactsEnabled, onChanged: (value) { - setDialogState(() => evictDiscoveredContactsEnabled = value); + setDialogState( + () => evictDiscoveredContactsEnabled = value, + ); }, ), ], diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index dbce1d39..6ef241bf 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -648,7 +648,6 @@ void main() { expect(contacts.first.path, equals(Uint8List.fromList([0x11, 0x22]))); }, ); - }); group('AppSettingsService — gps interval fallback', () { diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart index 55c10b14..74b2b37a 100644 --- a/test/screens/path_trace_test.dart +++ b/test/screens/path_trace_test.dart @@ -22,7 +22,8 @@ class _FakeStorageService extends StorageService { ContactPathHistory history, ) async {} @override - Future loadPathHistory(String contactPubKeyHex) async => null; + Future loadPathHistory(String contactPubKeyHex) async => + null; @override Future clearPathHistory(String contactPubKeyHex) async {} } @@ -71,13 +72,18 @@ Widget _buildTestApp({ required MeshCoreConnector connector, required Widget child, }) { + final appSettingsService = AppSettingsService(); + return MultiProvider( providers: [ ChangeNotifierProvider.value(value: connector), - ChangeNotifierProvider( - create: (_) => AppSettingsService(), + ChangeNotifierProvider.value( + value: appSettingsService, + ), + ChangeNotifierProvider( + create: (_) => + MapTileCacheService(appSettingsService: appSettingsService), ), - Provider(create: (_) => MapTileCacheService()), ChangeNotifierProvider( create: (_) => PathHistoryService(_FakeStorageService()), ), From c92415a0ff842634c9c72b994937a9fe859101e1 Mon Sep 17 00:00:00 2001 From: ericz Date: Tue, 4 Aug 2026 17:38:17 +0200 Subject: [PATCH 05/28] fix context mounted check --- lib/screens/settings_screen.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 27bbed0f..697af86c 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1265,7 +1265,7 @@ class _SettingsScreenState extends State { autoAddSensor, overwriteOldest, ); - if (!mounted) return; + if (!context.mounted) return; Navigator.pop(context); }, child: Text(l10n.common_save), From 0834509950786818a1739d207847b5da2b367401 Mon Sep 17 00:00:00 2001 From: ericz Date: Tue, 4 Aug 2026 17:52:33 +0200 Subject: [PATCH 06/28] fix forgotten default setting change in test. --- test/models/model_changes_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 6ef241bf..e742267e 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -396,7 +396,7 @@ void main() { expect(json.containsKey('route_weight_success_increment'), isTrue); expect(json.containsKey('route_weight_failure_decrement'), isTrue); expect(json.containsKey('max_message_retries'), isTrue); - expect(json.containsKey('evict_discovered_contacts_enabled'), isFalse); + expect(json.containsKey('evict_discovered_contacts_enabled'), isTrue); expect(json['max_route_weight'], equals(5.0)); expect(json['initial_route_weight'], equals(3.0)); expect(json['route_weight_success_increment'], equals(0.5)); From 1323bf13b67e83cec0cef915da28810db64c9ac4 Mon Sep 17 00:00:00 2001 From: ericz Date: Tue, 8 Sep 2026 18:05:11 +0200 Subject: [PATCH 07/28] Trim an oversized list when enabling eviction --- lib/connector/meshcore_connector.dart | 17 ++++++++++++++--- lib/screens/settings_screen.dart | 3 +++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index e6969d99..6db7f11e 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -1112,9 +1112,7 @@ class MeshCoreConnector extends ChangeNotifier { // Trim a previously-saved oversized list down to the freshest entries so a // device that grew unbounded before the cap existed recovers on load. if (_appSettingsService?.settings.evictDiscoveredContactsEnabled == true && - cached.length > _maxDiscoveredContacts) { - cached.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); - cached.removeRange(_maxDiscoveredContacts, cached.length); + _trimDiscoveredContactsToLimit(cached)) { unawaited(_discoveryContactStore.saveContacts(cached)); } _discoveredContacts @@ -1122,6 +1120,19 @@ class MeshCoreConnector extends ChangeNotifier { ..addAll(cached); } + bool _trimDiscoveredContactsToLimit(List contacts) { + if (contacts.length <= _maxDiscoveredContacts) return false; + contacts.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); + contacts.removeRange(_maxDiscoveredContacts, contacts.length); + return true; + } + + Future trimDiscoveredContactsToLimit() async { + if (!_trimDiscoveredContactsToLimit(_discoveredContacts)) return; + await _persistDiscoveredContacts(); + notifyListeners(); + } + Future loadChannelSettings({int? maxChannels}) async { _channelSmazEnabled.clear(); _channelCyr2LatEnabled.clear(); diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 838ebfb4..4e2cb8ff 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1269,6 +1269,9 @@ class _SettingsScreenState extends State { await appSettingsService.setEvictDiscoveredContactsEnabled( evictDiscoveredContactsEnabled, ); + if (evictDiscoveredContactsEnabled) { + await connector.trimDiscoveredContactsToLimit(); + } _sendSettings( connector, autoAddChat, From 1d7c5abbecf6eca8bff22ddc4fb5fb36582abfb7 Mon Sep 17 00:00:00 2001 From: shortwavesurfer2009 Date: Mon, 5 Oct 2026 13:39:04 -0400 Subject: [PATCH 08/28] Android: remove message copied snackbar in favor of the system text copied chip --- lib/screens/channel_chat_screen.dart | 3 +++ lib/screens/chat_screen.dart | 3 +++ 2 files changed, 6 insertions(+) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index dc3124c0..c3de648e 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -2478,6 +2478,9 @@ class _ChannelChatScreenState extends State { void _copyMessageText(String text) { Clipboard.setData(ClipboardData(text: text)); + // Android shows its own clipboard chip; the snackbar is redundant there + // and lingers over the input field after the chip dismisses. + if (PlatformInfo.isAndroid) return; showDismissibleSnackBar( context, content: Text(context.l10n.chat_messageCopied), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 30aac388..05c4e4e7 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -1279,6 +1279,9 @@ class _ChatScreenState extends State { void _copyMessageText(String text) { Clipboard.setData(ClipboardData(text: text)); + // Android shows its own clipboard chip; the snackbar is redundant there + // and lingers over the input field after the chip dismisses. + if (PlatformInfo.isAndroid) return; showDismissibleSnackBar( context, content: Text(context.l10n.chat_messageCopied), From 11c94040e3d0ba2be44eafd52722e9dd2b8d860f Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 20:38:59 -0700 Subject: [PATCH 09/28] Add review mode with a simulated radio Store reviewers have no MeshCore radio, so they could not reach any screen past Connect or test the Android Auto messaging notifications. - Long-press the "MeshCore Open" title on the Connect screen to enter review mode on any platform - A simulated radio speaks the companion protocol as a fourth transport, so sync, messages, ACKs, notifications and notification replies run through the normal code paths - Seeded contacts, channels and history; a new incoming message every 45 s, auto-replies a few seconds after sending, and a banner with "Send test message" and "Exit" - Review data uses its own fixed key scope and is cleared on entry, exit and at startup; the review scope never adopts legacy unscoped keys, and channel mutes changed during review are restored - Code lives in lib/review_mode/ with tests in test/review_mode/ --- documentation/README.md | 1 + documentation/review-mode.md | 44 ++ lib/connector/meshcore_connector.dart | 147 ++++- lib/l10n/app_bg.arb | 11 +- lib/l10n/app_de.arb | 11 +- lib/l10n/app_en.arb | 20 +- lib/l10n/app_es.arb | 11 +- lib/l10n/app_fr.arb | 11 +- lib/l10n/app_hu.arb | 11 +- lib/l10n/app_it.arb | 11 +- lib/l10n/app_ja.arb | 11 +- lib/l10n/app_ko.arb | 11 +- lib/l10n/app_localizations.dart | 54 ++ lib/l10n/app_localizations_bg.dart | 30 + lib/l10n/app_localizations_de.dart | 30 + lib/l10n/app_localizations_en.dart | 30 + lib/l10n/app_localizations_es.dart | 30 + lib/l10n/app_localizations_fr.dart | 30 + lib/l10n/app_localizations_hu.dart | 30 + lib/l10n/app_localizations_it.dart | 30 + lib/l10n/app_localizations_ja.dart | 30 + lib/l10n/app_localizations_ko.dart | 30 + lib/l10n/app_localizations_nl.dart | 30 + lib/l10n/app_localizations_pl.dart | 30 + lib/l10n/app_localizations_pt.dart | 30 + lib/l10n/app_localizations_ru.dart | 30 + lib/l10n/app_localizations_sk.dart | 30 + lib/l10n/app_localizations_sl.dart | 30 + lib/l10n/app_localizations_sv.dart | 30 + lib/l10n/app_localizations_uk.dart | 30 + lib/l10n/app_localizations_zh.dart | 30 + lib/l10n/app_nl.arb | 11 +- lib/l10n/app_pl.arb | 11 +- lib/l10n/app_pt.arb | 11 +- lib/l10n/app_ru.arb | 11 +- lib/l10n/app_sk.arb | 11 +- lib/l10n/app_sl.arb | 11 +- lib/l10n/app_sv.arb | 11 +- lib/l10n/app_uk.arb | 11 +- lib/l10n/app_zh.arb | 11 +- lib/main.dart | 3 + lib/review_mode/review_frames.dart | 289 ++++++++ lib/review_mode/review_mode.dart | 68 ++ lib/review_mode/review_mode_banner.dart | 72 ++ lib/review_mode/review_mode_entry.dart | 19 + lib/review_mode/review_mode_storage.dart | 55 ++ lib/review_mode/review_radio.dart | 624 ++++++++++++++++++ lib/review_mode/review_script.dart | 297 +++++++++ lib/screens/channels_screen.dart | 328 ++++----- lib/screens/contacts_screen.dart | 8 +- lib/screens/path_trace_map.dart | 10 +- lib/screens/scanner_screen.dart | 5 +- lib/storage/channel_message_store.dart | 4 +- lib/storage/channel_order_store.dart | 4 +- lib/storage/channel_settings_store.dart | 3 +- lib/storage/channel_store.dart | 4 +- lib/storage/community_store.dart | 4 +- lib/storage/contact_group_store.dart | 4 +- lib/storage/contact_settings_store.dart | 3 +- lib/storage/contact_store.dart | 4 +- lib/storage/legacy_key_migration.dart | 10 + lib/storage/message_store.dart | 4 +- lib/storage/unread_store.dart | 4 +- lib/widgets/routing_sheet.dart | 3 +- test/review_mode/review_mode_cancel_test.dart | 54 ++ .../review_mode_connector_test.dart | 103 +++ .../review_mode_settings_revert_test.dart | 107 +++ test/review_mode/review_radio_test.dart | 425 ++++++++++++ 68 files changed, 3314 insertions(+), 197 deletions(-) create mode 100644 documentation/review-mode.md create mode 100644 lib/review_mode/review_frames.dart create mode 100644 lib/review_mode/review_mode.dart create mode 100644 lib/review_mode/review_mode_banner.dart create mode 100644 lib/review_mode/review_mode_entry.dart create mode 100644 lib/review_mode/review_mode_storage.dart create mode 100644 lib/review_mode/review_radio.dart create mode 100644 lib/review_mode/review_script.dart create mode 100644 lib/storage/legacy_key_migration.dart create mode 100644 test/review_mode/review_mode_cancel_test.dart create mode 100644 test/review_mode/review_mode_connector_test.dart create mode 100644 test/review_mode/review_mode_settings_revert_test.dart create mode 100644 test/review_mode/review_radio_test.dart diff --git a/documentation/README.md b/documentation/README.md index af6c73bb..6778e97d 100644 --- a/documentation/README.md +++ b/documentation/README.md @@ -27,6 +27,7 @@ MeshCore Open is an open-source Flutter client for MeshCore LoRa mesh networking 14. [Image Messages](image-messages.md) - Model setup, mesh image sending, recovery, and reconstruction 15. [Companion Radio Statistics](radio-statistics.md) - Noise, signal metrics, and airtime 16. [Troubleshooting](troubleshooting.md) - BLE, USB, browser, and firmware issues +17. [Review Mode](review-mode.md) - Simulated radio and reviewer instructions for Google Play and App Store review ## App Overview diff --git a/documentation/review-mode.md b/documentation/review-mode.md new file mode 100644 index 00000000..779e24de --- /dev/null +++ b/documentation/review-mode.md @@ -0,0 +1,44 @@ +# Review Mode + +Review mode is a hidden mode for Google Play and App Store reviewers who have no MeshCore radio. It connects the app to a **simulated radio** that speaks the real companion protocol, so contact and channel sync, messages, ACKs, notifications, and Android Auto replies all run through the normal code paths. All of its code lives in `lib/review_mode/`. + +## Entering and Exiting + +1. Open the **Connect** (scanner) screen. +2. **Long-press the "MeshCore Open" title.** +3. Tap **Enter** in the dialog. The app connects to the simulated radio and opens the channel list. + +While review mode is active, a banner at the top of the channel and contact lists shows **Send test message** and **Exit**. Tap **Exit**, or disconnect as usual, to leave review mode. The simulator is shut down, its data is deleted, and the app returns to the Connect screen. + +## What the Simulated Radio Provides + +- 6 contacts (4 people, the **Hilltop Repeater** and the **Trailhead Room**), the **Public** channel and 2 more channels (**Hiking Group** and **Local Net**), with seeded message history. +- The room accepts any password. Repeater login always fails, because repeater administration needs real hardware. +- A new incoming message about every 45 seconds, alternating between direct and channel messages. +- Automatic replies to messages you send to a person or the room: the ACK arrives after about 1.5 seconds and the reply about 4 seconds later. Channel messages get a reply from a channel member about 4 seconds after sending. +- A **Send test message** button that delivers one incoming message immediately. + +## Data Isolation + +The simulated radio uses a fixed, obviously fake public key (starting `ee5e`), so its contacts, channels, messages, and unread counts are stored under their own per-radio scope and never mix with a real radio's data. Review data is cleared when entering and when leaving review mode. The simulated radio never adopts the legacy unscoped keys that older app versions left behind, so that data stays for the next real radio. + +Channel mutes are app-wide and stored by channel name, so muting the simulated **Public** channel would also mute a real one. Review mode saves the mute list when it starts and puts it back on exit. Other app settings changed during review (theme, notifications, text size) are kept, as they would be after any other session. If the app is killed while in review mode, the cleanup and mute restore run on the next launch. + +## Platforms + +Review mode works on Android, iOS, desktop, and web; it is not platform-gated. + +- Web has no system notifications. +- On iOS, the simulator's timers run only while the app is in the foreground, so scheduled messages stop in the background. Use **Send test message** in the foreground. +- iOS notifications have no reply actions. + +## When Notifications Appear + +Simulated messages go through the normal notification pipeline. A notification is shown when all of these hold: + +- Notifications are allowed by the OS (Android 13+ requires granting the permission) and **Enable Notifications** is on in App Settings. +- **Message Notifications** (direct) or **Channel Message Notifications** (channel) is on. +- The channel is not muted (there is no per-contact muting). +- The message is incoming and the sender is a known chat or room contact (direct messages from other contact types are not notified). + +The app does **not** suppress notifications because it is in the foreground or because that chat is open. Opening a chat clears its unread count and notification. Bursts of messages update the notification silently (rate limited). Reviewers do not need to background the app for notifications to be posted, but notifications are far easier to see from another screen or the home screen. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7874bc18..602081d8 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -54,6 +54,8 @@ import '../storage/contact_settings_store.dart'; import '../storage/contact_store.dart'; import '../storage/message_store.dart'; import '../storage/unread_store.dart'; +import '../review_mode/review_mode_storage.dart'; +import '../review_mode/review_radio.dart'; import '../utils/app_logger.dart'; import '../utils/battery_utils.dart'; import '../utils/platform_info.dart'; @@ -140,7 +142,7 @@ enum MeshCoreConnectionState { disconnecting, } -enum MeshCoreTransportType { bluetooth, usb, tcp } +enum MeshCoreTransportType { bluetooth, usb, tcp, review } class RepeaterBatterySnapshot { final int millivolts; @@ -208,6 +210,9 @@ class MeshCoreConnector extends ChangeNotifier { StreamSubscription? _usbFrameSubscription; final MeshCoreTcpConnector _tcpConnector = MeshCoreTcpConnector(); MeshCoreTransportType _activeTransport = MeshCoreTransportType.bluetooth; + ReviewRadio? _reviewRadio; + StreamSubscription? _reviewFrameSubscription; + int _reviewConnectGeneration = 0; final List _scanResults = []; final List _linuxSystemScanResults = []; @@ -458,6 +463,9 @@ class MeshCoreConnector extends ChangeNotifier { bool get isTcpTransportConnected => _state == MeshCoreConnectionState.connected && _activeTransport == MeshCoreTransportType.tcp; + bool get isReviewMode => + _activeTransport == MeshCoreTransportType.review && + _state != MeshCoreConnectionState.disconnected; String get deviceDisplayName { if (_selfName != null && _selfName!.isNotEmpty) { @@ -2200,6 +2208,121 @@ class MeshCoreConnector extends ChangeNotifier { } } + Future connectReview() async { + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connectReview ignored: already $_state', + tag: 'Review', + ); + return; + } + + _appDebugLogService?.info('connectReview: starting', tag: 'Review'); + + await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connectReview ignored: already $_state after disconnect wait', + tag: 'Review', + ); + return; + } + + await stopScan(); + _cancelReconnectTimer(); + _manualDisconnect = false; + _resetConnectionHandshakeState(); + _activeTransport = MeshCoreTransportType.review; + _setState(MeshCoreConnectionState.connecting); + + // A disconnect (or a newer connect) bumps the generation, so this attempt + // can tell after every await whether it still owns the connector. + final generation = ++_reviewConnectGeneration; + bool isCancelled() => + generation != _reviewConnectGeneration || + _activeTransport != MeshCoreTransportType.review || + _state == MeshCoreConnectionState.disconnecting || + _state == MeshCoreConnectionState.disconnected; + + try { + // Every review session starts from a clean slate. + await beginReviewModeSession(_appSettingsService); + if (isCancelled()) return; + await _reviewFrameSubscription?.cancel(); + _reviewFrameSubscription = null; + _reviewRadio?.dispose(); + final radio = reviewRadioFactoryForTest?.call() ?? ReviewRadio(); + _reviewRadio = radio; + _reviewFrameSubscription = radio.frames.listen( + _handleFrame, + onError: (error, stackTrace) { + _appDebugLogService?.error( + 'Review radio error: $error', + tag: 'Review', + ); + unawaited(disconnect(manual: false)); + }, + ); + + _setState(MeshCoreConnectionState.connected); + unawaited(_backgroundService?.start()); + _pendingInitialChannelSync = true; + _pendingInitialQueuedMessageSync = true; + _pendingInitialContactsSync = true; + await _requestDeviceInfo(); + _startBatteryPolling(); + if (_radioStatsPollRefCount > 0) _startRadioStatsPolling(); + + var gotSelfInfo = await _waitForSelfInfo( + timeout: const Duration(seconds: 3), + ); + if (isCancelled()) return; + if (!gotSelfInfo) { + await refreshDeviceInfo(); + gotSelfInfo = await _waitForSelfInfo( + timeout: const Duration(seconds: 3), + ); + } + if (isCancelled()) return; + if (!gotSelfInfo) { + throw StateError( + 'Timed out waiting for SELF_INFO during review connect', + ); + } + + await syncTime(); + if (!isCancelled() && isConnected) { + radio.start(); + } + } catch (error) { + if (isCancelled()) { + _appDebugLogService?.info( + 'Ignoring review connect error after cancellation: $error', + tag: 'Review', + ); + return; + } + _appDebugLogService?.error( + 'Review connection error: $error', + tag: 'Review', + ); + await disconnect(manual: false); + rethrow; + } + } + + @visibleForTesting + ReviewRadio Function()? reviewRadioFactoryForTest; + + void sendReviewTestMessage() { + if (!isReviewMode) return; + _reviewRadio?.sendTestMessage(); + } + @visibleForTesting void handleFrameForTest(List data) => _handleFrame(data); @@ -2951,6 +3074,7 @@ class MeshCoreConnector extends ChangeNotifier { bool get _shouldGateInitialChannelSync => _activeTransport == MeshCoreTransportType.usb || _activeTransport == MeshCoreTransportType.tcp || + _activeTransport == MeshCoreTransportType.review || (_activeTransport == MeshCoreTransportType.bluetooth && PlatformInfo.isWeb); @@ -3046,6 +3170,7 @@ class MeshCoreConnector extends ChangeNotifier { MeshCoreTransportType.bluetooth => 'BLE', MeshCoreTransportType.usb => 'USB', MeshCoreTransportType.tcp => 'TCP', + MeshCoreTransportType.review => 'Review', }; _appDebugLogService?.info( @@ -3074,6 +3199,12 @@ class MeshCoreConnector extends ChangeNotifier { _usbFrameSubscription = null; await _usbManager.disconnect(); await _tcpConnector.disconnect(); + final wasReviewMode = transportAtDisconnect == MeshCoreTransportType.review; + _reviewConnectGeneration++; + await _reviewFrameSubscription?.cancel(); + _reviewFrameSubscription = null; + _reviewRadio?.dispose(); + _reviewRadio = null; await _notifySubscription?.cancel(); _notifySubscription = null; @@ -3151,6 +3282,12 @@ class MeshCoreConnector extends ChangeNotifier { _reactionSendQueueSequence = 0; _activeTransport = MeshCoreTransportType.bluetooth; + if (wasReviewMode) { + // Write the debounced unread counts now so they cannot land after the + // review data has been deleted. + await _unreadStore.flush(); + await endReviewModeSession(_appSettingsService); + } _setState(MeshCoreConnectionState.disconnected); _appDebugLogService?.info( @@ -3189,6 +3326,12 @@ class MeshCoreConnector extends ChangeNotifier { await Future.delayed(const Duration(milliseconds: 10)); } else if (_activeTransport == MeshCoreTransportType.tcp) { await _tcpConnector.write(data); + } else if (_activeTransport == MeshCoreTransportType.review) { + final radio = _reviewRadio; + if (radio == null) { + throw Exception("Review radio not available"); + } + radio.handle(data); } else { if (_rxCharacteristic == null) { throw Exception("MeshCore RX characteristic not available"); @@ -7547,6 +7690,8 @@ class MeshCoreConnector extends ChangeNotifier { _contactsFullController.close(); _usbManager.dispose(); _tcpConnector.dispose(); + _reviewFrameSubscription?.cancel(); + _reviewRadio?.dispose(); // Flush pending unread writes before disposal _unreadStore.flush(); diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 2b2d285b..8039dfbe 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3051,5 +3051,14 @@ } } }, - "receivedImage_saveFailed": "Изображението не можа да бъде запазено" + "receivedImage_saveFailed": "Изображението не можа да бъде запазено", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 91cd0079..c1d59623 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3186,5 +3186,14 @@ } } }, - "receivedImage_saveFailed": "Das Bild konnte nicht gespeichert werden" + "receivedImage_saveFailed": "Das Bild konnte nicht gespeichert werden", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 47f2dba6..c2ef270c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3106,5 +3106,23 @@ "type": "int" } } - } + }, + "reviewMode_dialogTitle": "Enter review mode?", + "@reviewMode_dialogTitle": {"description": "Title of the review mode confirmation dialog"}, + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "@reviewMode_dialogBody": {"description": "Body of the review mode confirmation dialog"}, + "reviewMode_confirm": "Enter", + "@reviewMode_confirm": {"description": "Confirm button of the review mode dialog"}, + "reviewMode_cancel": "Cancel", + "@reviewMode_cancel": {"description": "Cancel button of the review mode dialog"}, + "reviewMode_banner": "Review mode — simulated data", + "@reviewMode_banner": {"description": "Label of the banner shown while review mode is active"}, + "reviewMode_sendTest": "Send test message", + "@reviewMode_sendTest": {"description": "Banner action that makes the simulated radio deliver a message"}, + "reviewMode_testSent": "A test message will arrive shortly.", + "@reviewMode_testSent": {"description": "Snackbar shown after requesting a test message"}, + "reviewMode_exit": "Exit", + "@reviewMode_exit": {"description": "Banner action that leaves review mode"}, + "reviewMode_connectFailed": "Could not start review mode: {error}", + "@reviewMode_connectFailed": {"description": "Snackbar shown when review mode fails to connect", "placeholders": {"error": {"type": "String"}}} } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 528ac95a..f75b3070 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3185,5 +3185,14 @@ } } }, - "receivedImage_saveFailed": "No se pudo guardar la imagen" + "receivedImage_saveFailed": "No se pudo guardar la imagen", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 65f7f8fb..dea0a2f3 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3185,5 +3185,14 @@ } } }, - "receivedImage_saveFailed": "Impossible d'enregistrer l'image" + "receivedImage_saveFailed": "Impossible d'enregistrer l'image", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 770c9f6a..fc56866d 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3090,5 +3090,14 @@ } } }, - "receivedImage_saveFailed": "A képet nem sikerült elmenteni" + "receivedImage_saveFailed": "A képet nem sikerült elmenteni", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 58b5ded3..577aa703 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3185,5 +3185,14 @@ } } }, - "receivedImage_saveFailed": "Impossibile salvare l'immagine" + "receivedImage_saveFailed": "Impossibile salvare l'immagine", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 18921269..997aacd1 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -3185,5 +3185,14 @@ } } }, - "receivedImage_saveFailed": "画像を保存できませんでした" + "receivedImage_saveFailed": "画像を保存できませんでした", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 915620cd..fcb0e819 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3185,5 +3185,14 @@ } } }, - "receivedImage_saveFailed": "이미지를 저장할 수 없습니다" + "receivedImage_saveFailed": "이미지를 저장할 수 없습니다", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 66eedf4c..2206b8e2 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -9297,6 +9297,60 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Over 158 bytes: sent at most {count} times'** String chat_longMessageRetryNote(int count); + + /// Title of the review mode confirmation dialog + /// + /// In en, this message translates to: + /// **'Enter review mode?'** + String get reviewMode_dialogTitle; + + /// Body of the review mode confirmation dialog + /// + /// In en, this message translates to: + /// **'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'** + String get reviewMode_dialogBody; + + /// Confirm button of the review mode dialog + /// + /// In en, this message translates to: + /// **'Enter'** + String get reviewMode_confirm; + + /// Cancel button of the review mode dialog + /// + /// In en, this message translates to: + /// **'Cancel'** + String get reviewMode_cancel; + + /// Label of the banner shown while review mode is active + /// + /// In en, this message translates to: + /// **'Review mode — simulated data'** + String get reviewMode_banner; + + /// Banner action that makes the simulated radio deliver a message + /// + /// In en, this message translates to: + /// **'Send test message'** + String get reviewMode_sendTest; + + /// Snackbar shown after requesting a test message + /// + /// In en, this message translates to: + /// **'A test message will arrive shortly.'** + String get reviewMode_testSent; + + /// Banner action that leaves review mode + /// + /// In en, this message translates to: + /// **'Exit'** + String get reviewMode_exit; + + /// Snackbar shown when review mode fails to connect + /// + /// In en, this message translates to: + /// **'Could not start review mode: {error}'** + String reviewMode_connectFailed(String error); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index c54ab2ee..9ca96e85 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -5477,4 +5477,34 @@ class AppLocalizationsBg extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Над 158 байта: изпраща се най-много $count пъти'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index ca2ada41..b1893db3 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -5494,4 +5494,34 @@ class AppLocalizationsDe extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Über 158 Byte: wird höchstens $count Mal gesendet'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 70ce610f..13143ae9 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -5400,4 +5400,34 @@ class AppLocalizationsEn extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Over 158 bytes: sent at most $count times'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index f0c31cb3..6bd776f7 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -5483,4 +5483,34 @@ class AppLocalizationsEs extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Más de 158 bytes: se envía como máximo $count veces'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 0385315d..627c6869 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -5507,4 +5507,34 @@ class AppLocalizationsFr extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Plus de 158 octets : envoi au maximum $count fois'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 0b909253..c3f642e0 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -5473,4 +5473,34 @@ class AppLocalizationsHu extends AppLocalizations { String chat_longMessageRetryNote(int count) { return '158 bájt felett: legfeljebb $count alkalommal küldve'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index e737afdd..b8d48bdf 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -5489,4 +5489,34 @@ class AppLocalizationsIt extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Oltre 158 byte: inviato al massimo $count volte'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 86130828..19d92ae1 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5215,4 +5215,34 @@ class AppLocalizationsJa extends AppLocalizations { String chat_longMessageRetryNote(int count) { return '158バイトを超える場合:最大 $count 回まで送信されます'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 94c0f3bd..e41d53e1 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5225,4 +5225,34 @@ class AppLocalizationsKo extends AppLocalizations { String chat_longMessageRetryNote(int count) { return '158바이트 초과 시: 최대 $count회 전송됩니다'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 0c7a199a..aab486a8 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -5451,4 +5451,34 @@ class AppLocalizationsNl extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Meer dan 158 bytes: maximaal $count keer verzonden'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index fbe65401..a88d7afd 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -5511,4 +5511,34 @@ class AppLocalizationsPl extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Powyżej 158 bajtów: wysyłane maksymalnie $count razy'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 4c3b7c43..1d05d25d 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -5479,4 +5479,34 @@ class AppLocalizationsPt extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Mais de 158 bytes: enviado no máximo $count vezes'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b197ce46..e4fe8631 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -5497,4 +5497,34 @@ class AppLocalizationsRu extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Более 158 байт: отправляется не более $count раз'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 2818ab6b..120db392 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -5460,4 +5460,34 @@ class AppLocalizationsSk extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Nad 158 bajtov: odoslané najviac $count-krát'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index ab8ba209..218c8e86 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -5464,4 +5464,34 @@ class AppLocalizationsSl extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Nad 158 bajtov: poslano največ $count-krat'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index aa6022e0..c73afad3 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -5434,4 +5434,34 @@ class AppLocalizationsSv extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Över 158 byte: skickas högst $count gånger'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index c3e5f7a0..f90fd994 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -5500,4 +5500,34 @@ class AppLocalizationsUk extends AppLocalizations { String chat_longMessageRetryNote(int count) { return 'Понад 158 байтів: надсилається не більше $count разів'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d9d7281e..c246fafa 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5092,4 +5092,34 @@ class AppLocalizationsZh extends AppLocalizations { String chat_longMessageRetryNote(int count) { return '超过158字节:最多发送 $count 次'; } + + @override + String get reviewMode_dialogTitle => 'Enter review mode?'; + + @override + String get reviewMode_dialogBody => + 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + + @override + String get reviewMode_confirm => 'Enter'; + + @override + String get reviewMode_cancel => 'Cancel'; + + @override + String get reviewMode_banner => 'Review mode — simulated data'; + + @override + String get reviewMode_sendTest => 'Send test message'; + + @override + String get reviewMode_testSent => 'A test message will arrive shortly.'; + + @override + String get reviewMode_exit => 'Exit'; + + @override + String reviewMode_connectFailed(String error) { + return 'Could not start review mode: $error'; + } } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 05d5f341..87d409f2 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -2952,5 +2952,14 @@ "notification_replyTooLong": "Je antwoord is te lang om vanuit een melding te verzenden. Verzend het vanuit MeshCore Open.", "notification_replyUnavailable": "Dit gesprek staat niet meer op de verbonden radio.", "notification_replySendFailed": "Je antwoord is mogelijk niet verzonden. Controleer dit in MeshCore Open en probeer het opnieuw.", - "notification_replyAppNotRunning": "MeshCore Open is niet actief. Open de app en verzend je antwoord opnieuw." + "notification_replyAppNotRunning": "MeshCore Open is niet actief. Open de app en verzend je antwoord opnieuw.", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index e01d93b3..2888a491 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3090,5 +3090,14 @@ } } }, - "receivedImage_saveFailed": "Nie udało się zapisać obrazu" + "receivedImage_saveFailed": "Nie udało się zapisać obrazu", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 5f60602d..1f3adc13 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3051,5 +3051,14 @@ } } }, - "receivedImage_saveFailed": "Não foi possível guardar a imagem" + "receivedImage_saveFailed": "Não foi possível guardar a imagem", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 033ad113..1a42ab58 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -2354,5 +2354,14 @@ } } }, - "receivedImage_saveFailed": "Не удалось сохранить изображение" + "receivedImage_saveFailed": "Не удалось сохранить изображение", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index a98a62de..eb0c225d 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3052,5 +3052,14 @@ } } }, - "receivedImage_saveFailed": "Nepodarilo sa uložiť obrázok" + "receivedImage_saveFailed": "Nepodarilo sa uložiť obrázok", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 8dd7f422..e0b9507e 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3052,5 +3052,14 @@ } } }, - "receivedImage_saveFailed": "Slike ni bilo mogoče shraniti" + "receivedImage_saveFailed": "Slike ni bilo mogoče shraniti", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 216df0f9..6f661397 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3052,5 +3052,14 @@ } } }, - "receivedImage_saveFailed": "Kunde inte spara bilden" + "receivedImage_saveFailed": "Kunde inte spara bilden", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 5fe2674f..3287f65b 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3031,5 +3031,14 @@ } } }, - "receivedImage_saveFailed": "Не вдалося зберегти зображення" + "receivedImage_saveFailed": "Не вдалося зберегти зображення", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index abe4977e..cd9427ab 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3056,5 +3056,14 @@ } } }, - "receivedImage_saveFailed": "无法保存图片" + "receivedImage_saveFailed": "无法保存图片", + "reviewMode_dialogTitle": "Enter review mode?", + "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", + "reviewMode_confirm": "Enter", + "reviewMode_cancel": "Cancel", + "reviewMode_banner": "Review mode — simulated data", + "reviewMode_sendTest": "Send test message", + "reviewMode_testSent": "A test message will arrive shortly.", + "reviewMode_exit": "Exit", + "reviewMode_connectFailed": "Could not start review mode: {error}" } diff --git a/lib/main.dart b/lib/main.dart index 82e9e0ac..7162f67a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -7,6 +7,7 @@ import 'package:flutter/services.dart'; import 'l10n/app_localizations.dart'; import 'package:provider/provider.dart'; +import 'review_mode/review_mode_storage.dart'; import 'screens/chrome_required_screen.dart'; import 'utils/platform_info.dart'; @@ -73,6 +74,8 @@ void main() async { // `appSettingsService.settings`, so this cannot stay where it used to be // (after the constructions) without those two starting out wrong. await appSettingsService.loadSettings(); + // Undo a review-mode session the app was killed in before it could exit. + await endReviewModeSession(appSettingsService); // ---- image messages (AEIC over GRP_DATA) -------------------------------- // The codec owns the ONNX decoder; the store owns received-image state and diff --git a/lib/review_mode/review_frames.dart b/lib/review_mode/review_frames.dart new file mode 100644 index 00000000..8427e23c --- /dev/null +++ b/lib/review_mode/review_frames.dart @@ -0,0 +1,289 @@ +import 'dart:typed_data'; + +import '../connector/meshcore_protocol.dart'; + +/// Pure builders for the radio-to-app companion frames the connector parses. +class ReviewFrames { + ReviewFrames._(); + + /// ERR_CODE_NOT_FOUND in the companion firmware. + static const int errNotFound = 2; + static const int errUnsupported = 1; + + static Uint8List ok() => Uint8List.fromList([respCodeOk]); + + static Uint8List err([int code = errUnsupported]) => + Uint8List.fromList([respCodeErr, code]); + + static Uint8List selfInfo({ + required Uint8List publicKey, + required String name, + required int latitudeE6, + required int longitudeE6, + required int frequencyHz, + required int bandwidthHz, + required int spreadingFactor, + required int codingRate, + required int txPowerDbm, + required int maxTxPowerDbm, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeSelfInfo); + writer.writeByte(advTypeChat); + writer.writeByte(txPowerDbm); + writer.writeByte(maxTxPowerDbm); + writer.writeBytes(publicKey); + writer.writeInt32LE(latitudeE6); + writer.writeInt32LE(longitudeE6); + writer.writeByte(0); // multi_acks + writer.writeByte(0); // advert_loc_policy + writer.writeByte(0); // telemetry modes + writer.writeByte( + 1, + ); // manual_add_contacts: 1 = auto-add controlled by flags + writer.writeUInt32LE(frequencyHz); + writer.writeUInt32LE(bandwidthHz); + writer.writeByte(spreadingFactor); + writer.writeByte(codingRate); + writer.writeString(name); + writer.writeByte(0); + return writer.toBytes(); + } + + static Uint8List deviceInfo({ + required int firmwareVerCode, + required int maxContacts, + required int maxChannels, + String manufacturer = 'MeshCore Open Review', + String version = 'review', + bool clientRepeat = false, + int pathHashMode = 0, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeDeviceInfo); + writer.writeByte(firmwareVerCode); + writer.writeByte(maxContacts ~/ 2); + writer.writeByte(maxChannels); + writer.writeUInt32LE(0); // ble pin, bytes 4..7 + writer.writeCString('', 12); // build date, bytes 8..19 + writer.writeCString(manufacturer, 40); // bytes 20..59 + writer.writeCString(version, 20); // bytes 60..79 + writer.writeByte(clientRepeat ? 1 : 0); // byte 80 + writer.writeByte(pathHashMode); // byte 81 + return writer.toBytes(); + } + + static Uint8List contactsStart(int count) { + final writer = BufferWriter(); + writer.writeByte(respCodeContactsStart); + writer.writeUInt32LE(count); + return writer.toBytes(); + } + + static Uint8List contact({ + required Uint8List publicKey, + required int type, + required Uint8List path, + required String name, + required int lastAdvertSecs, + required int latitudeE6, + required int longitudeE6, + required int lastModSecs, + int flags = 0, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeContact); + writer.writeBytes(publicKey); + writer.writeByte(type); + writer.writeByte(flags); + writer.writeByte(path.length); // one-byte hashes: hop count == byte count + writer.writeBytesPadded(path, maxPathSize); + writer.writeCString(name, maxNameSize); + writer.writeUInt32LE(lastAdvertSecs); + writer.writeInt32LE(latitudeE6); + writer.writeInt32LE(longitudeE6); + writer.writeUInt32LE(lastModSecs); + return writer.toBytes(); + } + + static Uint8List endOfContacts(int mostRecentLastModSecs) { + final writer = BufferWriter(); + writer.writeByte(respCodeEndOfContacts); + writer.writeUInt32LE(mostRecentLastModSecs); + return writer.toBytes(); + } + + static Uint8List channelInfo({ + required int index, + required String name, + required Uint8List psk, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeChannelInfo); + writer.writeByte(index); + writer.writeCString(name, 32); + writer.writeBytesPadded(psk, 16); + return writer.toBytes(); + } + + static Uint8List contactMessage({ + required Uint8List senderPublicKey, + required String text, + required int timestampSecs, + int pathLen = 0xFF, + int snrQuarterDb = 24, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeContactMsgRecvV3); + writer.writeByte(snrQuarterDb & 0xFF); + writer.writeByte(0); + writer.writeByte(0); + writer.writeBytes(Uint8List.fromList(senderPublicKey.sublist(0, 6))); + writer.writeByte(pathLen); + writer.writeByte(txtTypePlain); + writer.writeUInt32LE(timestampSecs); + writer.writeString(text); + writer.writeByte(0); + return writer.toBytes(); + } + + /// The on-air text is `sender: message`. + static Uint8List channelMessage({ + required int channelIndex, + required String sender, + required String message, + required int timestampSecs, + Uint8List? path, + int snrQuarterDb = 24, + }) { + final hasPath = path != null && path.isNotEmpty; + final writer = BufferWriter(); + writer.writeByte(respCodeChannelMsgRecvV3); + writer.writeByte(snrQuarterDb & 0xFF); + writer.writeByte(hasPath ? 1 : 0); + writer.writeByte(0); + writer.writeByte(channelIndex); + writer.writeByte(hasPath ? path.length : 0xFF); + if (hasPath) writer.writeBytes(path); + writer.writeByte(txtTypePlain); + writer.writeUInt32LE(timestampSecs); + writer.writeString('$sender: $message'); + writer.writeByte(0); + return writer.toBytes(); + } + + static Uint8List sent({ + required bool flood, + required int ackHash, + required int timeoutMs, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeSent); + writer.writeByte(flood ? 1 : 0); + writer.writeUInt32LE(ackHash); + writer.writeUInt32LE(timeoutMs); + return writer.toBytes(); + } + + static Uint8List sendConfirmed({ + required int ackHash, + required int tripTimeMs, + }) { + final writer = BufferWriter(); + writer.writeByte(pushCodeSendConfirmed); + writer.writeUInt32LE(ackHash); + writer.writeUInt32LE(tripTimeMs); + return writer.toBytes(); + } + + /// [code][permissions][pub_key_prefix x6][server_time x4][acl][fw_level]. + static Uint8List loginSuccess({ + required Uint8List publicKey, + required int serverTimeSecs, + int permissions = 0, + }) { + final writer = BufferWriter(); + writer.writeByte(pushCodeLoginSuccess); + writer.writeByte(permissions); + writer.writeBytes(Uint8List.fromList(publicKey.sublist(0, 6))); + writer.writeUInt32LE(serverTimeSecs); + writer.writeByte(0); // ACL permissions + writer.writeByte(0); // firmware version level + return writer.toBytes(); + } + + /// [code][reserved][pub_key_prefix x6]. + static Uint8List loginFail({required Uint8List publicKey}) { + final writer = BufferWriter(); + writer.writeByte(pushCodeLoginFail); + writer.writeByte(0); + writer.writeBytes(Uint8List.fromList(publicKey.sublist(0, 6))); + return writer.toBytes(); + } + + static Uint8List msgWaiting() => Uint8List.fromList([pushCodeMsgWaiting]); + + static Uint8List noMoreMessages() => + Uint8List.fromList([respCodeNoMoreMessages]); + + static Uint8List battAndStorage({ + required int millivolts, + required int usedKb, + required int totalKb, + }) { + final writer = BufferWriter(); + writer.writeByte(respCodeBattAndStorage); + writer.writeUInt16LE(millivolts); + writer.writeUInt32LE(usedKb); + writer.writeUInt32LE(totalKb); + return writer.toBytes(); + } + + static Uint8List currTime(int epochSecs) { + final writer = BufferWriter(); + writer.writeByte(respCodeCurrTime); + writer.writeUInt32LE(epochSecs); + return writer.toBytes(); + } + + /// [vars] is the comma separated "key:value" list the connector parses. + static Uint8List customVars(String vars) { + final writer = BufferWriter(); + writer.writeByte(respCodeCustomVars); + writer.writeString(vars); + writer.writeByte(0); + return writer.toBytes(); + } + + static Uint8List autoAddConfig({required int flags, int maxHops = 0}) => + Uint8List.fromList([respCodeAutoAddConfig, flags, maxHops]); + + static Uint8List allowedRepeatFreq(List ranges) { + final writer = BufferWriter(); + writer.writeByte(respCodeAllowedRepeatFreq); + for (final range in ranges) { + writer.writeUInt32LE(range.lowKHz); + writer.writeUInt32LE(range.highKHz); + } + return writer.toBytes(); + } + + /// STATS_TYPE_RADIO: [24][1][noise i16][rssi i8][snr*4 i8][tx u32][rx u32]. + static Uint8List radioStats({ + required int noiseFloorDbm, + required int lastRssiDbm, + required int lastSnrQuarterDb, + required int txAirSecs, + required int rxAirSecs, + }) { + final data = ByteData(14); + data.setUint8(0, respCodeStats); + data.setUint8(1, statsTypeRadio); + data.setInt16(2, noiseFloorDbm, Endian.little); + data.setInt8(4, lastRssiDbm); + data.setInt8(5, lastSnrQuarterDb); + data.setUint32(6, txAirSecs, Endian.little); + data.setUint32(10, rxAirSecs, Endian.little); + return data.buffer.asUint8List(); + } +} diff --git a/lib/review_mode/review_mode.dart b/lib/review_mode/review_mode.dart new file mode 100644 index 00000000..4a93126b --- /dev/null +++ b/lib/review_mode/review_mode.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../screens/channels_screen.dart'; + +export 'review_mode_banner.dart'; +export 'review_mode_entry.dart'; + +/// Asks for confirmation, connects to the simulated radio and opens the app. +Future enterReviewMode(BuildContext context) async { + final navigator = Navigator.of(context); + final messenger = ScaffoldMessenger.of(context); + final connector = context.read(); + final l10n = context.l10n; + + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(dialogContext.l10n.reviewMode_dialogTitle), + content: Text(dialogContext.l10n.reviewMode_dialogBody), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(dialogContext.l10n.reviewMode_cancel), + ), + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text(dialogContext.l10n.reviewMode_confirm), + ), + ], + ), + ); + if (confirmed != true || !navigator.mounted) return; + + // Progress dialog on the root navigator while connecting. + showDialog( + context: navigator.context, + barrierDismissible: false, + builder: (_) => const PopScope( + canPop: false, + child: Center(child: CircularProgressIndicator()), + ), + ); + + Object? error; + try { + await connector.connectReview(); + } catch (e) { + error = e; + } + + if (!navigator.mounted) return; + navigator.pop(); // progress dialog + + if (error != null) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.reviewMode_connectFailed(error.toString()))), + ); + return; + } + // The connect may have been ignored (another connection was in progress) + // or cancelled by a disconnect while it was running. + if (!connector.isReviewMode || !connector.isConnected) return; + + navigator.push(MaterialPageRoute(builder: (_) => const ChannelsScreen())); +} diff --git a/lib/review_mode/review_mode_banner.dart b/lib/review_mode/review_mode_banner.dart new file mode 100644 index 00000000..ff137d25 --- /dev/null +++ b/lib/review_mode/review_mode_banner.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../theme/mesh_theme.dart'; + +/// Strip shown on top of main screens while the simulated radio is active. +class ReviewModeBanner extends StatelessWidget { + const ReviewModeBanner({super.key}); + + @override + Widget build(BuildContext context) { + final connector = context.watch(); + if (!connector.isReviewMode) return const SizedBox.shrink(); + + final l10n = context.l10n; + const textStyle = TextStyle( + color: MeshPalette.ink, + fontSize: 16, + fontWeight: FontWeight.w700, + ); + final buttonStyle = TextButton.styleFrom( + foregroundColor: MeshPalette.warn, + textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700), + minimumSize: const Size(48, 48), + ); + + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: const BoxDecoration( + color: MeshPalette.bg3, + border: Border(bottom: BorderSide(color: MeshPalette.warnLine)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.science, color: MeshPalette.warn, size: 24), + const SizedBox(width: 8), + Expanded(child: Text(l10n.reviewMode_banner, style: textStyle)), + ], + ), + Wrap( + spacing: 8, + children: [ + TextButton( + style: buttonStyle, + onPressed: () { + connector.sendReviewTestMessage(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.reviewMode_testSent)), + ); + }, + child: Text(l10n.reviewMode_sendTest), + ), + TextButton( + style: buttonStyle, + // The screens hosting the banner return to the Connect screen + // themselves once disconnected. + onPressed: () => connector.disconnect(manual: true), + child: Text(l10n.reviewMode_exit), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/review_mode/review_mode_entry.dart b/lib/review_mode/review_mode_entry.dart new file mode 100644 index 00000000..5f36ae4d --- /dev/null +++ b/lib/review_mode/review_mode_entry.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; + +import 'review_mode.dart'; + +/// Hidden entry point: long-pressing [child] offers to enter review mode. +class ReviewModeLongPress extends StatelessWidget { + final Widget child; + + const ReviewModeLongPress({super.key, required this.child}); + + @override + Widget build(BuildContext context) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onLongPress: () => enterReviewMode(context), + child: child, + ); + } +} diff --git a/lib/review_mode/review_mode_storage.dart b/lib/review_mode/review_mode_storage.dart new file mode 100644 index 00000000..692ac5ee --- /dev/null +++ b/lib/review_mode/review_mode_storage.dart @@ -0,0 +1,55 @@ +import '../services/app_settings_service.dart'; +import '../storage/legacy_key_migration.dart'; +import '../storage/prefs_manager.dart'; +import 'review_radio.dart'; + +/// Muted channel names as they were when review mode started. Persisted so an +/// interrupted session (crash, app killed) is still undone on the next launch. +const _savedMutedChannelsKey = 'review_mode_saved_muted_channels'; + +/// Deletes every persisted per-radio preference written while review mode was +/// active. All per-radio stores (contacts, channels, messages, unread counts, +/// channel/contact settings, regions, discovery cache, path history, ...) embed +/// the first 10 hex characters of the radio's public key in their key, so the +/// simulated radio's fixed prefix identifies exactly its data and nothing else. +Future clearReviewModeData() async { + final prefs = PrefsManager.instance; + final prefix = ReviewRadio.storagePrefix; + final keys = prefs.getKeys().where((key) => key.contains(prefix)).toList(); + for (final key in keys) { + await prefs.remove(key); + } +} + +/// Starts a review session from a clean slate. +/// +/// The simulated radio's scope never adopts legacy unscoped keys, so real +/// radio data cannot be pulled into it. Channel mutes are app-wide and keyed +/// by channel name (muting the simulated "Public" would mute the real one), +/// so the current mutes are saved for [endReviewModeSession] to put back. +Future beginReviewModeSession(AppSettingsService? settings) async { + scopesWithoutLegacyMigration.add(ReviewRadio.storagePrefix); + await clearReviewModeData(); + final prefs = PrefsManager.instance; + // An earlier interrupted session's record holds the real pre-review state. + if (settings != null && !prefs.containsKey(_savedMutedChannelsKey)) { + await prefs.setStringList( + _savedMutedChannelsKey, + settings.settings.mutedChannels.toList(), + ); + } +} + +/// Deletes the review session's data and restores the channel mutes saved by +/// [beginReviewModeSession]. Also called at startup to finish a session that +/// was interrupted; it does nothing when no session was left behind. +Future endReviewModeSession(AppSettingsService? settings) async { + await clearReviewModeData(); + final prefs = PrefsManager.instance; + final savedMutes = prefs.getStringList(_savedMutedChannelsKey); + if (savedMutes == null || settings == null) return; + await settings.updateSettings( + settings.settings.copyWith(mutedChannels: savedMutes.toSet()), + ); + await prefs.remove(_savedMutedChannelsKey); +} diff --git a/lib/review_mode/review_radio.dart b/lib/review_mode/review_radio.dart new file mode 100644 index 00000000..7ff6ec32 --- /dev/null +++ b/lib/review_mode/review_radio.dart @@ -0,0 +1,624 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +import '../connector/meshcore_protocol.dart'; +import '../connector/pending_command_replies.dart'; +import '../services/message_retry_service.dart'; +import 'review_frames.dart'; +import 'review_script.dart'; + +/// A simulated MeshCore radio that speaks the companion binary protocol. +class ReviewRadio { + ReviewRadio({ + this.scheduledMessageInterval = const Duration(seconds: 45), + this.ackDelay = const Duration(milliseconds: 1500), + this.replyDelay = const Duration(seconds: 4), + }) { + _seedState(); + } + + /// 64 lowercase hex chars, fixed and obviously fake. + static const String selfPublicKeyHex = + 'ee5e04b332b386b6cce8355ccf27fffd3a98b7a7a5b9b3a550c039c6ebae38e4'; + + /// First 10 hex chars of [selfPublicKeyHex], the per-radio storage scope. + static String get storagePrefix => selfPublicKeyHex.substring(0, 10); + + final Duration scheduledMessageInterval; + final Duration ackDelay; + final Duration replyDelay; + + final StreamController _controller = + StreamController.broadcast(); + final List _outbox = []; + final Set _timers = {}; + final List _messageQueue = []; + final List<_Contact> _contacts = []; + final Map _channels = {}; + final Uint8List _selfKey = hexToPubKey(selfPublicKeyHex); + + Timer? _flushTimer; + Timer? _scheduledTimer; + bool _disposed = false; + bool _nextScheduledIsDirect = true; + int _directPoolIndex = 0; + int _channelPoolIndex = 0; + int _directReplyIndex = 0; + int _channelReplyIndex = 0; + + String _name = ReviewScript.selfName; + int _latitudeE6 = ReviewScript.selfLatitudeE6; + int _longitudeE6 = ReviewScript.selfLongitudeE6; + int _frequencyHz = ReviewScript.frequencyHz; + int _bandwidthHz = ReviewScript.bandwidthHz; + int _spreadingFactor = ReviewScript.spreadingFactor; + int _codingRate = ReviewScript.codingRate; + int _txPowerDbm = ReviewScript.txPowerDbm; + int _autoAddFlags = + autoAddChatFlag | autoAddRepeaterFlag | autoAddRoomServerFlag; + int _timeOffsetSecs = 0; + + /// Frames radio to app. Each event is one complete companion frame. + Stream get frames => _controller.stream; + + int get _nowSecs => + DateTime.now().millisecondsSinceEpoch ~/ 1000 + _timeOffsetSecs; + + void _seedState() { + final now = _nowSecs; + for (final c in ReviewScript.contacts) { + _contacts.add( + _Contact( + publicKey: hexToPubKey(c.publicKeyHex), + type: c.type, + path: c.pathHex.isEmpty ? Uint8List(0) : hex2Uint8List(c.pathHex), + name: c.name, + lastAdvertSecs: now - c.lastAdvertAgoSecs, + latitudeE6: (c.latitude * 1e6).round(), + longitudeE6: (c.longitude * 1e6).round(), + lastModSecs: now, + ), + ); + } + for (final c in ReviewScript.channels) { + _channels[c.index] = _Channel(c.name, hex2Uint8List(c.pskHex)); + } + + final history = <_SeedEntry>[ + for (final m in ReviewScript.seedDirectMessages) + _SeedEntry( + m.agoSecs, + ReviewFrames.contactMessage( + senderPublicKey: _contacts[m.contactIndex].publicKey, + text: m.text, + timestampSecs: now - m.agoSecs, + pathLen: ReviewScript.contacts[m.contactIndex].hopCount, + ), + ), + for (final m in ReviewScript.seedChannelMessages) + _SeedEntry( + m.agoSecs, + ReviewFrames.channelMessage( + channelIndex: m.channelIndex, + sender: m.sender, + message: m.text, + timestampSecs: now - m.agoSecs, + path: _pathForSender(m.sender), + ), + ), + ]..sort((a, b) => b.agoSecs.compareTo(a.agoSecs)); + for (final entry in history) { + _messageQueue.add(entry.frame); + } + } + + Uint8List? _pathForSender(String sender) { + for (final c in _contacts) { + if (c.name == sender && c.path.isNotEmpty) return c.path; + } + return null; + } + + /// Starts the scheduled incoming-message timer. + void start() { + if (_disposed || _scheduledTimer != null) return; + _scheduledTimer = Timer.periodic(scheduledMessageInterval, (_) { + _enqueueScheduledMessage(); + }); + } + + /// Immediately queues one incoming message and pushes MSG_WAITING. + void sendTestMessage() { + if (_disposed) return; + _enqueueScheduledMessage(); + } + + void _enqueueScheduledMessage() { + if (_disposed) return; + final now = _nowSecs; + if (_nextScheduledIsDirect) { + final pool = ReviewScript.incomingDirectPool; + final line = pool[_directPoolIndex++ % pool.length]; + _messageQueue.add( + ReviewFrames.contactMessage( + senderPublicKey: _contacts[line.contactIndex].publicKey, + text: line.text, + timestampSecs: now, + pathLen: ReviewScript.contacts[line.contactIndex].hopCount, + ), + ); + } else { + final pool = ReviewScript.incomingChannelPool; + final line = pool[_channelPoolIndex++ % pool.length]; + _messageQueue.add( + ReviewFrames.channelMessage( + channelIndex: line.channelIndex, + sender: line.sender, + message: line.text, + timestampSecs: now, + path: _pathForSender(line.sender), + ), + ); + } + _nextScheduledIsDirect = !_nextScheduledIsDirect; + _emit([ReviewFrames.msgWaiting()]); + } + + /// Frame app to radio. Responses are emitted asynchronously. + void handle(Uint8List frame) { + if (_disposed || frame.isEmpty) return; + final code = frame[0]; + switch (code) { + case cmdDeviceQuery: + _emit([ + ReviewFrames.deviceInfo( + firmwareVerCode: ReviewScript.firmwareVerCode, + maxContacts: ReviewScript.maxContacts, + maxChannels: ReviewScript.maxChannels, + ), + ]); + break; + case cmdAppStart: + _emit([_selfInfoFrame()]); + break; + case cmdGetContacts: + _handleGetContacts(frame); + break; + case cmdGetContactByKey: + _handleGetContactByKey(frame); + break; + case cmdGetChannel: + _handleGetChannel(frame); + break; + case cmdSetChannel: + _handleSetChannel(frame); + break; + case cmdSyncNextMessage: + _emit([ + _messageQueue.isEmpty + ? ReviewFrames.noMoreMessages() + : _messageQueue.removeAt(0), + ]); + break; + case cmdSendTxtMsg: + _handleSendText(frame); + break; + case cmdSendChannelTxtMsg: + _handleSendChannelText(frame); + break; + case cmdGetBattAndStorage: + _emit([ + ReviewFrames.battAndStorage( + millivolts: 3980, + usedKb: 412, + totalKb: 1792, + ), + ]); + break; + case cmdGetDeviceTime: + _emit([ReviewFrames.currTime(_nowSecs)]); + break; + case cmdSetDeviceTime: + if (frame.length >= 5) { + _timeOffsetSecs = + readUint32LE(frame, 1) - + DateTime.now().millisecondsSinceEpoch ~/ 1000; + } + _emit([ReviewFrames.ok()]); + break; + case cmdGetCustomVar: + _emit([ReviewFrames.customVars('gps:0')]); + break; + case cmdGetAutoAddConfig: + _emit([ReviewFrames.autoAddConfig(flags: _autoAddFlags)]); + break; + case cmdSetAutoAddConfig: + if (frame.length >= 2) _autoAddFlags = frame[1]; + _emit([ReviewFrames.ok()]); + break; + case cmdGetAllowedRepeatFreq: + _emit([ + ReviewFrames.allowedRepeatFreq(const [ + (lowKHz: 433000, highKHz: 433000), + (lowKHz: 869000, highKHz: 869000), + (lowKHz: 918000, highKHz: 918000), + ]), + ]); + break; + case cmdGetStats: + _emit([ + frame.length >= 2 && frame[1] == statsTypeRadio + ? ReviewFrames.radioStats( + noiseFloorDbm: -112, + lastRssiDbm: -78, + lastSnrQuarterDb: 28, + txAirSecs: 12, + rxAirSecs: 48, + ) + : ReviewFrames.err(), + ]); + break; + case cmdSetAdvertName: + _name = _readCString(frame, 1, maxNameSize - 1); + _emit([ReviewFrames.ok()]); + break; + case cmdSetAdvertLatLon: + if (frame.length >= 9) { + _latitudeE6 = readInt32LE(frame, 1); + _longitudeE6 = readInt32LE(frame, 5); + } + _emit([ReviewFrames.ok()]); + break; + case cmdSetRadioParams: + if (frame.length >= 11) { + _frequencyHz = readUint32LE(frame, 1); + _bandwidthHz = readUint32LE(frame, 5); + _spreadingFactor = frame[9]; + _codingRate = frame[10]; + } + _emit([ReviewFrames.ok()]); + break; + case cmdSetRadioTxPower: + if (frame.length >= 2) _txPowerDbm = frame[1]; + _emit([ReviewFrames.ok()]); + break; + case cmdRemoveContact: + if (frame.length >= 1 + pubKeySize) { + final key = frame.sublist(1, 1 + pubKeySize); + _contacts.removeWhere((c) => listEquals(c.publicKey, key)); + } + _emit([ReviewFrames.ok()]); + break; + case cmdSendLogin: + _handleLogin(frame); + break; + case cmdSendStatusReq: + case cmdSendTracePath: + case cmdSendBinaryReq: + case cmdSendAnonReq: + _emit([ReviewFrames.err()]); + break; + case cmdSendTelemetryReq: + // The 4-byte "self" form is answered with a push the app does not + // track; remote requests are answered with ERR. + if (frame.length > 4) _emit([ReviewFrames.err()]); + break; + default: + // Setters, advert, reset path, flood scope, import/export and any + // other command the app tracks get OK; untracked ones get nothing. + final reply = replyCodeForCommand(frame); + if (reply == respCodeOk) { + _emit([ReviewFrames.ok()]); + } else if (reply != null) { + _emit([ReviewFrames.err()]); + } + } + } + + Uint8List _selfInfoFrame() => ReviewFrames.selfInfo( + publicKey: _selfKey, + name: _name, + latitudeE6: _latitudeE6, + longitudeE6: _longitudeE6, + frequencyHz: _frequencyHz, + bandwidthHz: _bandwidthHz, + spreadingFactor: _spreadingFactor, + codingRate: _codingRate, + txPowerDbm: _txPowerDbm, + maxTxPowerDbm: ReviewScript.maxTxPowerDbm, + ); + + Uint8List _contactFrame(_Contact c) => ReviewFrames.contact( + publicKey: c.publicKey, + type: c.type, + path: c.path, + name: c.name, + lastAdvertSecs: c.lastAdvertSecs, + latitudeE6: c.latitudeE6, + longitudeE6: c.longitudeE6, + lastModSecs: c.lastModSecs, + ); + + void _handleGetContacts(Uint8List frame) { + final since = frame.length >= 5 ? readUint32LE(frame, 1) : 0; + final matching = _contacts.where((c) => c.lastModSecs > since).toList(); + var mostRecent = since; + for (final c in matching) { + if (c.lastModSecs > mostRecent) mostRecent = c.lastModSecs; + } + _emit([ + ReviewFrames.contactsStart(_contacts.length), + for (final c in matching) _contactFrame(c), + ReviewFrames.endOfContacts(mostRecent), + ]); + } + + void _handleGetContactByKey(Uint8List frame) { + if (frame.length >= 1 + pubKeySize) { + final key = frame.sublist(1, 1 + pubKeySize); + for (final c in _contacts) { + if (listEquals(c.publicKey, key)) { + _emit([_contactFrame(c)]); + return; + } + } + } + _emit([ReviewFrames.err(ReviewFrames.errNotFound)]); + } + + void _handleGetChannel(Uint8List frame) { + final index = frame.length >= 2 ? frame[1] : 0; + if (index >= ReviewScript.maxChannels) { + _emit([ReviewFrames.err(ReviewFrames.errNotFound)]); + return; + } + final channel = _channels[index]; + _emit([ + ReviewFrames.channelInfo( + index: index, + name: channel?.name ?? '', + psk: channel?.psk ?? Uint8List(16), + ), + ]); + } + + void _handleSetChannel(Uint8List frame) { + // [cmd][idx][name x32][psk x16] + if (frame.length >= 50) { + final index = frame[1]; + final name = _readCString(frame, 2, 32); + final psk = Uint8List.fromList(frame.sublist(34, 50)); + if (name.isEmpty && psk.every((b) => b == 0)) { + _channels.remove(index); + } else { + _channels[index] = _Channel(name, psk); + } + } + _emit([ReviewFrames.ok()]); + } + + void _handleSendText(Uint8List frame) { + // [cmd][txt_type][attempt][timestamp x4][pub_key_prefix x6][text...]\0 + if (frame.length < 13) { + _emit([ReviewFrames.err()]); + return; + } + final attempt = frame[2]; + final timestamp = readUint32LE(frame, 3); + final prefix = frame.sublist(7, 13); + final text = _readCString(frame, 13, frame.length - 13); + + final contact = _contactByPrefix(prefix); + if (contact == null) { + _emit([ReviewFrames.err(ReviewFrames.errNotFound)]); + return; + } + + final ackHash = MessageRetryService.computeExpectedAckHash( + timestamp, + attempt, + text, + _selfKey, + ); + final tripMs = ackDelay.inMilliseconds; + _emit([ + ReviewFrames.sent( + // Every simulated contact has a known path; an empty one is a + // direct neighbour, so sends are never flooded. + flood: false, + ackHash: ackHash, + timeoutMs: 8000, + ), + ]); + _later(ackDelay, () { + _emit([ReviewFrames.sendConfirmed(ackHash: ackHash, tripTimeMs: tripMs)]); + }); + + if (contact.type == advTypeChat || contact.type == advTypeRoom) { + _later(ackDelay + replyDelay, () { + final replies = ReviewScript.directReplies; + _messageQueue.add( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: replies[_directReplyIndex++ % replies.length], + timestampSecs: _nowSecs, + pathLen: contact.path.length, + ), + ); + _emit([ReviewFrames.msgWaiting()]); + }); + } + } + + void _handleLogin(Uint8List frame) { + // [cmd][pub_key x32][password...] + _Contact? contact; + if (frame.length >= 1 + pubKeySize) { + final key = frame.sublist(1, 1 + pubKeySize); + for (final c in _contacts) { + if (listEquals(c.publicKey, key)) contact = c; + } + } + if (contact == null) { + _emit([ReviewFrames.err(ReviewFrames.errNotFound)]); + return; + } + final target = contact; + // The firmware tags a login with the first 4 bytes of the target key. + _emit([ + ReviewFrames.sent( + flood: false, + ackHash: readUint32LE(target.publicKey, 0), + timeoutMs: 8000, + ), + ]); + // Room servers accept any password so reviewers can open the room chat. + // Repeater administration needs real hardware, so it fails right away + // instead of leaving the login dialog waiting for a timeout. + _later(ackDelay, () { + _emit([ + target.type == advTypeRoom + ? ReviewFrames.loginSuccess( + publicKey: target.publicKey, + serverTimeSecs: _nowSecs, + ) + : ReviewFrames.loginFail(publicKey: target.publicKey), + ]); + }); + } + + void _handleSendChannelText(Uint8List frame) { + // [cmd][txt_type][channel_idx][timestamp x4][text...]\0 + if (frame.length < 8) { + _emit([ReviewFrames.err()]); + return; + } + final channelIndex = frame[2]; + _emit([ReviewFrames.ok()]); + + final members = ReviewScript.channelMembers[channelIndex]; + if (members == null || + members.isEmpty || + !_channels.containsKey(channelIndex)) { + return; + } + _later(replyDelay, () { + final replies = ReviewScript.channelReplies; + final index = _channelReplyIndex++; + final sender = members[index % members.length]; + _messageQueue.add( + ReviewFrames.channelMessage( + channelIndex: channelIndex, + sender: sender, + message: replies[index % replies.length], + timestampSecs: _nowSecs, + path: _pathForSender(sender), + ), + ); + _emit([ReviewFrames.msgWaiting()]); + }); + } + + _Contact? _contactByPrefix(List prefix) { + for (final c in _contacts) { + if (c.publicKey.length >= prefix.length && + listEquals(c.publicKey.sublist(0, prefix.length), prefix)) { + return c; + } + } + return null; + } + + String _readCString(Uint8List frame, int start, int maxLength) { + final end = (start + maxLength).clamp(start, frame.length); + final bytes = []; + for (var i = start; i < end; i++) { + if (frame[i] == 0) break; + bytes.add(frame[i]); + } + return utf8.decode(bytes, allowMalformed: true); + } + + void _later(Duration delay, void Function() action) { + if (_disposed) return; + late final Timer timer; + timer = Timer(delay, () { + _timers.remove(timer); + if (!_disposed) action(); + }); + _timers.add(timer); + } + + /// Queues frames and flushes them from a timer, so a response is never + /// delivered synchronously inside [handle] and ordering is preserved. + void _emit(List frames) { + if (_disposed) return; + _outbox.addAll(frames); + _flushTimer ??= Timer(Duration.zero, _flush); + } + + void _flush() { + _flushTimer = null; + if (_disposed) return; + final pending = List.of(_outbox); + _outbox.clear(); + for (final frame in pending) { + if (_disposed || _controller.isClosed) return; + _controller.add(frame); + } + } + + /// Cancels all timers and closes the stream. Safe to call twice. + void dispose() { + if (_disposed) return; + _disposed = true; + _scheduledTimer?.cancel(); + _scheduledTimer = null; + _flushTimer?.cancel(); + _flushTimer = null; + for (final t in _timers) { + t.cancel(); + } + _timers.clear(); + _outbox.clear(); + unawaited(_controller.close()); + } +} + +class _Contact { + final Uint8List publicKey; + final int type; + final Uint8List path; + final String name; + final int lastAdvertSecs; + final int latitudeE6; + final int longitudeE6; + final int lastModSecs; + + _Contact({ + required this.publicKey, + required this.type, + required this.path, + required this.name, + required this.lastAdvertSecs, + required this.latitudeE6, + required this.longitudeE6, + required this.lastModSecs, + }); +} + +class _Channel { + final String name; + final Uint8List psk; + + _Channel(this.name, this.psk); +} + +class _SeedEntry { + final int agoSecs; + final Uint8List frame; + + _SeedEntry(this.agoSecs, this.frame); +} diff --git a/lib/review_mode/review_script.dart b/lib/review_mode/review_script.dart new file mode 100644 index 00000000..c37a1acf --- /dev/null +++ b/lib/review_mode/review_script.dart @@ -0,0 +1,297 @@ +import '../connector/meshcore_protocol.dart'; + +/// A contact in the simulated radio's contact table. +class ReviewContact { + final String name; + final String publicKeyHex; + final int type; + + /// One-byte path hashes, as hex. Empty means a direct (zero hop) path. + final String pathHex; + final double latitude; + final double longitude; + final int lastAdvertAgoSecs; + + const ReviewContact({ + required this.name, + required this.publicKeyHex, + required this.type, + required this.pathHex, + required this.latitude, + required this.longitude, + required this.lastAdvertAgoSecs, + }); + + int get hopCount => pathHex.length ~/ 2; +} + +/// A channel slot configured on the simulated radio. +class ReviewChannel { + final int index; + final String name; + final String pskHex; + + const ReviewChannel({ + required this.index, + required this.name, + required this.pskHex, + }); +} + +/// A direct message from a script contact. +class ReviewDirectLine { + final int contactIndex; + final String text; + final int agoSecs; + + const ReviewDirectLine({ + required this.contactIndex, + required this.text, + this.agoSecs = 0, + }); +} + +/// A channel message from a script member. +class ReviewChannelLine { + final int channelIndex; + final String sender; + final String text; + final int agoSecs; + + const ReviewChannelLine({ + required this.channelIndex, + required this.sender, + required this.text, + this.agoSecs = 0, + }); +} + +/// The fake world the simulated radio lives in. +class ReviewScript { + ReviewScript._(); + + static const String selfName = 'Review Radio'; + static const int selfLatitudeE6 = 45515232; + static const int selfLongitudeE6 = -122678385; + static const int frequencyHz = 910525000; + static const int bandwidthHz = 62500; + static const int spreadingFactor = 7; + static const int codingRate = 5; + static const int txPowerDbm = 20; + static const int maxTxPowerDbm = 22; + + static const int firmwareVerCode = 14; + static const int maxContacts = 100; + static const int maxChannels = 8; + + static const List contacts = [ + ReviewContact( + name: 'Maya', + publicKeyHex: + 'a95db5b0ac159e4384ff55ef91c94a98dc563d66a88e7b027fcd5190c0f5bed5', + type: advTypeChat, + pathHex: 'a1', + latitude: 45.5231, + longitude: -122.6765, + lastAdvertAgoSecs: 600, + ), + ReviewContact( + name: 'Jordan', + publicKeyHex: + '136c67657614311f32238751044a0a3c0294f2a521e573afa8e496992d3786ba', + type: advTypeChat, + pathHex: 'a1c4', + latitude: 45.5089, + longitude: -122.6912, + lastAdvertAgoSecs: 1800, + ), + ReviewContact( + name: 'Sam', + publicKeyHex: + 'e96e02d8e47f2a7c03be5117b3ed175c52aa30fb22028cf9c96f261563577605', + type: advTypeChat, + pathHex: '', + latitude: 45.5176, + longitude: -122.6701, + lastAdvertAgoSecs: 240, + ), + ReviewContact( + name: 'Ranger Pat', + publicKeyHex: + 'dbc4a04327176e6577b4da46df04564150053960eba5d89587dad1f76a818d80', + type: advTypeChat, + pathHex: 'a1c47f', + latitude: 45.5402, + longitude: -122.7120, + lastAdvertAgoSecs: 3600, + ), + ReviewContact( + name: 'Hilltop Repeater', + publicKeyHex: + '409e364456fa93642cd24878f532fffe31e3aae5944d04239a7d023e66ebdbe3', + type: advTypeRepeater, + pathHex: '', + latitude: 45.5298, + longitude: -122.7064, + lastAdvertAgoSecs: 120, + ), + ReviewContact( + name: 'Trailhead Room', + publicKeyHex: + '08d33503ee27d4c13055d0cefec5e730be4ef2e41cd6cfce434936ec1e7c9d4b', + type: advTypeRoom, + pathHex: 'a1', + latitude: 45.5350, + longitude: -122.6650, + lastAdvertAgoSecs: 900, + ), + ]; + + static const List channels = [ + ReviewChannel( + index: 0, + name: 'Public', + pskHex: '8b3387e9c5cdea6ac9e5edbaa115cd72', + ), + ReviewChannel( + index: 1, + name: 'Hiking Group', + pskHex: 'dd488fa58a29956b6271b573e1a33ac5', + ), + ReviewChannel( + index: 2, + name: 'Local Net', + pskHex: '8bca9c2e3ef52ebcd61d30ec6c724a25', + ), + ]; + + /// Senders that may speak in each channel, by channel index. + static const Map> channelMembers = { + 0: ['Maya', 'Sam'], + 1: ['Jordan', 'Sam'], + 2: ['Ranger Pat', 'Maya'], + }; + + static const List seedDirectMessages = [ + ReviewDirectLine( + contactIndex: 0, + text: 'Hey! Are you heading up to the ridge this weekend?', + agoSecs: 7200, + ), + ReviewDirectLine( + contactIndex: 0, + text: 'The repeater on the hill is showing a great signal today.', + agoSecs: 6900, + ), + ReviewDirectLine( + contactIndex: 1, + text: 'Signal check from the trailhead. Reading you loud and clear.', + agoSecs: 3300, + ), + ]; + + static const List seedChannelMessages = [ + ReviewChannelLine( + channelIndex: 0, + sender: 'Maya', + text: 'Good morning mesh! Anyone on the air?', + agoSecs: 5400, + ), + ReviewChannelLine( + channelIndex: 1, + sender: 'Jordan', + text: 'Planning to leave the trailhead at 8 on Saturday.', + agoSecs: 4800, + ), + ReviewChannelLine( + channelIndex: 1, + sender: 'Sam', + text: 'I will bring the spare battery pack.', + agoSecs: 4500, + ), + ReviewChannelLine( + channelIndex: 2, + sender: 'Ranger Pat', + text: 'Weekly net check-in starts at 7 pm. Please report your signal.', + agoSecs: 2400, + ), + ]; + + /// Scheduled incoming direct messages, cycled in order. + static const List incomingDirectPool = [ + ReviewDirectLine( + contactIndex: 0, + text: 'Just got a message through the hilltop repeater. Nice!', + ), + ReviewDirectLine( + contactIndex: 1, + text: 'Battery is at 80 percent. Plenty for the whole hike.', + ), + ReviewDirectLine( + contactIndex: 2, + text: 'Can you hear me from the creek crossing?', + ), + ReviewDirectLine( + contactIndex: 3, + text: 'Trail conditions are good. A little muddy near the bridge.', + ), + ReviewDirectLine( + contactIndex: 0, + text: 'Testing a new antenna today. How is my signal?', + ), + ReviewDirectLine( + contactIndex: 2, + text: 'Heading back down now. See you at the trailhead.', + ), + ]; + + /// Scheduled incoming channel messages, cycled in order. + static const List incomingChannelPool = [ + ReviewChannelLine( + channelIndex: 0, + sender: 'Sam', + text: 'Radio check, one two three. Anyone copy?', + ), + ReviewChannelLine( + channelIndex: 1, + sender: 'Jordan', + text: 'We reached the lookout. The view is great!', + ), + ReviewChannelLine( + channelIndex: 2, + sender: 'Ranger Pat', + text: 'Reminder: the net is open to everyone. Say hello.', + ), + ReviewChannelLine( + channelIndex: 0, + sender: 'Maya', + text: 'Clear skies and a strong signal across town today.', + ), + ReviewChannelLine( + channelIndex: 1, + sender: 'Sam', + text: 'Anyone need water? I am refilling at the next stop.', + ), + ReviewChannelLine( + channelIndex: 2, + sender: 'Maya', + text: 'Checking in from the east side. Copy you five by five.', + ), + ]; + + /// Auto-replies to a direct message the app sends. + static const List directReplies = [ + 'Got it, thanks!', + 'Sounds good to me.', + 'Message received loud and clear.', + 'Thanks for the update. Talk soon!', + ]; + + /// Auto-replies to a channel message the app sends. + static const List channelReplies = [ + 'Copy that!', + 'Welcome to the mesh!', + 'Heard you loud and clear.', + 'Thanks for checking in.', + ]; +} diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 199702e0..a8b9410b 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -35,6 +35,7 @@ import 'community_qr_scanner_screen.dart'; import 'contacts_screen.dart'; import 'map_screen.dart'; import 'settings_screen.dart'; +import '../review_mode/review_mode_banner.dart'; class ChannelsScreen extends StatefulWidget { final bool hideBackButton; @@ -166,172 +167,187 @@ class _ChannelsScreenState extends State ), ], ), - body: RefreshIndicator( - onRefresh: () async { - await context.read().getChannels(force: true); - }, - child: () { - final channels = connector.channels; - final waitingForFirstChannel = - connector.isLoadingChannels && channels.isEmpty; + body: Column( + children: [ + const ReviewModeBanner(), + Expanded( + child: RefreshIndicator( + onRefresh: () async { + await context.read().getChannels( + force: true, + ); + }, + child: () { + final channels = connector.channels; + final waitingForFirstChannel = + connector.isLoadingChannels && channels.isEmpty; - // Only block the list while the first channel is actively loading. - // If the initial sync aborts, show cached/partial channels instead - // of trapping the user behind an idle spinner. - if (waitingForFirstChannel) { - return const Center(child: CircularProgressIndicator()); - } + // Only block the list while the first channel is actively loading. + // If the initial sync aborts, show cached/partial channels instead + // of trapping the user behind an idle spinner. + if (waitingForFirstChannel) { + return const Center(child: CircularProgressIndicator()); + } - if (channels.isEmpty) { - return ListView( - children: [ - SizedBox( - height: MediaQuery.of(context).size.height - 200, - child: EmptyState( - icon: Icons.tag, - title: context.l10n.channels_noChannelsConfigured, - action: FilledButton.icon( - onPressed: () => _addPublicChannel(context, connector), - icon: const Icon(Icons.public), - label: Text(context.l10n.channels_addPublicChannel), - ), - ), - ), - ], - ); - } + if (channels.isEmpty) { + return ListView( + children: [ + SizedBox( + height: MediaQuery.of(context).size.height - 200, + child: EmptyState( + icon: Icons.tag, + title: context.l10n.channels_noChannelsConfigured, + action: FilledButton.icon( + onPressed: () => + _addPublicChannel(context, connector), + icon: const Icon(Icons.public), + label: Text( + context.l10n.channels_addPublicChannel, + ), + ), + ), + ), + ], + ); + } - final filteredChannels = _filterAndSortChannels( - channels, - connector, - viewState, - ); + final filteredChannels = _filterAndSortChannels( + channels, + connector, + viewState, + ); - return Column( - children: [ - Padding( - padding: const EdgeInsets.all(8.0), - child: TextField( - controller: _searchController, - decoration: InputDecoration( - hintText: context.l10n.channels_searchChannels, - prefixIcon: const Icon(Icons.search), - suffixIcon: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (viewState.channelsSearchText.isNotEmpty) - IconButton( - icon: const Icon(Icons.clear), - tooltip: context.l10n.common_clearSearch, - onPressed: () { - _searchDebounce?.cancel(); - _searchDebounce = null; - _searchController.clear(); + return Column( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: context.l10n.channels_searchChannels, + prefixIcon: const Icon(Icons.search), + suffixIcon: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (viewState.channelsSearchText.isNotEmpty) + IconButton( + icon: const Icon(Icons.clear), + tooltip: context.l10n.common_clearSearch, + onPressed: () { + _searchDebounce?.cancel(); + _searchDebounce = null; + _searchController.clear(); + context + .read() + .setChannelsSearchText(''); + }, + ), + _buildFilterButton(viewState), + ], + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + ), + onChanged: (value) { + _searchDebounce?.cancel(); + _searchDebounce = Timer( + const Duration(milliseconds: 300), + () { + if (!mounted) return; context .read() - .setChannelsSearchText(''); + .setChannelsSearchText(value); }, - ), - _buildFilterButton(viewState), - ], - ), - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 12, - ), - ), - onChanged: (value) { - _searchDebounce?.cancel(); - _searchDebounce = Timer( - const Duration(milliseconds: 300), - () { - if (!mounted) return; - context - .read() - .setChannelsSearchText(value); - }, - ); - }, - ), - ), - Expanded( - child: filteredChannels.isEmpty - ? LayoutBuilder( - builder: (context, constraints) => ListView( - physics: const AlwaysScrollableScrollPhysics(), - children: [ - ConstrainedBox( - constraints: BoxConstraints( - minHeight: constraints.maxHeight, - ), - child: EmptyState( - icon: Icons.search_off, - title: context.l10n.channels_noChannelsFound, - ), - ), - ], - ), - ) - : (viewState.channelsSortOption == - ChannelSortOption.manual && - viewState.channelsSearchText.isEmpty) - ? ReorderableListView.builder( - padding: const EdgeInsets.only( - left: 0, - right: 0, - top: 8, - bottom: 88, - ), - buildDefaultDragHandles: false, - itemCount: filteredChannels.length, - onReorderItem: (oldIndex, newIndex) { - final reordered = List.from( - filteredChannels, - ); - final item = reordered.removeAt(oldIndex); - reordered.insert(newIndex, item); - unawaited( - connector.setChannelOrder( - reordered.map((c) => c.index).toList(), - ), - ); - }, - itemBuilder: (context, index) { - final channel = filteredChannels[index]; - return _buildChannelTile( - context, - connector, - channelMessageStore, - channel, - showDragHandle: true, - dragIndex: index, - listIndex: index, - ); - }, - ) - : ListView.builder( - padding: const EdgeInsets.only( - left: 0, - right: 0, - top: 8, - bottom: 88, - ), - itemCount: filteredChannels.length, - itemBuilder: (context, index) { - final channel = filteredChannels[index]; - return _buildChannelTile( - context, - connector, - channelMessageStore, - channel, - listIndex: index, ); }, ), - ), - ], - ); - }(), + ), + Expanded( + child: filteredChannels.isEmpty + ? LayoutBuilder( + builder: (context, constraints) => ListView( + physics: + const AlwaysScrollableScrollPhysics(), + children: [ + ConstrainedBox( + constraints: BoxConstraints( + minHeight: constraints.maxHeight, + ), + child: EmptyState( + icon: Icons.search_off, + title: context + .l10n + .channels_noChannelsFound, + ), + ), + ], + ), + ) + : (viewState.channelsSortOption == + ChannelSortOption.manual && + viewState.channelsSearchText.isEmpty) + ? ReorderableListView.builder( + padding: const EdgeInsets.only( + left: 0, + right: 0, + top: 8, + bottom: 88, + ), + buildDefaultDragHandles: false, + itemCount: filteredChannels.length, + onReorderItem: (oldIndex, newIndex) { + final reordered = List.from( + filteredChannels, + ); + final item = reordered.removeAt(oldIndex); + reordered.insert(newIndex, item); + unawaited( + connector.setChannelOrder( + reordered.map((c) => c.index).toList(), + ), + ); + }, + itemBuilder: (context, index) { + final channel = filteredChannels[index]; + return _buildChannelTile( + context, + connector, + channelMessageStore, + channel, + showDragHandle: true, + dragIndex: index, + listIndex: index, + ); + }, + ) + : ListView.builder( + padding: const EdgeInsets.only( + left: 0, + right: 0, + top: 8, + bottom: 88, + ), + itemCount: filteredChannels.length, + itemBuilder: (context, index) { + final channel = filteredChannels[index]; + return _buildChannelTile( + context, + connector, + channelMessageStore, + channel, + listIndex: index, + ); + }, + ), + ), + ], + ); + }(), + ), + ), + ], ), floatingActionButton: FloatingActionButton( onPressed: () => _showAddChannelDialog(context), diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index fea71961..a5d205bc 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -37,6 +37,7 @@ import 'chat_screen.dart'; import 'contact_qr_scanner_screen.dart'; import 'discovery_screen.dart'; import 'map_screen.dart'; +import '../review_mode/review_mode_banner.dart'; import 'repeater_hub_screen.dart'; import 'settings_screen.dart'; @@ -477,7 +478,12 @@ class _ContactsScreenState extends State ), ], ), - body: _buildContactsBody(context, connector), + body: Column( + children: [ + const ReviewModeBanner(), + Expanded(child: _buildContactsBody(context, connector)), + ], + ), floatingActionButton: FloatingActionButton( onPressed: () => _showAddContactSheet(context), child: const Icon(Icons.person_add), diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index 5d1d8278..c8305562 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -819,10 +819,7 @@ class _PathTraceMapScreenState extends State (c) => c.hasLocation && c.path.isNotEmpty && - _matchesHopPrefix( - _lastHopChunk(c.path, c.pathHashWidth), - hop, - ), + _matchesHopPrefix(_lastHopChunk(c.path, c.pathHashWidth), hop), ) .toList(); if (peers.isEmpty) return null; @@ -862,10 +859,7 @@ class _PathTraceMapScreenState extends State if (record.pathBytes.isEmpty) continue; final recordHops = PathHelper.splitPathBytes( record.pathBytes, - Contact.inferPathHashWidth( - record.hopCount, - record.pathBytes.length, - ), + Contact.inferPathHashWidth(record.hopCount, record.pathBytes.length), ); if (!seen.add(_pathKeyForHops(recordHops))) continue; if (altIndex >= kAlternatePathColors.length) break; diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart index a8c83723..9f4685e6 100644 --- a/lib/screens/scanner_screen.dart +++ b/lib/screens/scanner_screen.dart @@ -15,6 +15,7 @@ import '../widgets/device_tile.dart'; import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; import '../helpers/snack_bar_builder.dart'; +import '../review_mode/review_mode_entry.dart'; import 'channels_screen.dart'; import 'tcp_screen.dart'; import 'usb_screen.dart'; @@ -103,7 +104,9 @@ class _ScannerScreenState extends State { }, ) : null, - title: AdaptiveAppBarTitle(context.l10n.scanner_title), + title: ReviewModeLongPress( + child: AdaptiveAppBarTitle(context.l10n.scanner_title), + ), centerTitle: true, automaticallyImplyLeading: false, actions: [ diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index dbb676ac..ff33ba90 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -5,6 +5,7 @@ import 'package:meshcore_open/utils/app_logger.dart'; import '../models/channel_message.dart'; import '../models/translation_support.dart'; import '../helpers/smaz.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ChannelMessageStore { @@ -50,7 +51,8 @@ class ChannelMessageStore { final oldKey = '$_keyPrefix$channelIndex'; String? jsonString = prefs.getString(key); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(oldKey); prefs.remove(oldKey); diff --git a/lib/storage/channel_order_store.dart b/lib/storage/channel_order_store.dart index 88d3f7a6..3bc0c7dc 100644 --- a/lib/storage/channel_order_store.dart +++ b/lib/storage/channel_order_store.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ChannelOrderStore { @@ -27,7 +28,8 @@ class ChannelOrderStore { } final prefs = PrefsManager.instance; String? jsonString = prefs.getString(keyFor); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(_keyPrefix); prefs.remove(_keyPrefix); diff --git a/lib/storage/channel_settings_store.dart b/lib/storage/channel_settings_store.dart index 2415d01c..c20daad4 100644 --- a/lib/storage/channel_settings_store.dart +++ b/lib/storage/channel_settings_store.dart @@ -1,4 +1,5 @@ import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ChannelSettingsStore { @@ -25,7 +26,7 @@ class ChannelSettingsStore { final key = '$keyFor$channelIndex'; final oldKey = '$_keyPrefix$channelIndex'; bool? enabled = prefs.getBool(key); - if (enabled == null) { + if (enabled == null && canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load enabled = prefs.getBool(oldKey); prefs.remove(oldKey); diff --git a/lib/storage/channel_store.dart b/lib/storage/channel_store.dart index 4f40482a..67e3e438 100644 --- a/lib/storage/channel_store.dart +++ b/lib/storage/channel_store.dart @@ -3,6 +3,7 @@ import 'dart:typed_data'; import '../models/channel.dart'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ChannelStore { @@ -20,7 +21,8 @@ class ChannelStore { } final prefs = PrefsManager.instance; String? jsonString = prefs.getString(keyFor); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(_keyPrefix); prefs.remove(_keyPrefix); diff --git a/lib/storage/community_store.dart b/lib/storage/community_store.dart index 75c7daf8..3ceebf4b 100644 --- a/lib/storage/community_store.dart +++ b/lib/storage/community_store.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import '../models/community.dart'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; /// Persists communities to local storage using SharedPreferences. @@ -26,7 +27,8 @@ class CommunityStore { } final prefs = PrefsManager.instance; String? jsonString = prefs.getString(keyFor); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(_keyPrefix); prefs.remove(_keyPrefix); diff --git a/lib/storage/contact_group_store.dart b/lib/storage/contact_group_store.dart index ce6a0c6e..fb297005 100644 --- a/lib/storage/contact_group_store.dart +++ b/lib/storage/contact_group_store.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import '../models/contact_group.dart'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ContactGroupStore { @@ -19,7 +20,8 @@ class ContactGroupStore { } final prefs = PrefsManager.instance; String? jsonString = prefs.getString(keyFor); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(_keyPrefix); prefs.remove(_keyPrefix); diff --git a/lib/storage/contact_settings_store.dart b/lib/storage/contact_settings_store.dart index a0760477..10ffaaee 100644 --- a/lib/storage/contact_settings_store.dart +++ b/lib/storage/contact_settings_store.dart @@ -1,4 +1,5 @@ import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ContactSettingsStore { @@ -25,7 +26,7 @@ class ContactSettingsStore { final key = '$keyFor$contactKeyHex'; final oldKey = '$_keyPrefix$contactKeyHex'; bool? enabled = prefs.getBool(key); - if (enabled == null) { + if (enabled == null && canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load enabled = prefs.getBool(oldKey); prefs.remove(oldKey); diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index c23983a8..e80ee952 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -3,6 +3,7 @@ import 'dart:typed_data'; import '../models/contact.dart'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ContactStore { @@ -21,7 +22,8 @@ class ContactStore { } final prefs = PrefsManager.instance; String? jsonString = prefs.getString(keyFor); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(_keyPrefix); prefs.remove(_keyPrefix); diff --git a/lib/storage/legacy_key_migration.dart b/lib/storage/legacy_key_migration.dart new file mode 100644 index 00000000..e66af47f --- /dev/null +++ b/lib/storage/legacy_key_migration.dart @@ -0,0 +1,10 @@ +/// Storage scopes (first 10 hex chars of a radio's public key) that must +/// never adopt data from the legacy unscoped keys. +/// +/// The per-radio stores move a legacy key into the first scope that loads it +/// and then delete the legacy key. A scope listed here, such as the simulated +/// review-mode radio, leaves legacy data for the next real radio. +final Set scopesWithoutLegacyMigration = {}; + +bool canMigrateLegacyKeys(String scopeHex) => + !scopesWithoutLegacyMigration.contains(scopeHex); diff --git a/lib/storage/message_store.dart b/lib/storage/message_store.dart index 46377348..fdd7f5fe 100644 --- a/lib/storage/message_store.dart +++ b/lib/storage/message_store.dart @@ -4,6 +4,7 @@ import '../models/message.dart'; import '../models/translation_support.dart'; import '../helpers/smaz.dart'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class MessageStore { @@ -38,7 +39,8 @@ class MessageStore { final key = '$keyFor$contactKeyHex'; final oldKey = '$_keyPrefix$contactKeyHex'; String? jsonString = prefs.getString(key); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(oldKey); prefs.remove(oldKey); diff --git a/lib/storage/unread_store.dart b/lib/storage/unread_store.dart index 3b615b1d..e191dba9 100644 --- a/lib/storage/unread_store.dart +++ b/lib/storage/unread_store.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; import '../utils/app_logger.dart'; +import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; /// Storage for unread message tracking with debounced writes to reduce I/O. @@ -33,7 +34,8 @@ class UnreadStore { } final prefs = PrefsManager.instance; String? jsonString = prefs.getString(keyFor); - if (jsonString == null || jsonString.isEmpty) { + if ((jsonString == null || jsonString.isEmpty) && + canMigrateLegacyKeys(publicKeyHex)) { // Attempt migration from legacy unscoped key on first load final legacyJsonString = prefs.getString(_keyPrefix); prefs.remove(_keyPrefix); diff --git a/lib/widgets/routing_sheet.dart b/lib/widgets/routing_sheet.dart index 1b8e3e5d..3934a7df 100644 --- a/lib/widgets/routing_sheet.dart +++ b/lib/widgets/routing_sheet.dart @@ -577,8 +577,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { return GestureDetector( behavior: HitTestBehavior.opaque, onSecondaryTapUp: PlatformInfo.isDesktop && hasBytes - ? (_) => - _showPathDetail(context, connector, contact, record) + ? (_) => _showPathDetail(context, connector, contact, record) : null, child: Card( margin: const EdgeInsets.symmetric(vertical: 4), diff --git a/test/review_mode/review_mode_cancel_test.dart b/test/review_mode/review_mode_cancel_test.dart new file mode 100644 index 00000000..cc8cf351 --- /dev/null +++ b/test/review_mode/review_mode_cancel_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({ + 'stale_key_${ReviewRadio.storagePrefix}': 'stale', + 'unrelated_key': 'keep', + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('disconnect during connectReview cancels quietly', () async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + final retryService = MessageRetryService(); + addTearDown(retryService.dispose); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + ReviewRadio? created; + connector.reviewRadioFactoryForTest = () => created = ReviewRadio( + scheduledMessageInterval: const Duration(milliseconds: 50), + ); + + final connecting = connector.connectReview(); + await Future.delayed(Duration.zero); + await connector.disconnect(manual: true); + await connecting; + + expect(connector.isConnected, isFalse); + expect(connector.isReviewMode, isFalse); + expect( + PrefsManager.instance.getKeys().where( + (k) => k.contains(ReviewRadio.storagePrefix), + ), + isEmpty, + ); + // Whether or not the radio was created, nothing keeps it running. + created?.sendTestMessage(); + await Future.delayed(const Duration(milliseconds: 200)); + expect(connector.isConnected, isFalse); + }); +} diff --git a/test/review_mode/review_mode_connector_test.dart b/test/review_mode/review_mode_connector_test.dart new file mode 100644 index 00000000..4f0e8231 --- /dev/null +++ b/test/review_mode/review_mode_connector_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Future _waitFor(bool Function() condition, {int seconds = 8}) async { + final end = DateTime.now().add(Duration(seconds: seconds)); + while (!condition()) { + if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); + await Future.delayed(const Duration(milliseconds: 25)); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({ + 'stale_key_${ReviewRadio.storagePrefix}': 'stale', + 'unrelated_key': 'keep', + // A legacy unscoped key that the contact store migrates into whichever + // radio scope loads first. Review mode must not keep it. + 'contacts': '[]', + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('connectReview syncs, auto-replies, and disconnect cleans up', () async { + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + final retryService = MessageRetryService(); + addTearDown(retryService.dispose); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(milliseconds: 100), + replyDelay: const Duration(milliseconds: 200), + ); + + await connector.connectReview(); + + expect(connector.isConnected, isTrue); + expect(connector.isReviewMode, isTrue); + expect(connector.activeTransport, MeshCoreTransportType.review); + // Stale data from a previous session is wiped on connect. + expect( + PrefsManager.instance.containsKey( + 'stale_key_${ReviewRadio.storagePrefix}', + ), + isFalse, + ); + expect(PrefsManager.instance.getString('unrelated_key'), 'keep'); + + await _waitFor( + () => connector.contacts.length >= 6 && connector.channels.length >= 3, + ); + expect(connector.channels.map((c) => c.name), contains('Hiking Group')); + + final contact = connector.contacts.firstWhere((c) => c.name == 'Maya'); + await _waitFor(() => connector.getMessages(contact).isNotEmpty); + final seeded = connector.getMessages(contact).length; + + await connector.sendMessage(contact, 'hello from test'); + await _waitFor( + () => connector + .getMessages(contact) + .any( + (m) => + m.isOutgoing && + m.text == 'hello from test' && + m.status == MessageStatus.delivered, + ), + ); + await _waitFor(() => connector.getMessages(contact).length >= seeded + 2); + expect(connector.getMessages(contact).last.isOutgoing, isFalse); + + await connector.disconnect(manual: true); + + expect(connector.isReviewMode, isFalse); + expect(connector.isConnected, isFalse); + expect(connector.activeTransport, isNot(MeshCoreTransportType.review)); + final leftover = PrefsManager.instance.getKeys().where( + (k) => k.contains(ReviewRadio.storagePrefix), + ); + expect(leftover, isEmpty); + expect(PrefsManager.instance.getString('unrelated_key'), 'keep'); + expect(PrefsManager.instance.getString('contacts'), '[]'); + + // Frames after teardown must not resurrect anything. + connector.sendReviewTestMessage(); + await Future.delayed(const Duration(milliseconds: 300)); + expect(connector.isReviewMode, isFalse); + }); +} diff --git a/test/review_mode/review_mode_settings_revert_test.dart b/test/review_mode/review_mode_settings_revert_test.dart new file mode 100644 index 00000000..fcd6ce3c --- /dev/null +++ b/test/review_mode/review_mode_settings_revert_test.dart @@ -0,0 +1,107 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/review_mode/review_mode_storage.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/contact_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// Separate file: NotificationService is a singleton whose reply stream can +// only be listened to by one connector per isolate. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({'unrelated_key': 'keep'}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('channel mutes made in review mode are undone on exit', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.muteChannel('Hiking Group'); + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + final retryService = MessageRetryService(); + addTearDown(retryService.dispose); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + appSettingsService: settings, + ); + connector.reviewRadioFactoryForTest = () => + ReviewRadio(scheduledMessageInterval: const Duration(hours: 1)); + + await connector.connectReview(); + // Mutes are keyed by channel name, so these would leak into real radios. + await settings.muteChannel('Public'); + await settings.unmuteChannel('Hiking Group'); + // Other app preferences are the user's to change, even while reviewing. + await PrefsManager.instance.setString('unrelated_key', 'changed'); + + await connector.disconnect(manual: true); + + expect(settings.isChannelMuted('Public'), isFalse); + expect(settings.isChannelMuted('Hiking Group'), isTrue); + expect(PrefsManager.instance.getString('unrelated_key'), 'changed'); + + // A fresh launch has nothing left to undo. + final relaunched = AppSettingsService(); + await relaunched.loadSettings(); + await endReviewModeSession(relaunched); + expect(relaunched.isChannelMuted('Public'), isFalse); + expect(relaunched.isChannelMuted('Hiking Group'), isTrue); + }); + + test( + 'a session interrupted by the app being killed is undone at startup', + () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.muteChannel('Hiking Group'); + + await beginReviewModeSession(settings); + await settings.muteChannel('Public'); + await settings.unmuteChannel('Hiking Group'); + await PrefsManager.instance.setString( + 'contacts${ReviewRadio.storagePrefix}', + '[]', + ); + // The app is killed here: no disconnect, no cleanup. + + final relaunched = AppSettingsService(); + await relaunched.loadSettings(); + expect(relaunched.isChannelMuted('Public'), isTrue); + await endReviewModeSession(relaunched); + + expect(relaunched.isChannelMuted('Public'), isFalse); + expect(relaunched.isChannelMuted('Hiking Group'), isTrue); + expect( + PrefsManager.instance.getKeys().where( + (k) => k.contains(ReviewRadio.storagePrefix), + ), + isEmpty, + ); + }, + ); + + test('the review scope never adopts legacy unscoped data', () async { + await PrefsManager.instance.setString('contacts', '[]'); + await beginReviewModeSession(null); + + final store = ContactStore() + ..setPublicKeyHex = ReviewRadio.selfPublicKeyHex; + await store.loadContacts(); + expect(PrefsManager.instance.getString('contacts'), '[]'); + + final realRadio = ContactStore()..setPublicKeyHex = 'ab' * 32; + await realRadio.loadContacts(); + expect(PrefsManager.instance.containsKey('contacts'), isFalse); + expect(PrefsManager.instance.getString(realRadio.keyFor), '[]'); + }); +} diff --git a/test/review_mode/review_radio_test.dart b/test/review_mode/review_radio_test.dart new file mode 100644 index 00000000..f7281ee4 --- /dev/null +++ b/test/review_mode/review_radio_test.dart @@ -0,0 +1,425 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/review_mode/review_script.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; + +const _tick = Duration(milliseconds: 60); + +class _Harness { + final ReviewRadio radio; + final List frames = []; + late final StreamSubscription _sub; + + _Harness(this.radio) { + _sub = radio.frames.listen(frames.add); + } + + Future settle([Duration d = _tick]) => Future.delayed(d); + + Future> request(Uint8List frame) async { + frames.clear(); + radio.handle(frame); + await settle(); + return List.of(frames); + } + + Future close() async { + await _sub.cancel(); + radio.dispose(); + } +} + +ReviewRadio _fastRadio() => ReviewRadio( + scheduledMessageInterval: const Duration(milliseconds: 40), + ackDelay: const Duration(milliseconds: 100), + replyDelay: const Duration(milliseconds: 200), +); + +void main() { + test('public key constants are consistent', () { + expect(ReviewRadio.selfPublicKeyHex.length, 64); + expect(ReviewRadio.selfPublicKeyHex.startsWith('ee5e'), isTrue); + expect( + ReviewRadio.selfPublicKeyHex, + ReviewRadio.selfPublicKeyHex.toLowerCase(), + ); + expect( + ReviewRadio.storagePrefix, + ReviewRadio.selfPublicKeyHex.substring(0, 10), + ); + }); + + test('responses are never synchronous', () async { + final h = _Harness(ReviewRadio()); + h.radio.handle(buildAppStartFrame()); + expect(h.frames, isEmpty); + await h.settle(); + expect(h.frames, hasLength(1)); + await h.close(); + }); + + test('handshake replies with SELF_INFO and DEVICE_INFO', () async { + final h = _Harness(ReviewRadio()); + + final self = (await h.request(buildAppStartFrame())).single; + expect(self[0], respCodeSelfInfo); + final reader = BufferReader(self)..skipBytes(4); + expect( + pubKeyToHex(reader.readBytes(pubKeySize)), + ReviewRadio.selfPublicKeyHex, + ); + expect(reader.readInt32LE(), ReviewScript.selfLatitudeE6); + expect(reader.readInt32LE(), ReviewScript.selfLongitudeE6); + reader.skipBytes(4); + expect(reader.readUInt32LE(), 910525000); + expect(reader.readUInt32LE(), 62500); + expect(reader.readByte(), 7); + expect(reader.readByte(), 5); + expect(reader.readCString(), 'Review Radio'); + + final info = (await h.request(buildDeviceQueryFrame())).single; + expect(info[0], respCodeDeviceInfo); + expect(info.length, 82); + expect(info[1], ReviewScript.firmwareVerCode); + expect(info[2] * 2, ReviewScript.maxContacts); + expect(info[3], ReviewScript.maxChannels); + expect( + String.fromCharCodes(info.sublist(20, 40)), + startsWith('MeshCore Open Review'), + ); + expect(String.fromCharCodes(info.sublist(60, 66)), 'review'); + expect(info[81], 0); + await h.close(); + }); + + test('contact list parses with the app Contact parser', () async { + final h = _Harness(ReviewRadio()); + final out = await h.request(buildGetContactsFrame()); + + expect(out.first[0], respCodeContactsStart); + expect(readUint32LE(out.first, 1), ReviewScript.contacts.length); + expect(out.last[0], respCodeEndOfContacts); + final contacts = out.sublist(1, out.length - 1); + expect(contacts, hasLength(6)); + for (final f in contacts) { + expect(f.length, contactFrameSize); + } + final parsed = contacts.map((f) => Contact.fromFrame(f)!).toList(); + expect(parsed.map((c) => c.name), ReviewScript.contacts.map((c) => c.name)); + expect(parsed.where((c) => c.type == advTypeChat), hasLength(4)); + expect(parsed.where((c) => c.type == advTypeRepeater), hasLength(1)); + expect(parsed.where((c) => c.type == advTypeRoom), hasLength(1)); + expect(parsed[1].pathLength, 2); + expect(parsed[0].latitude, closeTo(45.5231, 1e-6)); + expect(parsed.map((c) => c.publicKeyHex).toSet(), hasLength(6)); + + // Incremental sync with a current 'since' returns nothing new. + final since = readUint32LE(out.last, 1); + final incremental = await h.request(buildGetContactsFrame(since: since)); + expect(incremental, hasLength(2)); + await h.close(); + }); + + test('get contact by key returns the contact or ERR', () async { + final h = _Harness(ReviewRadio()); + final key = hexToPubKey(ReviewScript.contacts[2].publicKeyHex); + final found = (await h.request(buildGetContactByKeyFrame(key))).single; + expect(Contact.fromFrame(found)!.name, 'Sam'); + + final missing = (await h.request( + buildGetContactByKeyFrame(Uint8List(pubKeySize)..fillRange(0, 32, 9)), + )).single; + expect(missing[0], respCodeErr); + await h.close(); + }); + + test('channel info for configured and empty slots', () async { + final h = _Harness(ReviewRadio()); + final pub = Channel.fromFrame( + (await h.request(buildGetChannelFrame(0))).single, + )!; + expect(pub.name, 'Public'); + expect(pub.isPublicChannel, isTrue); + final hiking = Channel.fromFrame( + (await h.request(buildGetChannelFrame(1))).single, + )!; + expect(hiking.name, 'Hiking Group'); + expect(hiking.isPublicChannel, isFalse); + final local = Channel.fromFrame( + (await h.request(buildGetChannelFrame(2))).single, + )!; + expect(local.name, 'Local Net'); + final empty = Channel.fromFrame( + (await h.request(buildGetChannelFrame(5))).single, + )!; + expect(empty.isEmpty, isTrue); + + await h.request( + buildSetChannelFrame( + 4, + 'New One', + Uint8List.fromList(List.filled(16, 7)), + ), + ); + final added = Channel.fromFrame( + (await h.request(buildGetChannelFrame(4))).single, + )!; + expect(added.name, 'New One'); + await h.close(); + }); + + test('seed history drains through SYNC_NEXT_MESSAGE', () async { + final h = _Harness(ReviewRadio()); + final direct = []; + final channel = []; + for (var i = 0; i < 20; i++) { + final f = (await h.request(buildSyncNextMessageFrame())).single; + if (f[0] == respCodeNoMoreMessages) break; + if (f[0] == respCodeContactMsgRecvV3) { + direct.add(parseContactMessageText(f)!); + } else { + expect(f[0], respCodeChannelMsgRecvV3); + channel.add(ChannelMessage.fromFrame(f)!); + } + } + expect(direct, hasLength(3)); + expect(channel, hasLength(4)); + expect(direct.first.text, contains('ridge')); + expect( + direct.first.senderPrefix, + hexToPubKey(ReviewScript.contacts[0].publicKeyHex).sublist(0, 6), + ); + expect(channel.map((m) => m.channelIndex).toSet(), {0, 1, 2}); + expect( + channel.any( + (m) => m.senderName == 'Jordan' && m.text.contains('trailhead'), + ), + isTrue, + ); + + final again = (await h.request(buildSyncNextMessageFrame())).single; + expect(again[0], respCodeNoMoreMessages); + await h.close(); + }); + + test('direct send yields SENT, SEND_CONFIRMED and a queued reply', () async { + final h = _Harness(_fastRadio()); + final contact = ReviewScript.contacts[0]; + final key = hexToPubKey(contact.publicKeyHex); + final ts = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + final sent = await h.request( + buildSendTextMsgFrame(key, 'Hello Maya', timestampSeconds: ts), + ); + expect(sent.single[0], respCodeSent); + final reader = BufferReader(sent.single)..skipBytes(2); + final ackHash = reader.readUInt32LE(); + expect(reader.readUInt32LE(), greaterThan(0)); + expect( + ackHash, + MessageRetryService.computeExpectedAckHash( + ts, + 0, + 'Hello Maya', + hexToPubKey(ReviewRadio.selfPublicKeyHex), + ), + ); + + h.frames.clear(); + await h.settle(const Duration(milliseconds: 150)); + expect(h.frames.first[0], pushCodeSendConfirmed); + final confirmed = BufferReader(h.frames.first)..skipBytes(1); + expect(confirmed.readUInt32LE(), ackHash); + + await h.settle(const Duration(milliseconds: 300)); + expect(h.frames.last[0], pushCodeMsgWaiting); + + // Drain the seed history; the reply is the last queued message. + Uint8List? last; + for (var i = 0; i < 20; i++) { + final f = (await h.request(buildSyncNextMessageFrame())).single; + if (f[0] == respCodeNoMoreMessages) break; + last = f; + } + final reply = parseContactMessageText(last!)!; + expect(reply.senderPrefix, key.sublist(0, 6)); + expect(ReviewScript.directReplies, contains(reply.text)); + await h.close(); + }); + + test('room login succeeds and repeater login fails promptly', () async { + final h = _Harness(_fastRadio()); + final room = ReviewScript.contacts.firstWhere((c) => c.type == advTypeRoom); + final roomKey = hexToPubKey(room.publicKeyHex); + final sent = await h.request(buildSendLoginFrame(roomKey, 'any')); + expect(sent.single[0], respCodeSent); + h.frames.clear(); + await h.settle(const Duration(milliseconds: 150)); + final success = h.frames.single; + expect(success[0], pushCodeLoginSuccess); + expect(success.length, greaterThanOrEqualTo(12)); + expect(success.sublist(2, 8), roomKey.sublist(0, 6)); + expect(readUint32LE(success, 8), greaterThan(0)); + + final repeater = ReviewScript.contacts.firstWhere( + (c) => c.type == advTypeRepeater, + ); + final repeaterKey = hexToPubKey(repeater.publicKeyHex); + expect( + (await h.request(buildSendLoginFrame(repeaterKey, 'any'))).single[0], + respCodeSent, + ); + h.frames.clear(); + await h.settle(const Duration(milliseconds: 150)); + expect(h.frames.single[0], pushCodeLoginFail); + expect(h.frames.single.sublist(2, 8), repeaterKey.sublist(0, 6)); + await h.close(); + }); + + test('unknown recipient prefix is answered with ERR', () async { + final h = _Harness(ReviewRadio()); + final out = await h.request( + buildSendTextMsgFrame(Uint8List(pubKeySize)..fillRange(0, 32, 3), 'hi'), + ); + expect(out.single[0], respCodeErr); + await h.close(); + }); + + test('channel send yields OK then a channel reply', () async { + final h = _Harness(_fastRadio()); + final ok = await h.request( + buildSendChannelTextMsgFrame(1, 'Review Radio: hi all'), + ); + expect(ok.single[0], respCodeOk); + + h.frames.clear(); + await h.settle(const Duration(milliseconds: 300)); + expect(h.frames.single[0], pushCodeMsgWaiting); + + ChannelMessage? reply; + for (var i = 0; i < 20; i++) { + final f = (await h.request(buildSyncNextMessageFrame())).single; + if (f[0] == respCodeNoMoreMessages) break; + if (f[0] == respCodeChannelMsgRecvV3) reply = ChannelMessage.fromFrame(f); + } + expect(reply, isNotNull); + expect(reply!.channelIndex, 1); + expect(ReviewScript.channelMembers[1], contains(reply.senderName)); + expect(ReviewScript.channelReplies, contains(reply.text)); + await h.close(); + }); + + test('status commands get plausible replies', () async { + final h = _Harness(ReviewRadio()); + expect( + (await h.request(buildGetBattAndStorageFrame())).single[0], + respCodeBattAndStorage, + ); + final time = (await h.request(buildGetDeviceTimeFrame())).single; + expect(time[0], respCodeCurrTime); + expect( + readUint32LE(time, 1), + closeTo(DateTime.now().millisecondsSinceEpoch ~/ 1000, 5), + ); + expect( + (await h.request(buildGetCustomVarsFrame())).single[0], + respCodeCustomVars, + ); + expect( + (await h.request(buildGetAutoAddFlagsFrame())).single[0], + respCodeAutoAddConfig, + ); + final freq = (await h.request(buildGetAllowedRepeatFreqFrame())).single; + expect(parseAllowedRepeatFreqFrame(freq), isNotEmpty); + expect( + (await h.request(buildGetStatsFrame(statsTypeRadio))).single.length, + 14, + ); + expect( + (await h.request(buildSetFloodScopeFrame('#west'))).single[0], + respCodeOk, + ); + expect((await h.request(buildSendSelfAdvertFrame())).single[0], respCodeOk); + expect( + (await h.request( + buildSendLoginFrame(Uint8List(pubKeySize), 'pw'), + )).single[0], + respCodeErr, + ); + await h.close(); + }); + + test( + 'sendTestMessage queues alternating direct and channel messages', + () async { + final h = _Harness(ReviewRadio()); + // Drain seed history first. + for (var i = 0; i < 20; i++) { + final f = (await h.request(buildSyncNextMessageFrame())).single; + if (f[0] == respCodeNoMoreMessages) break; + } + + h.frames.clear(); + h.radio.sendTestMessage(); + h.radio.sendTestMessage(); + await h.settle(); + expect(h.frames.map((f) => f[0]), [ + pushCodeMsgWaiting, + pushCodeMsgWaiting, + ]); + + final first = (await h.request(buildSyncNextMessageFrame())).single; + final second = (await h.request(buildSyncNextMessageFrame())).single; + expect(first[0], respCodeContactMsgRecvV3); + expect(second[0], respCodeChannelMsgRecvV3); + expect(parseContactMessageText(first), isNotNull); + expect(ChannelMessage.fromFrame(second), isNotNull); + expect( + (await h.request(buildSyncNextMessageFrame())).single[0], + respCodeNoMoreMessages, + ); + await h.close(); + }, + ); + + test('scheduled timer emits MSG_WAITING after start', () async { + final h = _Harness(_fastRadio()); + await h.settle(const Duration(milliseconds: 150)); + expect(h.frames, isEmpty); + h.radio.start(); + await h.settle(const Duration(milliseconds: 150)); + expect(h.frames.where((f) => f[0] == pushCodeMsgWaiting), isNotEmpty); + await h.close(); + }); + + test('dispose cancels timers, closes the stream and is idempotent', () async { + final radio = _fastRadio(); + final frames = []; + var done = false; + radio.frames.listen(frames.add, onDone: () => done = true); + radio.start(); + radio.handle(buildSendChannelTextMsgFrame(0, 'x: y')); + radio.handle( + buildSendTextMsgFrame( + hexToPubKey(ReviewScript.contacts[0].publicKeyHex), + 'bye', + ), + ); + radio.dispose(); + radio.dispose(); + await Future.delayed(const Duration(milliseconds: 400)); + expect(frames, isEmpty); + expect(done, isTrue); + radio.handle(buildAppStartFrame()); + radio.sendTestMessage(); + await Future.delayed(_tick); + expect(frames, isEmpty); + }); +} From 78cb07cab4853ce28c665d8bad86ac7fbd5fdf18 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 20:40:59 -0700 Subject: [PATCH 10/28] Translate review mode strings for all locales --- lib/l10n/app_bg.arb | 18 +++++++++--------- lib/l10n/app_de.arb | 18 +++++++++--------- lib/l10n/app_es.arb | 18 +++++++++--------- lib/l10n/app_fr.arb | 18 +++++++++--------- lib/l10n/app_hu.arb | 18 +++++++++--------- lib/l10n/app_it.arb | 18 +++++++++--------- lib/l10n/app_ja.arb | 18 +++++++++--------- lib/l10n/app_ko.arb | 18 +++++++++--------- lib/l10n/app_localizations_bg.dart | 18 +++++++++--------- lib/l10n/app_localizations_de.dart | 18 +++++++++--------- lib/l10n/app_localizations_es.dart | 18 +++++++++--------- lib/l10n/app_localizations_fr.dart | 18 +++++++++--------- lib/l10n/app_localizations_hu.dart | 18 +++++++++--------- lib/l10n/app_localizations_it.dart | 18 +++++++++--------- lib/l10n/app_localizations_ja.dart | 18 +++++++++--------- lib/l10n/app_localizations_ko.dart | 18 +++++++++--------- lib/l10n/app_localizations_nl.dart | 18 +++++++++--------- lib/l10n/app_localizations_pl.dart | 18 +++++++++--------- lib/l10n/app_localizations_pt.dart | 18 +++++++++--------- lib/l10n/app_localizations_ru.dart | 18 +++++++++--------- lib/l10n/app_localizations_sk.dart | 18 +++++++++--------- lib/l10n/app_localizations_sl.dart | 18 +++++++++--------- lib/l10n/app_localizations_sv.dart | 18 +++++++++--------- lib/l10n/app_localizations_uk.dart | 18 +++++++++--------- lib/l10n/app_localizations_zh.dart | 19 +++++++++---------- lib/l10n/app_nl.arb | 18 +++++++++--------- lib/l10n/app_pl.arb | 18 +++++++++--------- lib/l10n/app_pt.arb | 18 +++++++++--------- lib/l10n/app_ru.arb | 18 +++++++++--------- lib/l10n/app_sk.arb | 18 +++++++++--------- lib/l10n/app_sl.arb | 18 +++++++++--------- lib/l10n/app_sv.arb | 18 +++++++++--------- lib/l10n/app_uk.arb | 18 +++++++++--------- lib/l10n/app_zh.arb | 18 +++++++++--------- 34 files changed, 306 insertions(+), 307 deletions(-) diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 8039dfbe..c93f6803 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3052,13 +3052,13 @@ } }, "receivedImage_saveFailed": "Изображението не можа да бъде запазено", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Вход в режим за преглед?", + "reviewMode_dialogBody": "Режимът за преглед се свързва със симулирано радио с примерни контакти, канали и съобщения. Не е нужно реално радио.", + "reviewMode_confirm": "Вход", + "reviewMode_cancel": "Отказ", + "reviewMode_banner": "Режим за преглед — симулирани данни", + "reviewMode_sendTest": "Тестово съобщение", + "reviewMode_testSent": "Скоро ще пристигне тестово съобщение.", + "reviewMode_exit": "Изход", + "reviewMode_connectFailed": "Режимът за преглед не можа да се стартира: {error}" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index c1d59623..496d44fd 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3187,13 +3187,13 @@ } }, "receivedImage_saveFailed": "Das Bild konnte nicht gespeichert werden", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Prüfmodus aktivieren?", + "reviewMode_dialogBody": "Der Prüfmodus verbindet sich mit einem simulierten Radio mit Beispielkontakten, Kanälen und Nachrichten. Es wird kein echtes Radio benötigt.", + "reviewMode_confirm": "Aktivieren", + "reviewMode_cancel": "Abbrechen", + "reviewMode_banner": "Prüfmodus — simulierte Daten", + "reviewMode_sendTest": "Testnachricht senden", + "reviewMode_testSent": "Eine Testnachricht trifft in Kürze ein.", + "reviewMode_exit": "Beenden", + "reviewMode_connectFailed": "Prüfmodus konnte nicht gestartet werden: {error}" } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index f75b3070..91fbf2bc 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3186,13 +3186,13 @@ } }, "receivedImage_saveFailed": "No se pudo guardar la imagen", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "¿Entrar en el modo de revisión?", + "reviewMode_dialogBody": "El modo de revisión se conecta a una radio simulada con contactos, canales y mensajes de ejemplo. No se necesita una radio real.", + "reviewMode_confirm": "Entrar", + "reviewMode_cancel": "Cancelar", + "reviewMode_banner": "Modo de revisión — datos simulados", + "reviewMode_sendTest": "Enviar mensaje de prueba", + "reviewMode_testSent": "En breve llegará un mensaje de prueba.", + "reviewMode_exit": "Salir", + "reviewMode_connectFailed": "No se pudo iniciar el modo de revisión: {error}" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index dea0a2f3..ac27208e 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3186,13 +3186,13 @@ } }, "receivedImage_saveFailed": "Impossible d'enregistrer l'image", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Activer le mode revue ?", + "reviewMode_dialogBody": "Le mode revue se connecte à une radio simulée avec des contacts, canaux et messages d'exemple. Aucune radio réelle n'est nécessaire.", + "reviewMode_confirm": "Activer", + "reviewMode_cancel": "Annuler", + "reviewMode_banner": "Mode revue — données simulées", + "reviewMode_sendTest": "Envoyer un message test", + "reviewMode_testSent": "Un message test arrivera sous peu.", + "reviewMode_exit": "Quitter", + "reviewMode_connectFailed": "Impossible de démarrer le mode revue : {error}" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index fc56866d..cb7a649b 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3091,13 +3091,13 @@ } }, "receivedImage_saveFailed": "A képet nem sikerült elmenteni", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Belép az áttekintő módba?", + "reviewMode_dialogBody": "Az áttekintő mód egy szimulált rádióhoz csatlakozik, mintakapcsolatokkal, csatornákkal és üzenetekkel. Nincs szükség valódi rádióra.", + "reviewMode_confirm": "Belépés", + "reviewMode_cancel": "Mégsem", + "reviewMode_banner": "Áttekintő mód — szimulált adatok", + "reviewMode_sendTest": "Tesztüzenet küldése", + "reviewMode_testSent": "Hamarosan megérkezik egy tesztüzenet.", + "reviewMode_exit": "Kilépés", + "reviewMode_connectFailed": "Az áttekintő mód nem indítható el: {error}" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 577aa703..820d3c7d 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3186,13 +3186,13 @@ } }, "receivedImage_saveFailed": "Impossibile salvare l'immagine", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Entrare nella modalità revisione?", + "reviewMode_dialogBody": "La modalità revisione si connette a una radio simulata con contatti, canali e messaggi di esempio. Non serve una radio reale.", + "reviewMode_confirm": "Entra", + "reviewMode_cancel": "Annulla", + "reviewMode_banner": "Modalità revisione — dati simulati", + "reviewMode_sendTest": "Invia messaggio di prova", + "reviewMode_testSent": "A breve arriverà un messaggio di prova.", + "reviewMode_exit": "Esci", + "reviewMode_connectFailed": "Impossibile avviare la modalità revisione: {error}" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 997aacd1..91c39b9c 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -3186,13 +3186,13 @@ } }, "receivedImage_saveFailed": "画像を保存できませんでした", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "レビューモードに入りますか?", + "reviewMode_dialogBody": "レビューモードでは、サンプルの連絡先、チャンネル、メッセージを備えたシミュレートされたデバイスに接続します。実際のデバイスは不要です。", + "reviewMode_confirm": "開始", + "reviewMode_cancel": "キャンセル", + "reviewMode_banner": "レビューモード — シミュレーションデータ", + "reviewMode_sendTest": "テストメッセージを送信", + "reviewMode_testSent": "まもなくテストメッセージが届きます。", + "reviewMode_exit": "終了", + "reviewMode_connectFailed": "レビューモードを開始できませんでした: {error}" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index fcb0e819..65bacbae 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3186,13 +3186,13 @@ } }, "receivedImage_saveFailed": "이미지를 저장할 수 없습니다", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "검토 모드로 들어갈까요?", + "reviewMode_dialogBody": "검토 모드는 샘플 연락처, 채널, 메시지가 있는 시뮬레이션 기기에 연결합니다. 실제 기기는 필요하지 않습니다.", + "reviewMode_confirm": "들어가기", + "reviewMode_cancel": "취소", + "reviewMode_banner": "검토 모드 — 시뮬레이션 데이터", + "reviewMode_sendTest": "테스트 메시지 보내기", + "reviewMode_testSent": "잠시 후 테스트 메시지가 도착합니다.", + "reviewMode_exit": "나가기", + "reviewMode_connectFailed": "검토 모드를 시작할 수 없습니다: {error}" } diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 9ca96e85..405d01d7 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -5479,32 +5479,32 @@ class AppLocalizationsBg extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Вход в режим за преглед?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Режимът за преглед се свързва със симулирано радио с примерни контакти, канали и съобщения. Не е нужно реално радио.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Вход'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Отказ'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Режим за преглед — симулирани данни'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Тестово съобщение'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Скоро ще пристигне тестово съобщение.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Изход'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Режимът за преглед не можа да се стартира: $error'; } } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index b1893db3..b2e5227f 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -5496,32 +5496,32 @@ class AppLocalizationsDe extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Prüfmodus aktivieren?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Der Prüfmodus verbindet sich mit einem simulierten Radio mit Beispielkontakten, Kanälen und Nachrichten. Es wird kein echtes Radio benötigt.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Aktivieren'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Abbrechen'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Prüfmodus — simulierte Daten'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Testnachricht senden'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Eine Testnachricht trifft in Kürze ein.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Beenden'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Prüfmodus konnte nicht gestartet werden: $error'; } } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 6bd776f7..afe87f8f 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -5485,32 +5485,32 @@ class AppLocalizationsEs extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => '¿Entrar en el modo de revisión?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'El modo de revisión se conecta a una radio simulada con contactos, canales y mensajes de ejemplo. No se necesita una radio real.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Entrar'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Cancelar'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Modo de revisión — datos simulados'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Enviar mensaje de prueba'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'En breve llegará un mensaje de prueba.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Salir'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'No se pudo iniciar el modo de revisión: $error'; } } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 627c6869..013151cf 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -5509,32 +5509,32 @@ class AppLocalizationsFr extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Activer le mode revue ?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Le mode revue se connecte à une radio simulée avec des contacts, canaux et messages d\'exemple. Aucune radio réelle n\'est nécessaire.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Activer'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Annuler'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Mode revue — données simulées'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Envoyer un message test'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Un message test arrivera sous peu.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Quitter'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Impossible de démarrer le mode revue : $error'; } } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index c3f642e0..acb4d8b1 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -5475,32 +5475,32 @@ class AppLocalizationsHu extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Belép az áttekintő módba?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Az áttekintő mód egy szimulált rádióhoz csatlakozik, mintakapcsolatokkal, csatornákkal és üzenetekkel. Nincs szükség valódi rádióra.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Belépés'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Mégsem'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Áttekintő mód — szimulált adatok'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Tesztüzenet küldése'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Hamarosan megérkezik egy tesztüzenet.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Kilépés'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Az áttekintő mód nem indítható el: $error'; } } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index b8d48bdf..0edfc067 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -5491,32 +5491,32 @@ class AppLocalizationsIt extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Entrare nella modalità revisione?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'La modalità revisione si connette a una radio simulata con contatti, canali e messaggi di esempio. Non serve una radio reale.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Entra'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Annulla'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Modalità revisione — dati simulati'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Invia messaggio di prova'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'A breve arriverà un messaggio di prova.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Esci'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Impossibile avviare la modalità revisione: $error'; } } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 19d92ae1..51d88f73 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5217,32 +5217,32 @@ class AppLocalizationsJa extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'レビューモードに入りますか?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'レビューモードでは、サンプルの連絡先、チャンネル、メッセージを備えたシミュレートされたデバイスに接続します。実際のデバイスは不要です。'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => '開始'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'キャンセル'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'レビューモード — シミュレーションデータ'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'テストメッセージを送信'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'まもなくテストメッセージが届きます。'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => '終了'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'レビューモードを開始できませんでした: $error'; } } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index e41d53e1..7227aea8 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5227,32 +5227,32 @@ class AppLocalizationsKo extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => '검토 모드로 들어갈까요?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + '검토 모드는 샘플 연락처, 채널, 메시지가 있는 시뮬레이션 기기에 연결합니다. 실제 기기는 필요하지 않습니다.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => '들어가기'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => '취소'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => '검토 모드 — 시뮬레이션 데이터'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => '테스트 메시지 보내기'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => '잠시 후 테스트 메시지가 도착합니다.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => '나가기'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return '검토 모드를 시작할 수 없습니다: $error'; } } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index aab486a8..a443de0f 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -5453,32 +5453,32 @@ class AppLocalizationsNl extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Beoordelingsmodus starten?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'De beoordelingsmodus maakt verbinding met een gesimuleerde radio met voorbeeldcontacten, kanalen en berichten. Een echte radio is niet nodig.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Starten'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Annuleren'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Beoordelingsmodus — gesimuleerde gegevens'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Testbericht sturen'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Er komt zo een testbericht binnen.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Afsluiten'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Beoordelingsmodus kon niet worden gestart: $error'; } } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index a88d7afd..44c23fc1 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -5513,32 +5513,32 @@ class AppLocalizationsPl extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Włączyć tryb recenzji?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Tryb recenzji łączy się z symulowanym radiem z przykładowymi kontaktami, kanałami i wiadomościami. Prawdziwe radio nie jest potrzebne.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Włącz'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Anuluj'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Tryb recenzji — dane symulowane'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Wyślij wiadomość testową'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Wiadomość testowa wkrótce nadejdzie.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Wyjdź'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Nie udało się uruchomić trybu recenzji: $error'; } } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 1d05d25d..5626cfef 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -5481,32 +5481,32 @@ class AppLocalizationsPt extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Entrar no modo de revisão?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'O modo de revisão conecta-se a um rádio simulado com contatos, canais e mensagens de exemplo. Não é necessário um rádio real.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Entrar'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Cancelar'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Modo de revisão — dados simulados'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Enviar mensagem de teste'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Uma mensagem de teste chegará em breve.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Sair'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Não foi possível iniciar o modo de revisão: $error'; } } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index e4fe8631..77356609 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -5499,32 +5499,32 @@ class AppLocalizationsRu extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Войти в режим проверки?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Режим проверки подключается к имитируемому радио с примерами контактов, каналов и сообщений. Реальное радио не требуется.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Войти'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Отмена'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Режим проверки — имитация данных'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Тестовое сообщение'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Скоро придёт тестовое сообщение.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Выйти'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Не удалось запустить режим проверки: $error'; } } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 120db392..b181c59e 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -5462,32 +5462,32 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Vstúpiť do režimu kontroly?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Režim kontroly sa pripojí k simulovanému rádiu s ukážkovými kontaktmi, kanálmi a správami. Skutočné rádio nie je potrebné.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Vstúpiť'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Zrušiť'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Režim kontroly — simulované údaje'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Poslať testovaciu správu'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Čoskoro príde testovacia správa.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Ukončiť'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Režim kontroly sa nepodarilo spustiť: $error'; } } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 218c8e86..6c51881d 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -5466,32 +5466,32 @@ class AppLocalizationsSl extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Vstop v način pregleda?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Način pregleda se poveže s simuliranim radiem z vzorčnimi stiki, kanali in sporočili. Pravi radio ni potreben.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Vstopi'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Prekliči'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Način pregleda — simulirani podatki'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Pošlji testno sporočilo'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Kmalu bo prispelo testno sporočilo.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Izhod'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Načina pregleda ni bilo mogoče zagnati: $error'; } } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index c73afad3..d6ef82e8 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -5436,32 +5436,32 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Aktivera granskningsläge?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Granskningsläget ansluter till en simulerad radio med exempelkontakter, kanaler och meddelanden. Ingen riktig radio behövs.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Aktivera'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Avbryt'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Granskningsläge — simulerad data'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Skicka testmeddelande'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Ett testmeddelande kommer snart.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Avsluta'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Det gick inte att starta granskningsläget: $error'; } } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index f90fd994..924b24af 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -5502,32 +5502,32 @@ class AppLocalizationsUk extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => 'Увійти в режим перевірки?'; @override String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + 'Режим перевірки підключається до імітованого радіо із прикладами контактів, каналів і повідомлень. Справжнє радіо не потрібне.'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => 'Увійти'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => 'Скасувати'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => 'Режим перевірки — імітовані дані'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => 'Тестове повідомлення'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => 'Незабаром надійде тестове повідомлення.'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => 'Вийти'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return 'Не вдалося запустити режим перевірки: $error'; } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index c246fafa..515370ae 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5094,32 +5094,31 @@ class AppLocalizationsZh extends AppLocalizations { } @override - String get reviewMode_dialogTitle => 'Enter review mode?'; + String get reviewMode_dialogTitle => '进入审核模式?'; @override - String get reviewMode_dialogBody => - 'Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.'; + String get reviewMode_dialogBody => '审核模式会连接到模拟设备,其中包含示例联系人、频道和消息。无需真实设备。'; @override - String get reviewMode_confirm => 'Enter'; + String get reviewMode_confirm => '进入'; @override - String get reviewMode_cancel => 'Cancel'; + String get reviewMode_cancel => '取消'; @override - String get reviewMode_banner => 'Review mode — simulated data'; + String get reviewMode_banner => '审核模式 — 模拟数据'; @override - String get reviewMode_sendTest => 'Send test message'; + String get reviewMode_sendTest => '发送测试消息'; @override - String get reviewMode_testSent => 'A test message will arrive shortly.'; + String get reviewMode_testSent => '测试消息即将送达。'; @override - String get reviewMode_exit => 'Exit'; + String get reviewMode_exit => '退出'; @override String reviewMode_connectFailed(String error) { - return 'Could not start review mode: $error'; + return '无法启动审核模式:$error'; } } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 87d409f2..bb43678c 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -2953,13 +2953,13 @@ "notification_replyUnavailable": "Dit gesprek staat niet meer op de verbonden radio.", "notification_replySendFailed": "Je antwoord is mogelijk niet verzonden. Controleer dit in MeshCore Open en probeer het opnieuw.", "notification_replyAppNotRunning": "MeshCore Open is niet actief. Open de app en verzend je antwoord opnieuw.", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Beoordelingsmodus starten?", + "reviewMode_dialogBody": "De beoordelingsmodus maakt verbinding met een gesimuleerde radio met voorbeeldcontacten, kanalen en berichten. Een echte radio is niet nodig.", + "reviewMode_confirm": "Starten", + "reviewMode_cancel": "Annuleren", + "reviewMode_banner": "Beoordelingsmodus — gesimuleerde gegevens", + "reviewMode_sendTest": "Testbericht sturen", + "reviewMode_testSent": "Er komt zo een testbericht binnen.", + "reviewMode_exit": "Afsluiten", + "reviewMode_connectFailed": "Beoordelingsmodus kon niet worden gestart: {error}" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index 2888a491..56e1dd7f 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3091,13 +3091,13 @@ } }, "receivedImage_saveFailed": "Nie udało się zapisać obrazu", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Włączyć tryb recenzji?", + "reviewMode_dialogBody": "Tryb recenzji łączy się z symulowanym radiem z przykładowymi kontaktami, kanałami i wiadomościami. Prawdziwe radio nie jest potrzebne.", + "reviewMode_confirm": "Włącz", + "reviewMode_cancel": "Anuluj", + "reviewMode_banner": "Tryb recenzji — dane symulowane", + "reviewMode_sendTest": "Wyślij wiadomość testową", + "reviewMode_testSent": "Wiadomość testowa wkrótce nadejdzie.", + "reviewMode_exit": "Wyjdź", + "reviewMode_connectFailed": "Nie udało się uruchomić trybu recenzji: {error}" } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 1f3adc13..8e3b445c 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3052,13 +3052,13 @@ } }, "receivedImage_saveFailed": "Não foi possível guardar a imagem", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Entrar no modo de revisão?", + "reviewMode_dialogBody": "O modo de revisão conecta-se a um rádio simulado com contatos, canais e mensagens de exemplo. Não é necessário um rádio real.", + "reviewMode_confirm": "Entrar", + "reviewMode_cancel": "Cancelar", + "reviewMode_banner": "Modo de revisão — dados simulados", + "reviewMode_sendTest": "Enviar mensagem de teste", + "reviewMode_testSent": "Uma mensagem de teste chegará em breve.", + "reviewMode_exit": "Sair", + "reviewMode_connectFailed": "Não foi possível iniciar o modo de revisão: {error}" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 1a42ab58..42e7c7b7 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -2355,13 +2355,13 @@ } }, "receivedImage_saveFailed": "Не удалось сохранить изображение", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Войти в режим проверки?", + "reviewMode_dialogBody": "Режим проверки подключается к имитируемому радио с примерами контактов, каналов и сообщений. Реальное радио не требуется.", + "reviewMode_confirm": "Войти", + "reviewMode_cancel": "Отмена", + "reviewMode_banner": "Режим проверки — имитация данных", + "reviewMode_sendTest": "Тестовое сообщение", + "reviewMode_testSent": "Скоро придёт тестовое сообщение.", + "reviewMode_exit": "Выйти", + "reviewMode_connectFailed": "Не удалось запустить режим проверки: {error}" } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index eb0c225d..5fa836f4 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3053,13 +3053,13 @@ } }, "receivedImage_saveFailed": "Nepodarilo sa uložiť obrázok", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Vstúpiť do režimu kontroly?", + "reviewMode_dialogBody": "Režim kontroly sa pripojí k simulovanému rádiu s ukážkovými kontaktmi, kanálmi a správami. Skutočné rádio nie je potrebné.", + "reviewMode_confirm": "Vstúpiť", + "reviewMode_cancel": "Zrušiť", + "reviewMode_banner": "Režim kontroly — simulované údaje", + "reviewMode_sendTest": "Poslať testovaciu správu", + "reviewMode_testSent": "Čoskoro príde testovacia správa.", + "reviewMode_exit": "Ukončiť", + "reviewMode_connectFailed": "Režim kontroly sa nepodarilo spustiť: {error}" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index e0b9507e..6a00cb3a 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3053,13 +3053,13 @@ } }, "receivedImage_saveFailed": "Slike ni bilo mogoče shraniti", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Vstop v način pregleda?", + "reviewMode_dialogBody": "Način pregleda se poveže s simuliranim radiem z vzorčnimi stiki, kanali in sporočili. Pravi radio ni potreben.", + "reviewMode_confirm": "Vstopi", + "reviewMode_cancel": "Prekliči", + "reviewMode_banner": "Način pregleda — simulirani podatki", + "reviewMode_sendTest": "Pošlji testno sporočilo", + "reviewMode_testSent": "Kmalu bo prispelo testno sporočilo.", + "reviewMode_exit": "Izhod", + "reviewMode_connectFailed": "Načina pregleda ni bilo mogoče zagnati: {error}" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 6f661397..fa05c8e5 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3053,13 +3053,13 @@ } }, "receivedImage_saveFailed": "Kunde inte spara bilden", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Aktivera granskningsläge?", + "reviewMode_dialogBody": "Granskningsläget ansluter till en simulerad radio med exempelkontakter, kanaler och meddelanden. Ingen riktig radio behövs.", + "reviewMode_confirm": "Aktivera", + "reviewMode_cancel": "Avbryt", + "reviewMode_banner": "Granskningsläge — simulerad data", + "reviewMode_sendTest": "Skicka testmeddelande", + "reviewMode_testSent": "Ett testmeddelande kommer snart.", + "reviewMode_exit": "Avsluta", + "reviewMode_connectFailed": "Det gick inte att starta granskningsläget: {error}" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 3287f65b..cbb51485 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3032,13 +3032,13 @@ } }, "receivedImage_saveFailed": "Не вдалося зберегти зображення", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "Увійти в режим перевірки?", + "reviewMode_dialogBody": "Режим перевірки підключається до імітованого радіо із прикладами контактів, каналів і повідомлень. Справжнє радіо не потрібне.", + "reviewMode_confirm": "Увійти", + "reviewMode_cancel": "Скасувати", + "reviewMode_banner": "Режим перевірки — імітовані дані", + "reviewMode_sendTest": "Тестове повідомлення", + "reviewMode_testSent": "Незабаром надійде тестове повідомлення.", + "reviewMode_exit": "Вийти", + "reviewMode_connectFailed": "Не вдалося запустити режим перевірки: {error}" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index cd9427ab..b80fed10 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3057,13 +3057,13 @@ } }, "receivedImage_saveFailed": "无法保存图片", - "reviewMode_dialogTitle": "Enter review mode?", - "reviewMode_dialogBody": "Review mode connects to a simulated radio with sample contacts, channels and messages. No real radio is needed.", - "reviewMode_confirm": "Enter", - "reviewMode_cancel": "Cancel", - "reviewMode_banner": "Review mode — simulated data", - "reviewMode_sendTest": "Send test message", - "reviewMode_testSent": "A test message will arrive shortly.", - "reviewMode_exit": "Exit", - "reviewMode_connectFailed": "Could not start review mode: {error}" + "reviewMode_dialogTitle": "进入审核模式?", + "reviewMode_dialogBody": "审核模式会连接到模拟设备,其中包含示例联系人、频道和消息。无需真实设备。", + "reviewMode_confirm": "进入", + "reviewMode_cancel": "取消", + "reviewMode_banner": "审核模式 — 模拟数据", + "reviewMode_sendTest": "发送测试消息", + "reviewMode_testSent": "测试消息即将送达。", + "reviewMode_exit": "退出", + "reviewMode_connectFailed": "无法启动审核模式:{error}" } From 551bf128c6a67c1f964263419837a196ec4c118e Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 21:01:53 -0700 Subject: [PATCH 11/28] Enable edge-to-edge on all Android versions and upgrade packages - Opt Android 14 and older into edge-to-edge so every version lays out the same way Android 15+ already enforces, and make the navigation bar transparent (its color is ignored on Android 15) - Raise minimum versions for packages with relevant fixes: flutter_blue_plus 2.3.14 (Android connection-state fixes), mobile_scanner 7.4.2 (scanner stall and camera-start crash fixes), flutter_map 8.3.2 (crash on NaN marker coordinates), flutter_onnxruntime 1.9.0 (ONNX Runtime 1.28), share_plus 13.3.1, flutter_cache_manager 3.4.5, flutter_local_notifications 22.3.1, package_info_plus 10.2.2 --- lib/main.dart | 14 ++++++++++---- pubspec.yaml | 16 ++++++++-------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 7162f67a..2014d5e3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -49,6 +49,12 @@ void main() async { debugPrint = (String? message, {int? wrapWidth}) {}; } + // Android 15+ forces edge-to-edge for apps targeting SDK 35; opt older + // versions in too so every device lays out the same way under the bars. + if (PlatformInfo.isAndroid) { + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } + // Initialize SharedPreferences cache await PrefsManager.initialize(); @@ -461,18 +467,18 @@ class _MeshCoreAppState extends State with WidgetsBindingObserver { SystemUiOverlayStyle _systemUiOverlayStyle(BuildContext context) { final theme = Theme.of(context); - final colorScheme = theme.colorScheme; final isDark = theme.brightness == Brightness.dark; final iconBrightness = isDark ? Brightness.light : Brightness.dark; - // Keep Android system bars aligned with the resolved Flutter theme. + // The app draws edge-to-edge, so both system bars stay transparent and + // only their icon brightness follows the resolved Flutter theme. return SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarIconBrightness: iconBrightness, statusBarBrightness: isDark ? Brightness.dark : Brightness.light, - systemNavigationBarColor: colorScheme.surface, + systemNavigationBarColor: Colors.transparent, systemNavigationBarIconBrightness: iconBrightness, - systemNavigationBarDividerColor: colorScheme.surface, + systemNavigationBarDividerColor: Colors.transparent, systemNavigationBarContrastEnforced: false, ); } diff --git a/pubspec.yaml b/pubspec.yaml index a0411431..f1065222 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -37,7 +37,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 - flutter_blue_plus: ^2.1.0 + flutter_blue_plus: ^2.3.14 # TODO: Switch to official flserial repo once changes are upstreamed flserial: git: @@ -47,18 +47,18 @@ dependencies: provider: ^6.1.5+1 shared_preferences: ^2.2.2 uuid: ^4.3.3 - flutter_map: ^8.2.2 + flutter_map: ^8.3.2 latlong2: ^0.9.1 - flutter_local_notifications: ^22.0.0 + flutter_local_notifications: ^22.3.1 crypto: ^3.0.3 pointycastle: ^4.0.0 http: ^1.2.0 cached_network_image: ^3.4.1 - flutter_cache_manager: ^3.4.1 + flutter_cache_manager: ^3.4.5 flutter_foreground_task: ^9.2.0 characters: ^1.4.0 - package_info_plus: ^10.1.0 - mobile_scanner: ^7.1.4 # QR/barcode scanning + package_info_plus: ^10.2.2 + mobile_scanner: ^7.4.2 # QR/barcode scanning image_picker: ^1.1.2 # Pick photos to send as compressed mesh images qr_flutter: ^4.1.0 # QR code generation url_launcher: ^6.3.0 # Launch URLs in system browser @@ -66,7 +66,7 @@ dependencies: gpx: ^2.3.0 path_provider: ^2.1.5 file_selector: ^1.0.3 # desktop save dialog for GPX export - share_plus: ^13.1.0 + share_plus: ^13.3.1 build_pipe: ^0.3.1 material_symbols_icons: ^4.2928.1 web: ^1.1.1 @@ -83,7 +83,7 @@ dependencies: # decoder (lib/services/image_codec_backend.dart). arm64-only on Android — see # the abiFilters note in android/app/build.gradle.kts; a universal APK pays # ~56 MB for ORT instead of ~18 MB. - flutter_onnxruntime: ^1.8.3 + flutter_onnxruntime: ^1.9.0 base32: ^2.2.0 hooks: From 1d64399d420883155444629bf5517c143b33dac0 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 21:06:41 -0700 Subject: [PATCH 12/28] Keep system bar content usable under edge-to-edge - Lift the QR scanner's torch and camera controls above the navigation bar instead of 16 px from the screen edge - Use light system bar icons on the black QR camera and received-image viewer, and keep Android's contrast scrim behind three-button navigation for any other dark route - Note that Flutter only applies edge-to-edge from Android 10 --- lib/main.dart | 12 +++-- lib/widgets/qr_scanner_widget.dart | 46 ++++++++++-------- lib/widgets/received_image_message.dart | 64 +++++++++++++------------ 3 files changed, 68 insertions(+), 54 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 2014d5e3..fa49e65f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -49,8 +49,9 @@ void main() async { debugPrint = (String? message, {int? wrapWidth}) {}; } - // Android 15+ forces edge-to-edge for apps targeting SDK 35; opt older - // versions in too so every device lays out the same way under the bars. + // Android 15+ forces edge-to-edge for apps targeting SDK 35; opt Android + // 10-14 in too so they lay out the same way under the bars. Flutter ignores + // this mode before Android 10, where the old layout remains. if (PlatformInfo.isAndroid) { await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); } @@ -471,7 +472,10 @@ class _MeshCoreAppState extends State with WidgetsBindingObserver { final iconBrightness = isDark ? Brightness.light : Brightness.dark; // The app draws edge-to-edge, so both system bars stay transparent and - // only their icon brightness follows the resolved Flutter theme. + // their icon brightness follows the resolved Flutter theme. Contrast + // enforcement keeps a scrim behind three-button navigation in case a + // route paints a dark surface under light-theme icons; dark full-screen + // routes also set light icons themselves. return SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarIconBrightness: iconBrightness, @@ -479,7 +483,7 @@ class _MeshCoreAppState extends State with WidgetsBindingObserver { systemNavigationBarColor: Colors.transparent, systemNavigationBarIconBrightness: iconBrightness, systemNavigationBarDividerColor: Colors.transparent, - systemNavigationBarContrastEnforced: false, + systemNavigationBarContrastEnforced: true, ); } diff --git a/lib/widgets/qr_scanner_widget.dart b/lib/widgets/qr_scanner_widget.dart index 5b6cf5e3..e54b379e 100644 --- a/lib/widgets/qr_scanner_widget.dart +++ b/lib/widgets/qr_scanner_widget.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; /// A reusable QR code scanner widget that can be embedded anywhere. @@ -150,28 +151,33 @@ class _QrScannerWidgetState extends State @override Widget build(BuildContext context) { - return Stack( - children: [ - // Scanner view - MobileScanner( - controller: _controller, - onDetect: _handleDetection, - errorBuilder: (context, error) { - return _buildErrorWidget(context, error); - }, - ), + // The camera preview is dark, so keep the system bar icons light, and lift + // the controls above the navigation bar the app draws behind. + return AnnotatedRegion( + value: SystemUiOverlayStyle.light, + child: Stack( + children: [ + // Scanner view + MobileScanner( + controller: _controller, + onDetect: _handleDetection, + errorBuilder: (context, error) { + return _buildErrorWidget(context, error); + }, + ), - // Overlay - widget.overlay ?? _buildDefaultOverlay(context), + // Overlay + widget.overlay ?? _buildDefaultOverlay(context), - // Control buttons - Positioned( - bottom: 16, - left: 0, - right: 0, - child: _buildControls(context), - ), - ], + // Control buttons + Positioned( + bottom: 16 + MediaQuery.viewPaddingOf(context).bottom, + left: 0, + right: 0, + child: _buildControls(context), + ), + ], + ), ); } diff --git a/lib/widgets/received_image_message.dart b/lib/widgets/received_image_message.dart index e3f56350..253f5164 100644 --- a/lib/widgets/received_image_message.dart +++ b/lib/widgets/received_image_message.dart @@ -29,9 +29,8 @@ /// with whoever implements export, not here. library; -import 'dart:typed_data'; - import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import '../services/received_image_store.dart'; @@ -618,36 +617,41 @@ class _ReceivedImageViewer extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.black, - appBar: AppBar( + // Light system bar icons over the black viewer, whatever the app theme. + return AnnotatedRegion( + value: SystemUiOverlayStyle.light, + child: Scaffold( backgroundColor: Colors.black, - foregroundColor: Colors.white, - ), - body: Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: Stack( - children: [ - InteractiveViewer(child: Image.memory(png)), - if (synthesized) - const Positioned( - left: 0, - right: 0, - bottom: 0, - child: _SyntheticBanner(), - ), - ], + appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, + systemOverlayStyle: SystemUiOverlayStyle.light, + ), + body: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Stack( + children: [ + InteractiveViewer(child: Image.memory(png)), + if (synthesized) + const Positioned( + left: 0, + right: 0, + bottom: 0, + child: _SyntheticBanner(), + ), + ], + ), ), - ), - if (synthesized) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: _SyntheticCaption(bytes: bytes, onDark: true), - ), - ], + if (synthesized) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _SyntheticCaption(bytes: bytes, onDark: true), + ), + ], + ), ), ), ); From ef53b8f390f0b72f070c6734e85159414b8b3c60 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 21:12:59 -0700 Subject: [PATCH 13/28] Default discovered-contact eviction on and harden the auto-add dialog - Default evictDiscoveredContactsEnabled to true so the 500-entry cap stays in effect unless the user opts out - Evict until under the cap when adding, so an oversized list recovers - Pass the cap into the localized subtitle instead of hard-coding 500 - Fix German title and subtitle wording - Save: block double taps, send radio config first, show an error if persisting the setting fails - Restore untranslated.json to match dev --- lib/connector/meshcore_connector.dart | 23 ++-- lib/l10n/app_de.arb | 11 +- lib/l10n/app_en.arb | 9 +- lib/l10n/app_localizations.dart | 4 +- lib/l10n/app_localizations_bg.dart | 5 +- lib/l10n/app_localizations_de.dart | 7 +- lib/l10n/app_localizations_en.dart | 5 +- 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 | 5 +- lib/l10n/app_localizations_ko.dart | 5 +- lib/l10n/app_localizations_nl.dart | 5 +- lib/l10n/app_localizations_pl.dart | 5 +- lib/l10n/app_localizations_pt.dart | 5 +- 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 | 5 +- lib/models/app_settings.dart | 4 +- lib/screens/settings_screen.dart | 57 ++++++---- test/models/model_changes_test.dart | 4 +- untranslated.json | 149 +------------------------- 26 files changed, 130 insertions(+), 223 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 123016eb..d5eb2282 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -180,7 +180,7 @@ class MeshCoreConnector extends ChangeNotifier { // continuously from the whole mesh, so without a bound this list grows for // as long as the app stays connected. When full, the stalest node (oldest // lastSeen) is evicted to make room for a newly heard one. - static const int _maxDiscoveredContacts = 500; + static const int maxDiscoveredContacts = 500; MeshCoreConnectionState _state = MeshCoreConnectionState.disconnected; BluetoothDevice? _device; @@ -1356,9 +1356,10 @@ class MeshCoreConnector extends ChangeNotifier { Future _loadDiscoveredContactCache() async { final cached = await _discoveryContactStore.loadContacts(); - // Trim a previously-saved oversized list down to the freshest entries so a - // device that grew unbounded before the cap existed recovers on load. - if (_appSettingsService?.settings.evictDiscoveredContactsEnabled == true && + // When eviction is enabled, trim a previously-saved oversized list down to + // the freshest entries so a device that grew unbounded before the cap + // existed recovers on load. + if (_evictDiscoveredContactsEnabled && _trimDiscoveredContactsToLimit(cached)) { unawaited(_discoveryContactStore.saveContacts(cached)); } @@ -1367,10 +1368,13 @@ class MeshCoreConnector extends ChangeNotifier { ..addAll(cached); } + bool get _evictDiscoveredContactsEnabled => + _appSettingsService?.settings.evictDiscoveredContactsEnabled ?? true; + bool _trimDiscoveredContactsToLimit(List contacts) { - if (contacts.length <= _maxDiscoveredContacts) return false; + if (contacts.length <= maxDiscoveredContacts) return false; contacts.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); - contacts.removeRange(_maxDiscoveredContacts, contacts.length); + contacts.removeRange(maxDiscoveredContacts, contacts.length); return true; } @@ -8194,9 +8198,10 @@ class MeshCoreConnector extends ChangeNotifier { flags: 0, ); - if (_appSettingsService?.settings.evictDiscoveredContactsEnabled == true && - _discoveredContacts.length >= _maxDiscoveredContacts) { - _evictStalestDiscoveredContact(); + if (_evictDiscoveredContactsEnabled) { + while (_discoveredContacts.length >= maxDiscoveredContacts) { + _evictStalestDiscoveredContact(); + } } _discoveredContacts.add(disContact); diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 733c35cc..ff4527fc 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -2145,8 +2145,15 @@ "discoveredContacts_copyContact": "Kontakt in die Zwischenablage kopieren", "contactsSettings_overwriteOldestTitle": "Überschreiben des Ältesten", "contactsSettings_overwriteOldestSubtitle": "Wenn die Kontaktliste voll ist, wird der älteste nicht favorisierte Kontakt ersetzt.", - "contactsSettings_evictDiscoveredContactsTitle": "Kürze entdeckte Kontakte Liste", - "contactsSettings_evictDiscoveredContactsSubtitle": "Wenn aktiviert, wird die Liste der entdeckten Kontackte auf 500 Kontakten begrenzt.", + "contactsSettings_evictDiscoveredContactsTitle": "Liste entdeckter Kontakte kürzen", + "contactsSettings_evictDiscoveredContactsSubtitle": "Wenn aktiviert, wird die Liste der entdeckten Kontakte auf {limit} Kontakte begrenzt.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Alles löschen", "discoveredContacts_deleteContactAllContent": "Sind Sie sicher, dass Sie alle gefundenen Kontakte löschen möchten?", "discoveredContacts_deleteContactAll": "Alle entdeckten Kontakte löschen", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index ace29877..06ae5d01 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2649,7 +2649,14 @@ "contactsSettings_overwriteOldestTitle": "Overwrite Oldest", "contactsSettings_overwriteOldestSubtitle": "When the contact list is full, the oldest non-favorited contact will be replaced.", "contactsSettings_evictDiscoveredContactsTitle": "Evict discovered contacts", - "contactsSettings_evictDiscoveredContactsSubtitle": "When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.", + "contactsSettings_evictDiscoveredContactsSubtitle": "When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of {limit} entries.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "discoveredContacts_Title": "Discovered Contacts", "discoveredContacts_noMatching": "No matching contacts", "discoveredContacts_searchHint": "Search discovered contacts", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 81a34f45..a1ccd08c 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -8215,8 +8215,8 @@ abstract class AppLocalizations { /// No description provided for @contactsSettings_evictDiscoveredContactsSubtitle. /// /// In en, this message translates to: - /// **'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'** - String get contactsSettings_evictDiscoveredContactsSubtitle; + /// **'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of {limit} entries.'** + String contactsSettings_evictDiscoveredContactsSubtitle(int limit); /// No description provided for @discoveredContacts_Title. /// diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index a12ec148..1bd49aad 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4794,8 +4794,9 @@ class AppLocalizationsBg extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Открити контакти'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index bd0c4afc..1fd2b632 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4803,11 +4803,12 @@ class AppLocalizationsDe extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Kürze entdeckte Kontakte Liste'; + 'Liste entdeckter Kontakte kürzen'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'Wenn aktiviert, wird die Liste der entdeckten Kontackte auf 500 Kontakten begrenzt.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'Wenn aktiviert, wird die Liste der entdeckten Kontakte auf $limit Kontakte begrenzt.'; + } @override String get discoveredContacts_Title => 'Entdeckte Kontakte'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index b297ecfc..4af5d2f0 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4725,8 +4725,9 @@ class AppLocalizationsEn extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Discovered Contacts'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 01605a9a..2c35a02b 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4797,8 +4797,9 @@ class AppLocalizationsEs extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Contactos descubiertos'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index be24acc8..76e862d4 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4819,8 +4819,9 @@ class AppLocalizationsFr extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Contacts découverts'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 25de36d7..44b737a2 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4793,8 +4793,9 @@ class AppLocalizationsHu extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Felfedezett kapcsolatok'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 3c681e76..d48917c7 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4803,8 +4803,9 @@ class AppLocalizationsIt extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Contatti scoperti'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 49bad245..872deafe 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4559,8 +4559,9 @@ class AppLocalizationsJa extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => '連絡先が見つかった'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 25ae2f8c..18fa4cd9 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4569,8 +4569,9 @@ class AppLocalizationsKo extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => '연락처 찾기'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 0f258b4b..f5959632 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4771,8 +4771,9 @@ class AppLocalizationsNl extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Ontdekte contacten'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index d330c3ce..fab6a476 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4826,8 +4826,9 @@ class AppLocalizationsPl extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Odkryte Kontakty'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 6f80b835..da2d61b0 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4798,8 +4798,9 @@ class AppLocalizationsPt extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Contatos Descobertos'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 3f4060c3..d63112b2 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4810,8 +4810,9 @@ class AppLocalizationsRu extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Обнаруженные контакты'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index ec95f35f..f939911e 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4780,8 +4780,9 @@ class AppLocalizationsSk extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Objavené kontakty'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 31a4da7d..77349499 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4780,8 +4780,9 @@ class AppLocalizationsSl extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Odkriti stiki'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index ef46c8f1..eaacb8f3 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4755,8 +4755,9 @@ class AppLocalizationsSv extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Upptäckta kontakter'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index dcf31ac6..6bbb580b 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4809,8 +4809,9 @@ class AppLocalizationsUk extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => 'Виявлені контакти'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 8525ffe9..2b7dcffb 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4444,8 +4444,9 @@ class AppLocalizationsZh extends AppLocalizations { 'Evict discovered contacts'; @override - String get contactsSettings_evictDiscoveredContactsSubtitle => - 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of 500 entries.'; + String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { + return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + } @override String get discoveredContacts_Title => '已发现的联系人'; diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index f64aa573..547b1e3e 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -227,7 +227,7 @@ class AppSettings { this.unitSystem = UnitSystem.metric, Set? mutedChannels, this.mapShowDiscoveryContacts = true, - this.evictDiscoveredContactsEnabled = false, + this.evictDiscoveredContactsEnabled = true, this.tcpServerAddress = '', this.tcpServerPort = 0, this.jumpToOldestUnread = false, @@ -411,7 +411,7 @@ class AppSettings { mapShowDiscoveryContacts: json['map_show_discovery_contacts'] as bool? ?? true, evictDiscoveredContactsEnabled: - json['evict_discovered_contacts_enabled'] as bool? ?? false, + json['evict_discovered_contacts_enabled'] as bool? ?? true, tcpServerAddress: json['tcp_server_address'] as String? ?? '', tcpServerPort: json['tcp_server_port'] as int? ?? 0, jumpToOldestUnread: json['jump_to_oldest_unread'] as bool? ?? false, diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 25c0ea21..a43d6051 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1234,6 +1234,7 @@ class _SettingsScreenState extends State { final appSettingsService = context.read(); bool evictDiscoveredContactsEnabled = appSettingsService.settings.evictDiscoveredContactsEnabled; + bool saving = false; final connector = context.read(); autoAddChat = connector.autoAddUsers ?? false; @@ -1298,8 +1299,10 @@ class _SettingsScreenState extends State { const Divider(height: 4), FeatureToggleRow( title: l10n.contactsSettings_evictDiscoveredContactsTitle, - subtitle: - l10n.contactsSettings_evictDiscoveredContactsSubtitle, + subtitle: l10n + .contactsSettings_evictDiscoveredContactsSubtitle( + MeshCoreConnector.maxDiscoveredContacts, + ), value: evictDiscoveredContactsEnabled, onChanged: (value) { setDialogState( @@ -1316,24 +1319,38 @@ class _SettingsScreenState extends State { child: Text(l10n.common_cancel), ), TextButton( - onPressed: () async { - await appSettingsService.setEvictDiscoveredContactsEnabled( - evictDiscoveredContactsEnabled, - ); - if (evictDiscoveredContactsEnabled) { - await connector.trimDiscoveredContactsToLimit(); - } - _sendSettings( - connector, - autoAddChat, - autoAddRepeater, - autoAddRoomServer, - autoAddSensor, - overwriteOldest, - ); - if (!context.mounted) return; - Navigator.pop(context); - }, + onPressed: saving + ? null + : () async { + setDialogState(() => saving = true); + _sendSettings( + connector, + autoAddChat, + autoAddRepeater, + autoAddRoomServer, + autoAddSensor, + overwriteOldest, + ); + try { + await appSettingsService + .setEvictDiscoveredContactsEnabled( + evictDiscoveredContactsEnabled, + ); + if (evictDiscoveredContactsEnabled) { + await connector.trimDiscoveredContactsToLimit(); + } + } catch (e) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + setDialogState(() => saving = false); + return; + } + if (!context.mounted) return; + Navigator.pop(context); + }, child: Text(l10n.common_save), ), ], diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index fcac50bb..b96666e3 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -405,7 +405,7 @@ void main() { expect(settings.routeWeightSuccessIncrement, equals(0.5)); expect(settings.routeWeightFailureDecrement, equals(0.2)); expect(settings.maxMessageRetries, equals(5)); - expect(settings.evictDiscoveredContactsEnabled, isFalse); + expect(settings.evictDiscoveredContactsEnabled, isTrue); }); test('toJson includes all new fields', () { @@ -422,7 +422,7 @@ void main() { expect(json['route_weight_success_increment'], equals(0.5)); expect(json['route_weight_failure_decrement'], equals(0.2)); expect(json['max_message_retries'], equals(5)); - expect(json['evict_discovered_contacts_enabled'], isFalse); + expect(json['evict_discovered_contacts_enabled'], isTrue); }); test('fromJson reads all new fields', () { diff --git a/untranslated.json b/untranslated.json index 0d526645..9e26dfee 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,148 +1 @@ -{ - "bg": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "de": [ - "settings_publicKeyCopied", - "reaction_report" - ], - - "es": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "fr": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "hu": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "it": [ - "urlImage_enable", - "urlImage_possible", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "ja": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "ko": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "nl": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "pl": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "pt": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "ru": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "sk": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "sl": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "sv": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "uk": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ], - - "zh": [ - "urlImage_enable", - "urlImage_possible", - "settings_publicKeyCopied", - "reaction_report", - "contactsSettings_evictDiscoveredContactsTitle", - "contactsSettings_evictDiscoveredContactsSubtitle" - ] -} +{} \ No newline at end of file From cdb6f4220566973a4357af14d97f01b4d78ab05f Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 21:18:34 -0700 Subject: [PATCH 14/28] Translate discovered-contact eviction strings for all locales --- lib/l10n/app_bg.arb | 9 +++++++++ lib/l10n/app_es.arb | 9 +++++++++ lib/l10n/app_fr.arb | 9 +++++++++ lib/l10n/app_hu.arb | 9 +++++++++ lib/l10n/app_it.arb | 9 +++++++++ lib/l10n/app_ja.arb | 9 +++++++++ lib/l10n/app_ko.arb | 9 +++++++++ lib/l10n/app_localizations_bg.dart | 4 ++-- lib/l10n/app_localizations_es.dart | 4 ++-- lib/l10n/app_localizations_fr.dart | 4 ++-- lib/l10n/app_localizations_hu.dart | 4 ++-- lib/l10n/app_localizations_it.dart | 4 ++-- lib/l10n/app_localizations_ja.dart | 5 ++--- lib/l10n/app_localizations_ko.dart | 5 ++--- lib/l10n/app_localizations_nl.dart | 4 ++-- lib/l10n/app_localizations_pl.dart | 4 ++-- lib/l10n/app_localizations_pt.dart | 4 ++-- lib/l10n/app_localizations_ru.dart | 4 ++-- lib/l10n/app_localizations_sk.dart | 4 ++-- lib/l10n/app_localizations_sl.dart | 4 ++-- lib/l10n/app_localizations_sv.dart | 4 ++-- lib/l10n/app_localizations_uk.dart | 4 ++-- lib/l10n/app_localizations_zh.dart | 5 ++--- lib/l10n/app_nl.arb | 9 +++++++++ lib/l10n/app_pl.arb | 9 +++++++++ lib/l10n/app_pt.arb | 9 +++++++++ lib/l10n/app_ru.arb | 9 +++++++++ lib/l10n/app_sk.arb | 9 +++++++++ lib/l10n/app_sl.arb | 9 +++++++++ lib/l10n/app_sv.arb | 9 +++++++++ lib/l10n/app_uk.arb | 9 +++++++++ lib/l10n/app_zh.arb | 9 +++++++++ 32 files changed, 176 insertions(+), 35 deletions(-) diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index c93f6803..a871fc21 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -2018,6 +2018,15 @@ "discoveredContacts_deleteContact": "Изтрий контакт", "discoveredContacts_addContact": "Добави контакт", "contactsSettings_overwriteOldestSubtitle": "Когато списъкът с контакти е пълен, най-старият неключов контакт ще бъде заменен.", + "contactsSettings_evictDiscoveredContactsTitle": "Премахване на открити контакти", + "contactsSettings_evictDiscoveredContactsSubtitle": "Когато е включено, приложението премахва най-старите открити контакти, щом списъкът с открити контакти достигне лимита си от {limit} записа.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "discoveredContacts_deleteContactAll": "Изтриване на Всички Открити Контакти", "discoveredContacts_deleteContactAllContent": "Сигурни ли сте, че искате да изтриете всички открити контакти?", "common_deleteAll": "Изтрий всичко", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 91fbf2bc..6b0c9c53 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -2145,6 +2145,15 @@ "discoveredContacts_searchHint": "Buscar contactos descubiertos", "discoveredContacts_addContact": "Agregar contacto", "contactsSettings_overwriteOldestSubtitle": "Cuando la lista de contactos esté llena, se reemplazará el contacto no favorito más antiguo.", + "contactsSettings_evictDiscoveredContactsTitle": "Expulsar contactos descubiertos", + "contactsSettings_evictDiscoveredContactsSubtitle": "Si está activado, la aplicación elimina los contactos descubiertos más antiguos cuando la lista de descubrimiento alcanza su límite de {limit} entradas.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Eliminar todo", "discoveredContacts_deleteContactAll": "Eliminar Todos los Contactos Descubiertos", "discoveredContacts_deleteContactAllContent": "¿Está seguro de que desea eliminar todos los contactos descubiertos!", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index ac27208e..0e5b56ba 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2138,6 +2138,15 @@ "discoveredContacts_Title": "Contacts découverts", "discoveredContacts_searchHint": "Rechercher des contacts découverts", "contactsSettings_overwriteOldestSubtitle": "Lorsque la liste de contacts est pleine, le contact le plus ancien non favori sera remplacé.", + "contactsSettings_evictDiscoveredContactsTitle": "Évincer les contacts découverts", + "contactsSettings_evictDiscoveredContactsSubtitle": "Lorsque cette option est activée, l'application supprime les contacts découverts les plus anciens dès que la liste de découverte atteint sa limite de {limit} entrées.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Tout supprimer", "discoveredContacts_deleteContactAll": "Supprimer tous les contacts découverts", "discoveredContacts_deleteContactAllContent": "Êtes-vous sûr de vouloir supprimer tous les contacts découverts ?", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index cb7a649b..0a733183 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -2133,6 +2133,15 @@ "contactsSettings_autoAddSensorsSubtitle": "Engedélyezze a társ számára a felfedezett érzékelők automatikus hozzáadását.", "contactsSettings_overwriteOldestTitle": "A legrégebbi felülírása", "contactsSettings_overwriteOldestSubtitle": "Amikor a névjegylista megtelik, a legrégebbi, nem kedvenc névjegy lecserélődik.", + "contactsSettings_evictDiscoveredContactsTitle": "Felfedezett kapcsolatok eltávolítása", + "contactsSettings_evictDiscoveredContactsSubtitle": "Ha engedélyezve van, az alkalmazás eltávolítja a legrégebbi felfedezett kapcsolatokat, amint a felfedezési lista eléri a(z) {limit} bejegyzéses korlátot.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "discoveredContacts_Title": "Felfedezett kapcsolatok", "discoveredContacts_noMatching": "Nincsenek megfelelő névjegyek", "discoveredContacts_searchHint": "Keresés a talált névjegyek között", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 820d3c7d..35bb2b8a 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -2149,6 +2149,15 @@ "discoveredContacts_deleteContact": "Elimina Contatto", "discoveredContacts_copyContact": "Copia contatto negli appunti", "contactsSettings_overwriteOldestSubtitle": "Quando l'elenco dei contatti è pieno, il contatto più vecchio non tra i preferiti verrà sostituito.", + "contactsSettings_evictDiscoveredContactsTitle": "Rimuovi i contatti scoperti", + "contactsSettings_evictDiscoveredContactsSubtitle": "Se abilitato, l'app rimuove i contatti scoperti più vecchi quando l'elenco dei contatti scoperti raggiunge il limite di {limit} voci.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Elimina tutto", "discoveredContacts_deleteContactAllContent": "Sei sicuro di voler eliminare tutti i contatti scoperti?", "discoveredContacts_deleteContactAll": "Eliminare tutti i contatti scoperti", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 91c39b9c..39d0db1e 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -2228,6 +2228,15 @@ "contactsSettings_autoAddSensorsSubtitle": "利用者が、発見したセンサーを自動的に追加できるようにする。", "contactsSettings_overwriteOldestTitle": "最も古いものを上書きする", "contactsSettings_overwriteOldestSubtitle": "連絡先リストが満杯になった場合、最も古いかつ「お気に入り」ではない連絡先が削除されます。", + "contactsSettings_evictDiscoveredContactsTitle": "検出された連絡先を削除", + "contactsSettings_evictDiscoveredContactsSubtitle": "有効にすると、検出された連絡先のリストが上限の{limit}件に達した際に、最も古い検出済み連絡先が削除されます。", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "discoveredContacts_Title": "連絡先が見つかった", "discoveredContacts_noMatching": "一致する連絡先が見つかりませんでした", "discoveredContacts_searchHint": "発見された連絡先を検索する", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 65bacbae..17becbc6 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -2133,6 +2133,15 @@ "contactsSettings_autoAddSensorsSubtitle": "애완동물이 발견한 센서를 자동으로 추가할 수 있도록 설정합니다.", "contactsSettings_overwriteOldestTitle": "가장 오래된 것을 덮어쓰기", "contactsSettings_overwriteOldestSubtitle": "연락처 목록이 가득 차면, 가장 오래된 (선호하지 않은) 연락처가 대체됩니다.", + "contactsSettings_evictDiscoveredContactsTitle": "발견된 연락처 삭제", + "contactsSettings_evictDiscoveredContactsSubtitle": "활성화하면 발견된 연락처 목록이 {limit}개의 한도에 도달했을 때 가장 오래된 발견된 연락처를 삭제합니다.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "discoveredContacts_Title": "연락처 찾기", "discoveredContacts_noMatching": "일치하는 연락처가 없습니다.", "discoveredContacts_searchHint": "발견된 연락처 검색", diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 1bd49aad..8ddb847a 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4791,11 +4791,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Премахване на открити контакти'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Когато е включено, приложението премахва най-старите открити контакти, щом списъкът с открити контакти достигне лимита си от $limit записа.'; } @override diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 2c35a02b..58e63f45 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4794,11 +4794,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Expulsar contactos descubiertos'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Si está activado, la aplicación elimina los contactos descubiertos más antiguos cuando la lista de descubrimiento alcanza su límite de $limit entradas.'; } @override diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 76e862d4..aa6a2822 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4816,11 +4816,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Évincer les contacts découverts'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Lorsque cette option est activée, l\'application supprime les contacts découverts les plus anciens dès que la liste de découverte atteint sa limite de $limit entrées.'; } @override diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 44b737a2..49d60c26 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4790,11 +4790,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Felfedezett kapcsolatok eltávolítása'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Ha engedélyezve van, az alkalmazás eltávolítja a legrégebbi felfedezett kapcsolatokat, amint a felfedezési lista eléri a(z) $limit bejegyzéses korlátot.'; } @override diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index d48917c7..7079893e 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4800,11 +4800,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Rimuovi i contatti scoperti'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Se abilitato, l\'app rimuove i contatti scoperti più vecchi quando l\'elenco dei contatti scoperti raggiunge il limite di $limit voci.'; } @override diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 872deafe..1a2b875e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4555,12 +4555,11 @@ class AppLocalizationsJa extends AppLocalizations { '連絡先リストが満杯になった場合、最も古いかつ「お気に入り」ではない連絡先が削除されます。'; @override - String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + String get contactsSettings_evictDiscoveredContactsTitle => '検出された連絡先を削除'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return '有効にすると、検出された連絡先のリストが上限の$limit件に達した際に、最も古い検出済み連絡先が削除されます。'; } @override diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 18fa4cd9..0842f889 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4565,12 +4565,11 @@ class AppLocalizationsKo extends AppLocalizations { '연락처 목록이 가득 차면, 가장 오래된 (선호하지 않은) 연락처가 대체됩니다.'; @override - String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + String get contactsSettings_evictDiscoveredContactsTitle => '발견된 연락처 삭제'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return '활성화하면 발견된 연락처 목록이 $limit개의 한도에 도달했을 때 가장 오래된 발견된 연락처를 삭제합니다.'; } @override diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index f5959632..92f2d27d 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4768,11 +4768,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Ontdekte contacten verwijderen'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Indien ingeschakeld verwijdert de app de oudste ontdekte contacten zodra de lijst met ontdekte contacten de limiet van $limit items bereikt.'; } @override diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index fab6a476..b5e95fc6 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4823,11 +4823,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Usuwaj odkryte kontakty'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Gdy ta opcja jest włączona, aplikacja usuwa najstarsze odkryte kontakty, gdy lista odkrytych osiągnie limit $limit wpisów.'; } @override diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index da2d61b0..c0cb6931 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4795,11 +4795,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Remover contatos descobertos'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Quando ativado, o aplicativo remove os contatos descobertos mais antigos assim que a lista de descobertos atingir o limite de $limit entradas.'; } @override diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index d63112b2..f7ff950c 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4807,11 +4807,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Удалять обнаруженные контакты'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Если включено, приложение удаляет самые старые обнаруженные контакты, когда список обнаруженных достигает лимита в $limit записей.'; } @override diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index f939911e..9490e022 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4777,11 +4777,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Odstraňovať objavené kontakty'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Keď je táto možnosť zapnutá, aplikácia odstráni najstaršie objavené kontakty, keď zoznam objavených dosiahne limit $limit záznamov.'; } @override diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 77349499..52c311b5 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4777,11 +4777,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Odstrani odkrite stike'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Ko je ta možnost vklopljena, aplikacija odstrani najstarejše odkrite stike, ko seznam odkritih stikov doseže omejitev $limit vnosov.'; } @override diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index eaacb8f3..84fcfeb9 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4752,11 +4752,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Rensa upptäckta kontakter'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'När detta är aktiverat tar appen bort de äldsta upptäckta kontakterna när listan över upptäckta kontakter når sin gräns på $limit poster.'; } @override diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 6bbb580b..f8c56dec 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4806,11 +4806,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + 'Видаляти виявлені контакти'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return 'Якщо ввімкнено, застосунок видаляє найстаріші виявлені контакти, коли список виявлених контактів досягає ліміту в $limit записів.'; } @override diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 2b7dcffb..9276c9cc 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4440,12 +4440,11 @@ class AppLocalizationsZh extends AppLocalizations { '当联系人列表已满时,将替换最老的非收藏联系人。'; @override - String get contactsSettings_evictDiscoveredContactsTitle => - 'Evict discovered contacts'; + String get contactsSettings_evictDiscoveredContactsTitle => '清除已发现的联系人'; @override String contactsSettings_evictDiscoveredContactsSubtitle(int limit) { - return 'When enabled, the app removes the oldest discovered contacts once the discovery list reaches its limit of $limit entries.'; + return '启用后,当已发现联系人列表达到 $limit 条的上限时,应用会移除最旧的已发现联系人。'; } @override diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index bb43678c..7f01ca01 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -2053,6 +2053,15 @@ "discoveredContacts_contactAdded": "Contact toegevoegd", "discoveredContacts_searchHint": "Ontdekte contacten zoeken", "contactsSettings_overwriteOldestSubtitle": "Wanneer de contactenlijst vol is, wordt de oudste niet-favoriete contactpersoon vervangen.", + "contactsSettings_evictDiscoveredContactsTitle": "Ontdekte contacten verwijderen", + "contactsSettings_evictDiscoveredContactsSubtitle": "Indien ingeschakeld verwijdert de app de oudste ontdekte contacten zodra de lijst met ontdekte contacten de limiet van {limit} items bereikt.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Alles verwijderen", "discoveredContacts_deleteContactAll": "Verwijder alle ontdekte contacten", "discoveredContacts_deleteContactAllContent": "Weet je zeker dat je alle ontdekte contacten wilt verwijderen?", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index 56e1dd7f..e1701d88 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -2056,6 +2056,15 @@ "discoveredContacts_noMatching": "Brak pasujących kontaktów", "discoveredContacts_deleteContact": "Usuń kontakt", "contactsSettings_overwriteOldestSubtitle": "Gdy lista kontaktów jest pełna, najstarszy nieulubiony kontakt zostanie zastąpiony.", + "contactsSettings_evictDiscoveredContactsTitle": "Usuwaj odkryte kontakty", + "contactsSettings_evictDiscoveredContactsSubtitle": "Gdy ta opcja jest włączona, aplikacja usuwa najstarsze odkryte kontakty, gdy lista odkrytych osiągnie limit {limit} wpisów.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Usuń wszystko", "discoveredContacts_deleteContactAllContent": "Czy na pewno chcesz usunąć wszystkie znalezione kontakty?", "discoveredContacts_deleteContactAll": "Usuń wszystkie odkryte kontakty", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 8e3b445c..0cb2a5c7 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -2018,6 +2018,15 @@ "discoveredContacts_contactAdded": "Contato adicionado", "discoveredContacts_addContact": "Adicionar Contato", "contactsSettings_overwriteOldestSubtitle": "Quando a lista de contatos estiver cheia, o contato mais antigo não favoritado será substituído.", + "contactsSettings_evictDiscoveredContactsTitle": "Remover contatos descobertos", + "contactsSettings_evictDiscoveredContactsSubtitle": "Quando ativado, o aplicativo remove os contatos descobertos mais antigos assim que a lista de descobertos atingir o limite de {limit} entradas.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Excluir Tudo", "discoveredContacts_deleteContactAll": "Excluir Todos os Contatos Descobertos", "discoveredContacts_deleteContactAllContent": "Tem certeza de que deseja excluir todos os contatos descobertos?", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 42e7c7b7..4afddfdc 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -1187,6 +1187,15 @@ "discoveredContacts_Title": "Обнаруженные контакты", "discoveredContacts_deleteContact": "Удалить контакт", "contactsSettings_overwriteOldestSubtitle": "Когда список контактов заполнен, будет заменен самый старый контакт, который не находится в избранном.", + "contactsSettings_evictDiscoveredContactsTitle": "Удалять обнаруженные контакты", + "contactsSettings_evictDiscoveredContactsSubtitle": "Если включено, приложение удаляет самые старые обнаруженные контакты, когда список обнаруженных достигает лимита в {limit} записей.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "common_deleteAll": "Удалить все", "discoveredContacts_deleteContactAllContent": "Вы уверены, что хотите удалить все обнаруженные контакты?", "discoveredContacts_deleteContactAll": "Удалить Все Обнаруженные Контакты", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index 5fa836f4..44e8e5f5 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -2018,6 +2018,15 @@ "contactsSettings_overwriteOldestTitle": "Prepísať najstaršie", "discoveredContacts_addContact": "Pridať kontakt", "contactsSettings_overwriteOldestSubtitle": "Keď je zoznam kontaktov plný, bude nahradený najstarší neoznačený kontakt.", + "contactsSettings_evictDiscoveredContactsTitle": "Odstraňovať objavené kontakty", + "contactsSettings_evictDiscoveredContactsSubtitle": "Keď je táto možnosť zapnutá, aplikácia odstráni najstaršie objavené kontakty, keď zoznam objavených dosiahne limit {limit} záznamov.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "discoveredContacts_deleteContactAll": "Zmazať všetky objavené kontakty", "common_deleteAll": "Zmazať všetko", "discoveredContacts_deleteContactAllContent": "Ste si istí, že chcete zmazať všetky objavené kontakty?", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 6a00cb3a..18742424 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -2018,6 +2018,8 @@ "discoveredContacts_searchHint": "Najdeni stiki po iskanju", "discoveredContacts_deleteContact": "Izbriši stik", "contactsSettings_overwriteOldestSubtitle": "Ko je seznam stikov poln, bo najstarejši nestarševski stik zamenjan.", + "contactsSettings_evictDiscoveredContactsTitle": "Odstrani odkrite stike", + "contactsSettings_evictDiscoveredContactsSubtitle": "Ko je ta možnost vklopljena, aplikacija odstrani najstarejše odkrite stike, ko seznam odkritih stikov doseže omejitev {limit} vnosov.", "common_deleteAll": "Izbriši vse", "discoveredContacts_deleteContactAllContent": "Ste prepričani, da želite izbrisati vse odkrite kontakte?", "discoveredContacts_deleteContactAll": "Izbriši vse odkrite kontakte", @@ -2876,6 +2878,13 @@ } }, "messageStatus_hopsNotReached": "Poslano, a nazaj slišano le skozi {hops} od {required} ponoviteljev. Morda je odšlo še dlje, kot vaše radio sliši.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "@messageStatus_hopsNotReached": { "placeholders": { "hops": { diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index fa05c8e5..b599089e 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -2019,6 +2019,8 @@ "discoveredContacts_addContact": "Lägg till kontakt", "discoveredContacts_copyContact": "Kopiera kontakt till urklipp", "contactsSettings_overwriteOldestSubtitle": "När kontaktlistan är full ersätts den äldsta icke-favoriterade kontakten.", + "contactsSettings_evictDiscoveredContactsTitle": "Rensa upptäckta kontakter", + "contactsSettings_evictDiscoveredContactsSubtitle": "När detta är aktiverat tar appen bort de äldsta upptäckta kontakterna när listan över upptäckta kontakter når sin gräns på {limit} poster.", "common_deleteAll": "Ta bort alla", "discoveredContacts_deleteContactAllContent": "Är du säker på att du vill ta bort alla upptäckta kontakter?", "discoveredContacts_deleteContactAll": "Ta bort alla upptäckta kontakter", @@ -2876,6 +2878,13 @@ } }, "messageStatus_hopsNotReached": "Skickat, men endast hört tillbaka via {hops} av {required} repeatrar. Det kan ha kommit längre än din radio kan höra.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "@messageStatus_hopsNotReached": { "placeholders": { "hops": { diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index cbb51485..8cfa9de2 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -2028,6 +2028,8 @@ "discoveredContacts_copyContact": "Копіювати контакт у буфер обміну", "discoveredContacts_addContact": "Додати контакт", "contactsSettings_overwriteOldestSubtitle": "Коли список контактів заповнений, найстарший контакт без позначки улюбленого буде замінений.", + "contactsSettings_evictDiscoveredContactsTitle": "Видаляти виявлені контакти", + "contactsSettings_evictDiscoveredContactsSubtitle": "Якщо ввімкнено, застосунок видаляє найстаріші виявлені контакти, коли список виявлених контактів досягає ліміту в {limit} записів.", "common_deleteAll": "Видалити все", "discoveredContacts_deleteContactAll": "Видалити всі виявлені контакти", "discoveredContacts_deleteContactAllContent": "Ви впевнені, що хочете видалити всі виявлені контакти?", @@ -2855,6 +2857,13 @@ } }, "messageStatus_hopsNotReached": "Надіслано, але у відповідь почуто лише через {hops} з {required} ретрансляторів. Можливо, воно дійшло далі, ніж може почути ваше радіо.", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "@messageStatus_hopsNotReached": { "placeholders": { "hops": { diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index b80fed10..56680eea 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2023,6 +2023,8 @@ "discoveredContacts_Title": "已发现的联系人", "discoveredContacts_copyContact": "复制联系人到剪贴板", "contactsSettings_overwriteOldestSubtitle": "当联系人列表已满时,将替换最老的非收藏联系人。", + "contactsSettings_evictDiscoveredContactsTitle": "清除已发现的联系人", + "contactsSettings_evictDiscoveredContactsSubtitle": "启用后,当已发现联系人列表达到 {limit} 条的上限时,应用会移除最旧的已发现联系人。", "common_deleteAll": "删除全部", "discoveredContacts_deleteContactAllContent": "您确定要删除所有发现的联系人吗?", "discoveredContacts_deleteContactAll": "删除所有发现的联系人", @@ -2880,6 +2882,13 @@ } }, "messageStatus_hopsNotReached": "已发送,但只有 {hops} 个中继器(共 {required} 个)回传。它可能已经到达你的无线电收不到的范围之外。", + "@contactsSettings_evictDiscoveredContactsSubtitle": { + "placeholders": { + "limit": { + "type": "int" + } + } + }, "@messageStatus_hopsNotReached": { "placeholders": { "hops": { From 9c66e20b6c9c0ad4672187efb9cc7ecde4d1f1cb Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 21:19:12 -0700 Subject: [PATCH 15/28] Bump build number to 9.5.0+18 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index f1065222..c27d3827 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 9.5.0+17 +version: 9.5.0+18 environment: sdk: ^3.9.2 From a64a33d0c08ff549ffe526d923fdf3dfd0e7d9dc Mon Sep 17 00:00:00 2001 From: zjs81 Date: Wed, 7 Oct 2026 21:26:32 -0700 Subject: [PATCH 16/28] Add release notes for build 18 --- metadata/en-US/changelogs/18.txt | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 metadata/en-US/changelogs/18.txt diff --git a/metadata/en-US/changelogs/18.txt b/metadata/en-US/changelogs/18.txt new file mode 100644 index 00000000..de6974ad --- /dev/null +++ b/metadata/en-US/changelogs/18.txt @@ -0,0 +1,9 @@ +- Android Auto: hear and reply to messages in your car +- Reply, mark as read or mute a channel from notifications +- Import contacts from a QR code; show and copy a node's full public key +- Image previews for links, enabled per contact or channel +- MeshCore One emoji reactions +- Regions shown on received messages, with replies sent to the same region +- More reliable Bluetooth, USB and reconnect handling +- Edge-to-edge layout on Android 10 and newer +- New radio presets and updated translations From 6cb8e07173b72a5dd8ee8b7106712e523c74fb7d Mon Sep 17 00:00:00 2001 From: ericz Date: Thu, 8 Oct 2026 21:33:42 +0200 Subject: [PATCH 17/28] add share location to InputBar popup. --- lib/l10n/app_de.arb | 1 + lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 ++ lib/l10n/app_localizations_bg.dart | 4 + lib/l10n/app_localizations_de.dart | 4 + lib/l10n/app_localizations_en.dart | 4 + lib/l10n/app_localizations_es.dart | 4 + lib/l10n/app_localizations_fr.dart | 4 + lib/l10n/app_localizations_hu.dart | 4 + lib/l10n/app_localizations_it.dart | 4 + lib/l10n/app_localizations_ja.dart | 4 + lib/l10n/app_localizations_ko.dart | 4 + lib/l10n/app_localizations_nl.dart | 4 + lib/l10n/app_localizations_pl.dart | 4 + lib/l10n/app_localizations_pt.dart | 4 + lib/l10n/app_localizations_ru.dart | 4 + lib/l10n/app_localizations_sk.dart | 4 + lib/l10n/app_localizations_sl.dart | 4 + lib/l10n/app_localizations_sv.dart | 4 + lib/l10n/app_localizations_uk.dart | 4 + lib/l10n/app_localizations_zh.dart | 4 + lib/screens/channel_chat_screen.dart | 123 ++++++++++++++++++++++- lib/screens/chat_screen.dart | 142 ++++++++++++++++++++++++++- lib/screens/map_screen.dart | 136 +++++++++++++++++++------ untranslated.json | 66 ++++++++++++- 25 files changed, 511 insertions(+), 36 deletions(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index ff4527fc..ebd598dd 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -711,6 +711,7 @@ "map_shareMarkerHere": "Marker hier teilen", "map_pinLabel": "Pin-Beschriftung", "map_label": "Beschriftung", + "map_labelUpdateHint": "Wenn Sie denselben Namen verwenden wie zuvor, wird die Markierung bei MeshCore Open-Empfängern aktualisiert.", "map_pointOfInterest": "Punkt von Interesse", "map_sendToContact": "An Kontakt senden", "map_sendToChannel": "An Kanal senden", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 06ae5d01..144f0dbc 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1145,6 +1145,7 @@ "map_setAsMyLocation": "Set as my location", "map_pinLabel": "Pin label", "map_label": "Label", + "map_labelUpdateHint": "Using the same label as before will update the marker for MeshCore Open recipients.", "map_pointOfInterest": "Point of interest", "map_sendToContact": "Send to contact", "map_sendToChannel": "Send to channel", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index a1ccd08c..64f132e5 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3916,6 +3916,12 @@ abstract class AppLocalizations { /// **'Label'** String get map_label; + /// No description provided for @map_labelUpdateHint. + /// + /// In en, this message translates to: + /// **'Using the same label as before will update the marker for MeshCore Open recipients.'** + String get map_labelUpdateHint; + /// No description provided for @map_pointOfInterest. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 8ddb847a..8df652af 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -2190,6 +2190,10 @@ class AppLocalizationsBg extends AppLocalizations { @override String get map_label => 'Етикет'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Точка на интерес'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 1fd2b632..9d8a363a 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2187,6 +2187,10 @@ class AppLocalizationsDe extends AppLocalizations { @override String get map_label => 'Beschriftung'; + @override + String get map_labelUpdateHint => + 'Wenn Sie denselben Namen verwenden wie zuvor, wird die Markierung bei MeshCore Open-Empfängern aktualisiert.'; + @override String get map_pointOfInterest => 'Punkt von Interesse'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 4af5d2f0..8f139446 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2154,6 +2154,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get map_label => 'Label'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Point of interest'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 58e63f45..5238e9b5 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2182,6 +2182,10 @@ class AppLocalizationsEs extends AppLocalizations { @override String get map_label => 'Etiqueta'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Punto de interés'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index aa6a2822..e9eeaea5 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2190,6 +2190,10 @@ class AppLocalizationsFr extends AppLocalizations { @override String get map_label => 'Étiquette'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Point d\'intérêt'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 49d60c26..d4e2b92a 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -2179,6 +2179,10 @@ class AppLocalizationsHu extends AppLocalizations { @override String get map_label => 'Címke'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Érdekes pont'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 7079893e..8695d351 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2188,6 +2188,10 @@ class AppLocalizationsIt extends AppLocalizations { @override String get map_label => 'Etichetta'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Punto di interesse'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 1a2b875e..8c982d52 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2091,6 +2091,10 @@ class AppLocalizationsJa extends AppLocalizations { @override String get map_label => 'ラベル'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => '興味地点'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 0842f889..04dc3b1f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2097,6 +2097,10 @@ class AppLocalizationsKo extends AppLocalizations { @override String get map_label => '레이블'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => '관심 지점'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 92f2d27d..3391ab38 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -2173,6 +2173,10 @@ class AppLocalizationsNl extends AppLocalizations { @override String get map_label => 'Label'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Interessepunt'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index b5e95fc6..948cb829 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -2205,6 +2205,10 @@ class AppLocalizationsPl extends AppLocalizations { @override String get map_label => 'Etykieta'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Punkt zainteresowań'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index c0cb6931..7b931b7e 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2186,6 +2186,10 @@ class AppLocalizationsPt extends AppLocalizations { @override String get map_label => 'Rótulo'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Ponto de interesse'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index f7ff950c..bba694bb 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2191,6 +2191,10 @@ class AppLocalizationsRu extends AppLocalizations { @override String get map_label => 'Подпись'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Точка интереса'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 9490e022..7077203d 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -2178,6 +2178,10 @@ class AppLocalizationsSk extends AppLocalizations { @override String get map_label => 'Značka'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Bod záujmu'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 52c311b5..8b8a370a 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -2172,6 +2172,10 @@ class AppLocalizationsSl extends AppLocalizations { @override String get map_label => 'Oznaka'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Točka zanimivosti'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 84fcfeb9..54ed4112 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -2162,6 +2162,10 @@ class AppLocalizationsSv extends AppLocalizations { @override String get map_label => 'Etikett'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Plats av intresse'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index f8c56dec..1c5097ae 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -2181,6 +2181,10 @@ class AppLocalizationsUk extends AppLocalizations { @override String get map_label => 'Мітка'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => 'Точка інтересу'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 9276c9cc..d69e9382 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2065,6 +2065,10 @@ class AppLocalizationsZh extends AppLocalizations { @override String get map_label => '标签'; + @override + String get map_labelUpdateHint => + 'Using the same label as before will update the marker for MeshCore Open recipients.'; + @override String get map_pointOfInterest => '兴趣点'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index c3de648e..df85ec2b 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -38,6 +38,7 @@ import '../widgets/received_image_message.dart'; import '../widgets/byte_count_input.dart'; import '../widgets/chat_day_separator.dart'; import '../widgets/empty_state.dart'; + import '../widgets/chat_zoom_wrapper.dart'; import '../widgets/emoji_picker.dart'; import '../widgets/gif_message.dart'; @@ -2011,6 +2012,79 @@ class _ChannelChatScreenState extends State { } Widget _buildInputBar() { + Future promptForMarkerLabel( + BuildContext context, { + required double lat, + required double lon, + required String defaultLabel, + required String flags, + }) async { + final controller = TextEditingController(text: defaultLabel); + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, + ); + final focusNode = FocusNode(); + + final latStr = lat.toStringAsFixed(6); + final lonStr = lon.toStringAsFixed(6); + final prefix = 'm:$latStr,$lonStr|'; + final suffix = '|$flags'; + final overheadBytes = utf8.encode(prefix + suffix).length; + final maxForContact = maxContactMessageBytes(); + final maxForChannel = maxChannelMessageBytes(null); + final maxPayload = maxForContact < maxForChannel + ? maxForContact + : maxForChannel; + final allowedLabelBytes = (maxPayload - overheadBytes) > 0 + ? (maxPayload - overheadBytes) + : 0; + + try { + final result = await showDialog( + context: context, + builder: (dialogContext) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (dialogContext.mounted) { + focusNode.requestFocus(); + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, + ); + } + }); + return AlertDialog( + title: Text(dialogContext.l10n.map_pinLabel), + content: ByteCountedTextField( + focusNode: focusNode, + maxBytes: allowedLabelBytes, + controller: controller, + decoration: InputDecoration( + helperText: dialogContext.l10n.map_labelUpdateHint, + helperMaxLines: 3, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, null), + child: Text(dialogContext.l10n.common_cancel), + ), + FilledButton( + onPressed: () => + Navigator.pop(dialogContext, controller.text.trim()), + child: Text(dialogContext.l10n.common_share), + ), + ], + ); + }, + ); + return result; + } finally { + focusNode.dispose(); + controller.dispose(); + } + } + final connector = context.watch(); final maxBytes = maxChannelMessageBytes(connector.selfName); final settings = context.watch().settings; @@ -2044,9 +2118,9 @@ class _ChannelChatScreenState extends State { PopupMenuButton( icon: const Icon(Icons.add_circle_outline), position: PopupMenuPosition.over, - offset: Offset(0, showImageAction ? -112 : -64), + offset: Offset(0, showImageAction ? -220 : -160), tooltip: context.l10n.chat_selectSendAction, - onSelected: (action) { + onSelected: (action) async { switch (action) { case 'gif': _showGifPicker(context); @@ -2054,6 +2128,39 @@ class _ChannelChatScreenState extends State { case 'meshcore-image': _showImageSendPreview(); break; + case 'send-my-location': + final connector = context.read(); + if (connector.selfLatitude == null || + connector.selfLongitude == null) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.map_connectToShareMarkers, + ), + ); + break; + } + final lat = connector.selfLatitude!; + final lon = connector.selfLongitude!; + final initialLabel = + connector.selfName?.isNotEmpty == true + ? connector.selfName! + : context.l10n.map_sharedPin; + final label = await promptForMarkerLabel( + context, + lat: lat, + lon: lon, + defaultLabel: initialLabel, + flags: 'poi', + ); + if (label == null || label.trim().isEmpty) break; + final markerText = + 'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|${label.trim()}|poi'; + connector.sendChannelMessage( + widget.channel, + markerText, + ); + break; } }, itemBuilder: (context) => [ @@ -2078,6 +2185,18 @@ class _ChannelChatScreenState extends State { ], ), ), + if (connector.selfLatitude != null && + connector.selfLongitude != null) + PopupMenuItem( + value: 'send-my-location', + child: Row( + children: [ + const Icon(Icons.my_location), + const SizedBox(width: 12), + Text(context.l10n.map_shareMarkerHere), + ], + ), + ), ], ), if (settings.translationEnabled) diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 05c4e4e7..e5f28687 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -472,6 +472,79 @@ class _ChatScreenState extends State { } Widget _buildInputBar(MeshCoreConnector connector) { + Future promptForMarkerLabel( + BuildContext context, { + required double lat, + required double lon, + required String defaultLabel, + required String flags, + }) async { + final controller = TextEditingController(text: defaultLabel); + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, + ); + final focusNode = FocusNode(); + + final latStr = lat.toStringAsFixed(6); + final lonStr = lon.toStringAsFixed(6); + final prefix = 'm:$latStr,$lonStr|'; + final suffix = '|$flags'; + final overheadBytes = utf8.encode(prefix + suffix).length; + final maxForContact = maxContactMessageBytes(); + final maxForChannel = maxChannelMessageBytes(null); + final maxPayload = maxForContact < maxForChannel + ? maxForContact + : maxForChannel; + final allowedLabelBytes = (maxPayload - overheadBytes) > 0 + ? (maxPayload - overheadBytes) + : 0; + + try { + final result = await showDialog( + context: context, + builder: (dialogContext) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (dialogContext.mounted) { + focusNode.requestFocus(); + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, + ); + } + }); + return AlertDialog( + title: Text(dialogContext.l10n.map_pinLabel), + content: ByteCountedTextField( + focusNode: focusNode, + maxBytes: allowedLabelBytes, + controller: controller, + decoration: InputDecoration( + helperText: dialogContext.l10n.map_labelUpdateHint, + helperMaxLines: 3, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, null), + child: Text(dialogContext.l10n.common_cancel), + ), + FilledButton( + onPressed: () => + Navigator.pop(dialogContext, controller.text.trim()), + child: Text(dialogContext.l10n.common_share), + ), + ], + ); + }, + ); + return result; + } finally { + focusNode.dispose(); + controller.dispose(); + } + } + final maxBytes = maxContactMessageBytes(); final scheme = Theme.of(context).colorScheme; final settings = context.watch().settings; @@ -486,10 +559,71 @@ class _ChatScreenState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ - IconButton( - icon: const Icon(Icons.gif_box_outlined), - tooltip: context.l10n.chat_sendGif, - onPressed: () => _showGifPicker(context), + PopupMenuButton( + icon: const Icon(Icons.add_circle_outline), + position: PopupMenuPosition.over, + offset: const Offset(0, -160), + tooltip: context.l10n.chat_selectSendAction, + onSelected: (action) async { + switch (action) { + case 'gif': + _showGifPicker(context); + break; + case 'send-my-location': + final connector = context.read(); + if (connector.selfLatitude == null || + connector.selfLongitude == null) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.map_connectToShareMarkers), + ); + break; + } + final lat = connector.selfLatitude!; + final lon = connector.selfLongitude!; + final initialLabel = + connector.selfName?.isNotEmpty == true + ? connector.selfName! + : context.l10n.map_sharedPin; + final label = await promptForMarkerLabel( + context, + lat: lat, + lon: lon, + defaultLabel: initialLabel, + flags: 'poi', + ); + if (label == null || label.trim().isEmpty) break; + final markerText = + 'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|${label.trim()}|poi'; + connector.sendMessage( + _resolveContact(connector), + markerText, + ); + break; + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'gif', + child: Row( + children: [ + const Icon(Icons.gif_box), + const SizedBox(width: 12), + Text(context.l10n.chat_sendGif), + ], + ), + ), + PopupMenuItem( + value: 'send-my-location', + child: Row( + children: [ + const Icon(Icons.my_location), + const SizedBox(width: 12), + Text(context.l10n.map_shareMarkerHere), + ], + ), + ), + ], ), if (settings.translationEnabled) MessageTranslationButton( diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index aec3ba9e..ff4f381a 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:math'; +import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -36,6 +37,7 @@ import 'chat_screen.dart'; import 'contacts_screen.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/byte_count_input.dart'; import '../widgets/repeater_login_dialog.dart'; import '../widgets/room_login_dialog.dart'; import '../helpers/guessed_location_estimator.dart'; @@ -3119,7 +3121,11 @@ class _MapScreenState extends State with DisconnectNavigationMixin { return; } - final label = await _promptForLabel(context, defaultLabel); + final initialLabel = + connector.selfName == null || connector.selfName!.isEmpty + ? defaultLabel + : connector.selfName!; + final label = await _promptForLabel(context, position, initialLabel, flags); if (label == null || !mounted) return; final markerText = _formatMarkerMessage(position, label, flags); @@ -3135,42 +3141,114 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Future _promptForLabel( BuildContext context, + LatLng position, String defaultLabel, + String flags, ) async { final controller = TextEditingController(text: defaultLabel); controller.selection = TextSelection( baseOffset: 0, extentOffset: controller.text.length, ); - return showDialog( - context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.map_pinLabel), - content: TextField( - controller: controller, - decoration: InputDecoration( - hintText: context.l10n.map_label, - border: const OutlineInputBorder(), - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () { - final label = controller.text.trim().replaceAll('|', '/'); - Navigator.pop( - dialogContext, - label.isEmpty ? defaultLabel : label, + final focusNode = FocusNode(); + // Compute available bytes for the label taking marker overhead into + // account. Use a conservative limit based on both contact and channel + // message maxima. + final lat = position.latitude.toStringAsFixed(6); + final lon = position.longitude.toStringAsFixed(6); + final prefix = 'm:$lat,$lon|'; + final suffix = '|$flags'; + final overheadBytes = utf8.encode(prefix + suffix).length; + final maxForContact = maxContactMessageBytes(); + final maxForChannel = maxChannelMessageBytes(null); + final maxPayload = maxForContact < maxForChannel + ? maxForContact + : maxForChannel; + final allowedLabelBytes = (maxPayload - overheadBytes) > 0 + ? (maxPayload - overheadBytes) + : 0; + + try { + final result = await showDialog( + context: context, + builder: (dialogContext) { + final scheme = Theme.of(dialogContext).colorScheme; + // Request focus and ensure selection after the frame so the + // keyboard appears and text is selected for replacement. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (dialogContext.mounted) { + focusNode.requestFocus(); + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, ); - }, - child: Text(context.l10n.common_continue), - ), - ], - ), - ); + } + }); + return AlertDialog( + title: Text(dialogContext.l10n.map_pinLabel), + content: ByteCountedTextField( + focusNode: focusNode, + maxBytes: allowedLabelBytes, + controller: controller, + decoration: InputDecoration( + hintText: dialogContext.l10n.map_label, + helperText: dialogContext.l10n.map_labelUpdateHint, + helperMaxLines: 3, + helperStyle: TextStyle( + color: _overlaySecondaryTextColor, + fontSize: 12, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + borderSide: BorderSide(color: scheme.outlineVariant), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + borderSide: BorderSide(color: scheme.outlineVariant), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + borderSide: BorderSide(color: scheme.primary, width: 1.5), + ), + filled: true, + fillColor: scheme.surfaceContainerLow, + contentPadding: const EdgeInsets.symmetric( + horizontal: 18, + vertical: 12, + ), + ), + onSubmitted: (_) { + final label = controller.text.trim().replaceAll('|', '/'); + Navigator.pop( + dialogContext, + label.isEmpty ? defaultLabel : label, + ); + }, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(dialogContext.l10n.common_cancel), + ), + TextButton( + onPressed: () { + final label = controller.text.trim().replaceAll('|', '/'); + Navigator.pop( + dialogContext, + label.isEmpty ? defaultLabel : label, + ); + }, + child: Text(dialogContext.l10n.common_continue), + ), + ], + ); + }, + ); + return result; + } finally { + focusNode.dispose(); + controller.dispose(); + } } String _formatMarkerMessage(LatLng position, String label, String flags) { diff --git a/untranslated.json b/untranslated.json index 9e26dfee..beb95225 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,65 @@ -{} \ No newline at end of file +{ + "bg": [ + "map_labelUpdateHint" + ], + + "es": [ + "map_labelUpdateHint" + ], + + "fr": [ + "map_labelUpdateHint" + ], + + "hu": [ + "map_labelUpdateHint" + ], + + "it": [ + "map_labelUpdateHint" + ], + + "ja": [ + "map_labelUpdateHint" + ], + + "ko": [ + "map_labelUpdateHint" + ], + + "nl": [ + "map_labelUpdateHint" + ], + + "pl": [ + "map_labelUpdateHint" + ], + + "pt": [ + "map_labelUpdateHint" + ], + + "ru": [ + "map_labelUpdateHint" + ], + + "sk": [ + "map_labelUpdateHint" + ], + + "sl": [ + "map_labelUpdateHint" + ], + + "sv": [ + "map_labelUpdateHint" + ], + + "uk": [ + "map_labelUpdateHint" + ], + + "zh": [ + "map_labelUpdateHint" + ] +} From 3cc0f48c731e15a349fa203864912927fa32c074 Mon Sep 17 00:00:00 2001 From: ericz Date: Thu, 8 Oct 2026 22:06:44 +0200 Subject: [PATCH 18/28] reworked popup for correct placement. --- lib/screens/channel_chat_screen.dart | 200 ++++++++++++++++----------- lib/screens/chat_screen.dart | 161 ++++++++++++--------- 2 files changed, 221 insertions(+), 140 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index df85ec2b..a3a8cf99 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -2115,89 +2115,135 @@ class _ChannelChatScreenState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ - PopupMenuButton( - icon: const Icon(Icons.add_circle_outline), - position: PopupMenuPosition.over, - offset: Offset(0, showImageAction ? -220 : -160), - tooltip: context.l10n.chat_selectSendAction, - onSelected: (action) async { - switch (action) { - case 'gif': - _showGifPicker(context); - break; - case 'meshcore-image': - _showImageSendPreview(); - break; - case 'send-my-location': - final connector = context.read(); - if (connector.selfLatitude == null || - connector.selfLongitude == null) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.map_connectToShareMarkers, + Builder( + builder: (menuContext) { + return IconButton( + icon: const Icon(Icons.add_circle_outline), + tooltip: context.l10n.chat_selectSendAction, + onPressed: () async { + final RenderBox button = + menuContext.findRenderObject() as RenderBox; + final RenderBox overlay = + Overlay.of(menuContext).context.findRenderObject() + as RenderBox; + final Offset buttonOffset = button.localToGlobal( + Offset.zero, + ancestor: overlay, + ); + final items = >[ + PopupMenuItem( + value: 'gif', + child: Row( + children: [ + const Icon(Icons.gif_box), + const SizedBox(width: 12), + Text(context.l10n.chat_sendGif), + ], + ), + ), + ]; + if (showImageAction) { + items.add( + PopupMenuItem( + value: 'meshcore-image', + child: Row( + children: [ + const Icon(Icons.image_outlined), + const SizedBox(width: 12), + Text(context.l10n.chat_sendImageLora), + ], + ), ), ); - break; } - final lat = connector.selfLatitude!; - final lon = connector.selfLongitude!; - final initialLabel = - connector.selfName?.isNotEmpty == true - ? connector.selfName! - : context.l10n.map_sharedPin; - final label = await promptForMarkerLabel( - context, - lat: lat, - lon: lon, - defaultLabel: initialLabel, - flags: 'poi', + if (context.read().selfLatitude != + null && + context.read().selfLongitude != + null) { + items.add( + PopupMenuItem( + value: 'send-my-location', + child: Row( + children: [ + const Icon(Icons.my_location), + const SizedBox(width: 12), + Text(context.l10n.map_shareMarkerHere), + ], + ), + ), + ); + } + + final menuHeight = + items.length * kMinInteractiveDimension + 16; + final menuTop = (buttonOffset.dy - menuHeight).clamp( + 8.0, + overlay.size.height, ); - if (label == null || label.trim().isEmpty) break; - final markerText = - 'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|${label.trim()}|poi'; - connector.sendChannelMessage( - widget.channel, - markerText, + final position = RelativeRect.fromLTRB( + buttonOffset.dx, + menuTop, + overlay.size.width - + buttonOffset.dx - + button.size.width, + overlay.size.height - buttonOffset.dy, ); - break; - } + + final selected = await showMenu( + context: menuContext, + position: position, + items: items, + ); + if (!mounted || !menuContext.mounted) return; + if (selected == null) return; + switch (selected) { + case 'gif': + _showGifPicker(context); + break; + case 'meshcore-image': + _showImageSendPreview(); + break; + case 'send-my-location': + final connector = context + .read(); + if (connector.selfLatitude == null || + connector.selfLongitude == null) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.map_connectToShareMarkers, + ), + ); + break; + } + final lat = connector.selfLatitude!; + final lon = connector.selfLongitude!; + final initialLabel = + connector.selfName?.isNotEmpty == true + ? connector.selfName! + : context.l10n.map_sharedPin; + final label = await promptForMarkerLabel( + context, + lat: lat, + lon: lon, + defaultLabel: initialLabel, + flags: 'poi', + ); + if (label == null || label.trim().isEmpty) break; + if (!mounted || !menuContext.mounted) break; + final connector2 = context + .read(); + final markerText = + 'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|${label.trim()}|poi'; + connector2.sendChannelMessage( + widget.channel, + markerText, + ); + break; + } + }, + ); }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'gif', - child: Row( - children: [ - const Icon(Icons.gif_box), - const SizedBox(width: 12), - Text(context.l10n.chat_sendGif), - ], - ), - ), - if (showImageAction) - PopupMenuItem( - value: 'meshcore-image', - child: Row( - children: [ - const Icon(Icons.image_outlined), - const SizedBox(width: 12), - Text(context.l10n.chat_sendImageLora), - ], - ), - ), - if (connector.selfLatitude != null && - connector.selfLongitude != null) - PopupMenuItem( - value: 'send-my-location', - child: Row( - children: [ - const Icon(Icons.my_location), - const SizedBox(width: 12), - Text(context.l10n.map_shareMarkerHere), - ], - ), - ), - ], ), if (settings.translationEnabled) MessageTranslationButton( diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e5f28687..4db6db3d 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -559,71 +559,106 @@ class _ChatScreenState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ - PopupMenuButton( - icon: const Icon(Icons.add_circle_outline), - position: PopupMenuPosition.over, - offset: const Offset(0, -160), - tooltip: context.l10n.chat_selectSendAction, - onSelected: (action) async { - switch (action) { - case 'gif': - _showGifPicker(context); - break; - case 'send-my-location': - final connector = context.read(); - if (connector.selfLatitude == null || - connector.selfLongitude == null) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.map_connectToShareMarkers), - ); - break; + Builder( + builder: (menuContext) { + return IconButton( + icon: const Icon(Icons.add_circle_outline), + tooltip: context.l10n.chat_selectSendAction, + onPressed: () async { + final RenderBox button = + menuContext.findRenderObject() as RenderBox; + final RenderBox overlay = + Overlay.of(menuContext).context.findRenderObject() + as RenderBox; + final Offset buttonOffset = button.localToGlobal( + Offset.zero, + ancestor: overlay, + ); + const menuHeight = 2 * kMinInteractiveDimension + 16; + final menuTop = (buttonOffset.dy - menuHeight).clamp( + 8.0, + overlay.size.height, + ); + final position = RelativeRect.fromLTRB( + buttonOffset.dx, + menuTop, + overlay.size.width - + buttonOffset.dx - + button.size.width, + overlay.size.height - buttonOffset.dy, + ); + + final selected = await showMenu( + context: menuContext, + position: position, + items: [ + PopupMenuItem( + value: 'gif', + child: Row( + children: [ + const Icon(Icons.gif_box), + const SizedBox(width: 12), + Text(context.l10n.chat_sendGif), + ], + ), + ), + PopupMenuItem( + value: 'send-my-location', + child: Row( + children: [ + const Icon(Icons.my_location), + const SizedBox(width: 12), + Text(context.l10n.map_shareMarkerHere), + ], + ), + ), + ], + ); + if (!mounted || !menuContext.mounted) return; + if (selected == null) return; + switch (selected) { + case 'gif': + _showGifPicker(context); + break; + case 'send-my-location': + final connector = context.read(); + if (connector.selfLatitude == null || + connector.selfLongitude == null) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.map_connectToShareMarkers, + ), + ); + break; + } + final lat = connector.selfLatitude!; + final lon = connector.selfLongitude!; + final initialLabel = + connector.selfName?.isNotEmpty == true + ? connector.selfName! + : context.l10n.map_sharedPin; + final label = await promptForMarkerLabel( + context, + lat: lat, + lon: lon, + defaultLabel: initialLabel, + flags: 'poi', + ); + if (label == null || label.trim().isEmpty) break; + if (!mounted || !menuContext.mounted) break; + final connector2 = context.read(); + final markerText = + 'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|${label.trim()}|poi'; + connector2.sendMessage( + _resolveContact(connector2), + markerText, + ); + break; } - final lat = connector.selfLatitude!; - final lon = connector.selfLongitude!; - final initialLabel = - connector.selfName?.isNotEmpty == true - ? connector.selfName! - : context.l10n.map_sharedPin; - final label = await promptForMarkerLabel( - context, - lat: lat, - lon: lon, - defaultLabel: initialLabel, - flags: 'poi', - ); - if (label == null || label.trim().isEmpty) break; - final markerText = - 'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|${label.trim()}|poi'; - connector.sendMessage( - _resolveContact(connector), - markerText, - ); - break; - } + }, + ); }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'gif', - child: Row( - children: [ - const Icon(Icons.gif_box), - const SizedBox(width: 12), - Text(context.l10n.chat_sendGif), - ], - ), - ), - PopupMenuItem( - value: 'send-my-location', - child: Row( - children: [ - const Icon(Icons.my_location), - const SizedBox(width: 12), - Text(context.l10n.map_shareMarkerHere), - ], - ), - ), - ], ), if (settings.translationEnabled) MessageTranslationButton( From 25f197c979ce6b476a32ff08565b724d2103fb28 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 01:25:31 -0700 Subject: [PATCH 19/28] Fix review findings, add default flood scope, and address recent issues Review fixes: - Keep stored message history beyond the 200-message window; stop messages leaking between radios; reset link/session state on disconnect - Accept firmware's 176-byte RX frames over USB/TCP - Hold APP_START during contact sync; contact-sync watchdog; replay DMs from not-yet-known senders; tombstone late command replies; finish channel sync on ERR_NOT_FOUND; fail region-scoped sends cleanly - DM retry watchdog when RESP_CODE_SENT never arrives; late repeater CLI replies; ACK hash collisions; UTF-8-safe name truncation - Image pipeline: delete-during-decode, lifecycle cancels, decoder memory release, entry cap, dead worker recovery, atomic model writes - Storage: deterministic reaction hash across web/native, Smaz double-decode, per-entry parsing, per-radio path history and regions, review-mode data isolation - UI: safe channel slot selection, byte-length name limits, double-send guard, mounted checks, localized hardcoded strings - Skip persisted-store reload on repeat SELF_INFO Features: - Radio default flood scope (firmware ver 11+) and explicit unscoped sends (ver 12+) - Scan for nearby nodes (#570) - Optional distinct first-hop repeater counting for channel resend (#589) - Optional region next to hop count (#580) Issues: - Message text follows system font size (#569) - Repeater/room password field accepts 20 chars (#576) - TCP auto-reconnect and keepalive (#571) - Order feeds by local receive time; flag future timestamps (#584) - Coding rate help text (#568), French "Favoris" (#575) - iOS/macOS app badge now clears Translations for all new strings in every locale. --- documentation/ble-protocol.md | 7 +- documentation/regions.md | 32 +- ios/Runner/AppDelegate.swift | 21 + lib/connector/meshcore_connector.dart | 831 +++++++++++++++--- lib/connector/meshcore_protocol.dart | 165 +++- lib/connector/pending_command_replies.dart | 49 +- lib/helpers/channel_resend_coverage.dart | 53 ++ lib/helpers/cyr2lat.dart | 4 +- lib/helpers/link_handler.dart | 16 + lib/helpers/reaction_helper.dart | 25 +- lib/helpers/smaz.dart | 24 +- lib/helpers/utf8_length_limiter.dart | 30 + lib/l10n/app_bg.arb | 56 +- lib/l10n/app_de.arb | 56 +- lib/l10n/app_en.arb | 108 ++- lib/l10n/app_es.arb | 56 +- lib/l10n/app_fr.arb | 58 +- lib/l10n/app_hu.arb | 56 +- lib/l10n/app_it.arb | 56 +- lib/l10n/app_ja.arb | 56 +- lib/l10n/app_ko.arb | 56 +- lib/l10n/app_localizations.dart | 314 ++++++- lib/l10n/app_localizations_bg.dart | 207 ++++- lib/l10n/app_localizations_de.dart | 206 ++++- lib/l10n/app_localizations_en.dart | 204 ++++- lib/l10n/app_localizations_es.dart | 207 ++++- lib/l10n/app_localizations_fr.dart | 209 ++++- lib/l10n/app_localizations_hu.dart | 206 ++++- lib/l10n/app_localizations_it.dart | 207 ++++- lib/l10n/app_localizations_ja.dart | 199 ++++- lib/l10n/app_localizations_ko.dart | 199 ++++- lib/l10n/app_localizations_nl.dart | 206 ++++- lib/l10n/app_localizations_pl.dart | 210 ++++- lib/l10n/app_localizations_pt.dart | 207 ++++- lib/l10n/app_localizations_ru.dart | 210 ++++- lib/l10n/app_localizations_sk.dart | 210 ++++- lib/l10n/app_localizations_sl.dart | 209 ++++- lib/l10n/app_localizations_sv.dart | 205 ++++- lib/l10n/app_localizations_uk.dart | 210 ++++- lib/l10n/app_localizations_zh.dart | 196 ++++- lib/l10n/app_nl.arb | 56 +- lib/l10n/app_pl.arb | 56 +- lib/l10n/app_pt.arb | 56 +- lib/l10n/app_ru.arb | 56 +- lib/l10n/app_sk.arb | 56 +- lib/l10n/app_sl.arb | 56 +- lib/l10n/app_sv.arb | 56 +- lib/l10n/app_uk.arb | 56 +- lib/l10n/app_zh.arb | 56 +- lib/main.dart | 14 +- lib/models/app_settings.dart | 17 + lib/models/channel_message.dart | 15 + lib/models/message.dart | 31 + lib/review_mode/review_mode_storage.dart | 33 +- lib/review_mode/review_radio.dart | 71 +- lib/screens/app_settings_screen.dart | 35 +- lib/screens/channel_chat_screen.dart | 152 +++- lib/screens/channels_screen.dart | 151 +++- lib/screens/chat_screen.dart | 30 +- lib/screens/community_qr_scanner_screen.dart | 30 +- lib/screens/discovery_screen.dart | 7 + lib/screens/line_of_sight_map_screen.dart | 63 +- lib/screens/map_cache_screen.dart | 1 + lib/screens/map_screen.dart | 65 +- lib/screens/path_trace_map.dart | 9 +- lib/screens/region_management_screen.dart | 97 +- lib/screens/repeater_cli_screen.dart | 25 +- lib/screens/repeater_settings_screen.dart | 65 +- lib/screens/scanner_screen.dart | 5 +- lib/screens/settings_screen.dart | 111 +-- lib/services/app_settings_service.dart | 10 + lib/services/image_chunk_transport.dart | 13 +- lib/services/image_codec_backend.dart | 6 + lib/services/image_codec_file_store_io.dart | 29 +- lib/services/image_codec_service.dart | 30 +- lib/services/image_codec_session_io.dart | 26 +- lib/services/image_codec_session_stub.dart | 2 + lib/services/message_retry_service.dart | 159 +++- lib/services/notification_service.dart | 36 +- .../received_image_blob_store_io.dart | 12 +- lib/services/received_image_store.dart | 250 ++++-- lib/services/repeater_command_service.dart | 146 ++- lib/services/storage_service.dart | 47 +- .../tcp_transport_service_native.dart | 80 ++ lib/services/timeout_prediction_service.dart | 5 + lib/services/usb_serial_frame_codec.dart | 6 +- lib/services/usb_serial_service_web.dart | 14 +- lib/storage/channel_message_store.dart | 160 +++- lib/storage/channel_region_store.dart | 23 +- lib/storage/channel_store.dart | 18 +- lib/storage/contact_discovery_store.dart | 3 +- lib/storage/message_store.dart | 154 +++- lib/storage/region_store.dart | 21 +- lib/storage/unread_store.dart | 16 +- lib/widgets/future_timestamp_indicator.dart | 26 + lib/widgets/gif_message.dart | 6 +- lib/widgets/node_scan_sheet.dart | 310 +++++++ lib/widgets/qr_scanner_widget.dart | 12 +- lib/widgets/received_image_message.dart | 15 +- lib/widgets/repeater_login_dialog.dart | 3 +- lib/widgets/room_login_dialog.dart | 3 +- macos/Runner/MainFlutterWindow.swift | 14 + test/connector/default_flood_scope_test.dart | 238 +++++ .../meshcore_protocol_strings_test.dart | 69 ++ test/connector/node_discover_test.dart | 206 +++++ .../pending_command_replies_test.dart | 48 + test/connector/tcp_auto_reconnect_test.dart | 210 +++++ .../helpers/channel_resend_coverage_test.dart | 142 +++ test/helpers/utf8_length_limiter_test.dart | 25 + test/models/received_at_test.dart | 217 +++++ test/models/region_on_hops_line_test.dart | 21 + test/reaction_helper_test.dart | 35 + .../services/message_retry_watchdog_test.dart | 95 ++ test/services/received_image_store_test.dart | 150 ++++ .../repeater_command_service_test.dart | 81 ++ .../tcp_transport_service_native_test.dart | 59 ++ .../services/usb_serial_frame_codec_test.dart | 31 +- test/storage/message_store_archive_test.dart | 223 +++++ test/storage/scoped_store_fixes_test.dart | 184 ++++ .../translated_message_content_test.dart | 55 ++ 120 files changed, 10424 insertions(+), 687 deletions(-) create mode 100644 lib/helpers/channel_resend_coverage.dart create mode 100644 lib/widgets/future_timestamp_indicator.dart create mode 100644 lib/widgets/node_scan_sheet.dart create mode 100644 test/connector/default_flood_scope_test.dart create mode 100644 test/connector/meshcore_protocol_strings_test.dart create mode 100644 test/connector/node_discover_test.dart create mode 100644 test/connector/tcp_auto_reconnect_test.dart create mode 100644 test/helpers/channel_resend_coverage_test.dart create mode 100644 test/models/received_at_test.dart create mode 100644 test/models/region_on_hops_line_test.dart create mode 100644 test/services/message_retry_watchdog_test.dart create mode 100644 test/storage/message_store_archive_test.dart create mode 100644 test/storage/scoped_store_fixes_test.dart create mode 100644 test/widgets/translated_message_content_test.dart diff --git a/documentation/ble-protocol.md b/documentation/ble-protocol.md index a8a67bf3..8bd742ad 100644 --- a/documentation/ble-protocol.md +++ b/documentation/ble-protocol.md @@ -112,7 +112,7 @@ On unexpected disconnection, auto-reconnect with exponential backoff: | 40 | CMD_GET_CUSTOM_VAR | Get custom variables | | 41 | CMD_SET_CUSTOM_VAR | Set a custom variable | | 50 | CMD_SEND_BINARY_REQ | Send binary request | -| 54 | CMD_SET_FLOOD_SCOPE_KEY | Set flood routing scope (v8+; `cmdSetFloodScope` in the app) | +| 54 | CMD_SET_FLOOD_SCOPE_KEY | Set flood routing scope (v8+; `cmdSetFloodScope` in the app). `[54,0,key16]` sets, `[54,0]` clears the override (radio default scope then applies), `[54,1]` sends unscoped (firmware code 12+) | | 55 | CMD_SEND_CONTROL_DATA | Send control data (e.g. zero-hop discovery, v8+) | | 56 | CMD_GET_STATS | Request companion radio stats | | 57 | CMD_SEND_ANON_REQ | Send anonymous request | @@ -120,6 +120,8 @@ On unexpected disconnection, auto-reconnect with exponential backoff: | 59 | CMD_GET_AUTO_ADD_CONFIG | Get auto-add configuration | | 61 | CMD_SET_PATH_HASH_MODE | Set path hash width (bytes per hop) | | 62 | CMD_SEND_CHANNEL_DATA | Send GRP_DATA image chunks (firmware code 11+) | +| 63 | CMD_SET_DEFAULT_FLOOD_SCOPE | Store the radio's default flood scope: `[63][name 31, NUL padded][key 16]`, or `[63]` to clear (firmware code 11+) | +| 64 | CMD_GET_DEFAULT_FLOOD_SCOPE | Read the radio's default flood scope (firmware code 11+) | ## Response / Push Codes (Device → App) @@ -146,6 +148,7 @@ On unexpected disconnection, auto-reconnect with exponential backoff: | 24 | RESP_CODE_STATS | Companion radio stats | | 25 | RESP_CODE_AUTO_ADD_CONFIG | Auto-add flags | | 27 | RESP_CODE_CHANNEL_DATA_RECV | Received GRP_DATA image chunk | +| 28 | RESP_CODE_DEFAULT_FLOOD_SCOPE | `[28][name 31][key 16]`, or `[28]` alone when no default is set | | 0x80 | PUSH_CODE_ADVERT | Known contact re-seen | | 0x81 | PUSH_CODE_PATH_UPDATED | Better path found; carries the 32-byte public key of the updated contact | | 0x82 | PUSH_CODE_SEND_CONFIRMED | Delivery ACK from remote; carries ACK hash (4 bytes) + trip time (4 bytes) | @@ -272,6 +275,6 @@ Reactions use `r::`. Channel replies ## Regions and image data -Transport-routed raw packets include four transport-code bytes before packed path metadata. For transport floods, the app matches the first two code bytes against locally known region candidates using HMAC-SHA256 over `[payloadType][payload]`. Region scope keys are the first 16 bytes of SHA256 of `#`. The name itself is not carried as plain text. Unknown or ambiguous matches remain null; see [regions](regions.md). +Transport-routed raw packets include four transport-code bytes before packed path metadata. For transport floods, the app matches the first two code bytes against locally known region candidates using HMAC-SHA256 over `[payloadType][payload]`. Region scope keys are the first 16 bytes of SHA256 of `#`. The radio's default flood scope is also a candidate, matched on the key the radio reports (it may have been set by another client). The name itself is not carried as plain text. Unknown or ambiguous matches remain null; see [regions](regions.md). Image chunks use `CMD_SEND_CHANNEL_DATA` (62), `RESP_CODE_CHANNEL_DATA_RECV` (27), and application data type `0xAE1C`. The framing, capacities, metadata byte, and XOR recovery algorithm are defined in [image_chunk_transport.dart](../lib/services/image_chunk_transport.dart), which is the source of truth. See [image messages](image-messages.md) for user requirements and limitations. diff --git a/documentation/regions.md b/documentation/regions.md index e6651fb2..e2a83d1a 100644 --- a/documentation/regions.md +++ b/documentation/regions.md @@ -7,12 +7,32 @@ Regions limit which configured repeaters forward a channel flood. They are routi 1. While connected, open Settings → Regions. 2. Add a region name manually, or choose Fetch from repeaters and add names from the results. Discovery queries nearby responding repeaters already present in your contacts; an empty result does not prove that no regions exist on the wider mesh. 3. Manual names accept lowercase letters, digits, and hyphens, up to 30 characters. Use the exact name configured by your local repeater operators. -4. Choose a Default region to use for channels without their own override. None means the app sets no default scope. -5. In channel chat, tap the title or landscape icon to select an override. The subtitle shows the effective region, with `(default)` when inherited. +4. Choose a Default region to use for channels without their own override. None means the app sets no default scope (the radio default region, if any, applies). +5. In channel chat, tap the title or landscape icon to select an override. The subtitle shows the effective region, with `(default)` when inherited from the app default or `(radio default)` when the radio's own default applies. -Tapping the selected region again, or choosing Clear region, removes the channel override. **If a default exists, clearing an override falls back to that default; it does not force an unscoped send.** With no override and the default set to None, the app sets no scope: the companion's scope override stays cleared (`[54, 0]`). Since companion firmware v1.15.0, the radio then falls back to its own default flood scope if one is configured on the device. The app does not issue an explicitly unscoped send. +Tapping the selected region again, or choosing Clear region, removes the channel override. **If a default exists, clearing an override falls back to that default; it does not force an unscoped send.** To send a channel truly unscoped, pick **No region (unscoped)** instead (see below). -The saved region-name list is global to the app. Default and channel assignments are stored per connected radio identity. Removing a region from the list also clears matching assignments stored for the current radio; it does not change repeater configuration. +## Radio default region + +Companion firmware v1.15.0 (firmware code 11) and later can store a default flood scope on the radio itself. The radio uses it for every flood sent without a scope override, by this app or any other app connected to the radio. + +- On supported firmware, Settings → Regions shows **Radio default region**. Choosing a region writes it to the radio (`CMD_SET_DEFAULT_FLOOD_SCOPE`, 63); choosing None clears it. The app reads it back after connecting and after each change (`CMD_GET_DEFAULT_FLOOD_SCOPE`, 64 → `RESP_CODE_DEFAULT_FLOOD_SCOPE`, 28). The key written is derived the same way as for app regions. +- On older firmware the setting is hidden and these commands are never sent. + +## Precedence and "No region" + +The scope used for a channel flood is decided in this order: + +1. **The channel's own assignment**: a region, or **No region (unscoped)**. +2. **The app default region**: a region, None, or **No region (unscoped)**. +3. **The radio default region**, when the app sets no scope (channel cleared and app default None). +4. Otherwise the flood is unscoped. + +**No region (unscoped)** is offered only on firmware code 12 and later (companion v1.16.0+), where the app can override the radio default with `[54, 1]` around the send. On firmware code 11 the option is hidden: floods without a region use the radio default, and the channel region picker says so when a radio default is set. On firmware without a radio default, None and No region behave the same. + +Replying with a message's original region (below) is a one-off override at step 1. + +The saved region-name list is global to the app. Default and channel assignments are stored per connected radio identity. Removing a region from the list also clears matching assignments stored for every radio; it does not change repeater configuration or the radio default region stored on a radio. ## Regions displayed on messages @@ -20,7 +40,7 @@ Channel text messages show a region label beside routing metadata when a region Outgoing messages retain the effective region used when they were sent. Changing a channel or default region does not relabel earlier messages. Region metadata persists with message history; older records may have no region. -Incoming region names are inferred from raw **transport-flood** packets by testing locally known names (saved regions, channel overrides, and the default). The name is not sent as plain text in the packet. Unknown names, ambiguous matches, and messages without suitable raw transport metadata do not get a region label. `foo` and `#foo` are treated as the same candidate for matching. +Incoming region names are inferred from raw **transport-flood** packets by testing locally known names (saved regions, channel overrides, the app default, and the radio default region). The name is not sent as plain text in the packet. Unknown names, ambiguous matches, and messages without suitable raw transport metadata do not get a region label. `foo` and `#foo` are treated as the same candidate for matching. **No label does not prove a message was unscoped.** It can mean that its region could not be identified. A region label is routing metadata, not proof of the sender’s location or identity. @@ -34,6 +54,6 @@ If the original message has no known region, the reply uses the channel’s effe ## Technical reference -Scoped sends temporarily set the companion’s flood scope, send the message, and then clear the scope override (`buildSetFloodScopeFrame('')`); they do not restore a previously set scope. Channel sends are serialized to prevent another channel from inheriting the temporary setting. Repeaters and companion firmware must support the relevant scope functionality. +Scoped sends temporarily set the companion’s flood scope (`[54, 0, key]`, or `[54, 1]` for No region on firmware code 12+), send the message, and then clear the scope override (`buildSetFloodScopeFrame('')`, `[54, 0]`); they do not restore a previously set scope. Channels with no scope to apply send without any scope command, so the radio default region applies. Channel sends are serialized to prevent another channel from inheriting the temporary setting. Repeaters and companion firmware must support the relevant scope functionality. See [channels](channels.md), [routing paths](routing-paths.md), and [protocol metadata](ble-protocol.md#regions-and-image-data). diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index c30b367e..5c38c90f 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -1,5 +1,6 @@ import Flutter import UIKit +import UserNotifications @main @objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { @@ -12,5 +13,25 @@ import UIKit func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "MeshAppBadge") { + let channel = FlutterMethodChannel( + name: "meshcore_open/app_badge", + binaryMessenger: registrar.messenger() + ) + channel.setMethodCallHandler { call, result in + guard call.method == "setBadgeCount" else { + result(FlutterMethodNotImplemented) + return + } + let count = (call.arguments as? Int) ?? 0 + UNUserNotificationCenter.current().setBadgeCount(max(0, count)) { error in + if let error = error { + result(FlutterError(code: "badge", message: error.localizedDescription, details: nil)) + } else { + result(nil) + } + } + } + } } } diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index d5eb2282..d8bbf986 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -17,6 +17,7 @@ import '../models/message.dart'; import '../models/path_selection.dart'; import '../models/translation_support.dart'; import '../helpers/reaction_helper.dart'; +import '../helpers/channel_resend_coverage.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/smaz.dart'; import '../services/app_debug_log_service.dart'; @@ -192,6 +193,9 @@ class MeshCoreConnector extends ChangeNotifier { String? _lastDeviceId; String? _lastDeviceDisplayName; bool _manualDisconnect = false; + // Bumped by every BLE connect attempt so a superseded attempt can tell it + // no longer owns the connector. + int _bleConnectGeneration = 0; /// Non-null while [disconnect] is tearing the transport down. Connect paths /// join it so a teardown cannot finish after a new connection and reset the @@ -226,8 +230,18 @@ class MeshCoreConnector extends ChangeNotifier { staleAfter: _commandAckTimeout * 2, ); static const String _reactionSendQueuePrefix = '__reaction_send__'; + // TXT_TYPE_CLI_COMMAND (firmware TxtDataHelpers.h). + static const int _txtTypeCliCommand = 3; + // ERR_CODE_NOT_FOUND (companion MyMesh.cpp). + static const int _errCodeNotFound = 2; int _reactionSendQueueSequence = 0; final Set _loadedConversationKeys = {}; + // Self public key of the radio whose messages are held in memory. + String? _messageStateOwnerKey; + // Self public key whose persisted stores were loaded this link session. + // Later SELF_INFO replies (refreshDeviceInfo after a settings change) skip + // the reload while it still matches. + String? _persistedStateLoadedKey; final Map> _processedChannelReactions = {}; // channelIndex -> Set of "targetHash_emoji" final Map> _processedContactReactions = @@ -249,6 +263,16 @@ class MeshCoreConnector extends ChangeNotifier { final ValueNotifier radioStatsNotifier = ValueNotifier(null); int _reconnectAttempts = 0; + // Endpoint of the last TCP link that completed its handshake. Set only + // after SELF_INFO, cleared on a manual disconnect or a user-started + // connect, so a failed first attempt never loops on a bad address. + String? _tcpReconnectHost; + int? _tcpReconnectPort; + // True while [connectTcp] runs on behalf of [_scheduleTcpReconnect]. + bool _tcpAutoReconnectAttempt = false; + // Bumped by each [connectTcp] and by every disconnect, so an attempt that + // was superseded mid-handshake cannot record a stale reconnect target. + int _tcpConnectGeneration = 0; bool _notifyListenersDirty = false; static const Duration _notifyListenersDebounce = Duration(milliseconds: 50); @@ -353,6 +377,19 @@ class MeshCoreConnector extends ChangeNotifier { bool _queuedMessageSyncInFlight = false; final List _deferredQueuedContactMessageFrames = []; bool _pendingQueueSync = false; + // CMD_APP_START stops the firmware's contact iterator (END_OF_CONTACTS is + // then never sent), so APP_START requested during a contact sync is held + // until the sync ends. + bool _appStartDeferredForContactSync = false; + // Ends a contact sync whose frames stopped arriving, so queued-message sync + // and deferred processing cannot stay blocked behind it. + Timer? _contactSyncWatchdog; + static const Duration _contactSyncStallTimeout = Duration(seconds: 20); + // Contact messages whose sender was not a known contact yet. The firmware + // already removed them from its offline queue, so they are held and + // replayed once the sender's CONTACT frame arrives (or the sync ends). + final List _unknownSenderMessageFrames = []; + static const int _maxUnknownSenderMessageFrames = 32; Timer? _queueSyncTimeout; int _queueSyncRetries = 0; static const int _maxQueueSyncRetries = 3; @@ -379,6 +416,9 @@ class MeshCoreConnector extends ChangeNotifier { int _nextChannelIndexToRequest = 0; int _totalChannelsToRequest = 0; List _previousChannelsCache = []; + // Slots whose GET_CHANNEL timed out in the last sync with no cached copy: + // their contents are unknown, so UI must not treat them as free. + final Set _unconfirmedChannelSlots = {}; static const int _maxChannelSyncRetries = 3; static const int _channelSyncTimeoutMs = 2000; // 2 second timeout per channel static const Duration _batteryPollInterval = Duration(seconds: 120); @@ -411,8 +451,10 @@ class MeshCoreConnector extends ChangeNotifier { final Map _channelCyr2LatProfileId = {}; final Map _channelRegions = {}; Region _defaultRegion = ''; - bool _lastSentWasCliCommand = - false; // Track if last sent message was a CLI command + // Radio-stored default flood scope (GET_DEFAULT_FLOOD_SCOPE, ver 11+). + // Null when the radio has none or has not reported it yet. + String? _defaultFloodScopeName; + Uint8List? _defaultFloodScopeKey; final Map _contactSmazEnabled = {}; final Map _contactCyr2LatEnabled = {}; final Map _contactUrlImagesEnabled = {}; @@ -458,7 +500,8 @@ class MeshCoreConnector extends ChangeNotifier { _state == MeshCoreConnectionState.connected && _activeTransport == MeshCoreTransportType.usb; bool get isAutoReconnectScheduled => - _shouldAutoReconnect && (_reconnectTimer?.isActive ?? false); + (_shouldAutoReconnect || _shouldAutoReconnectTcp) && + (_reconnectTimer?.isActive ?? false); String? get activeTcpEndpoint => _tcpConnector.activeEndpoint; bool get isTcpTransportConnected => _state == MeshCoreConnectionState.connected && @@ -519,6 +562,8 @@ class MeshCoreConnector extends ChangeNotifier { bool get hasLoadedContacts => _hasLoadedContacts; bool get isLoadingChannels => _isLoadingChannels; bool get hasLoadedChannels => _hasLoadedChannels; + Set get unconfirmedChannelSlots => + Set.unmodifiable(_unconfirmedChannelSlots); Stream get receivedFrames => _receivedFramesController.stream; Uint8List? get selfPublicKey => _selfPublicKey; String get selfPublicKeyHex => pubKeyToHex(_selfPublicKey ?? Uint8List(0)); @@ -570,6 +615,21 @@ class MeshCoreConnector extends ChangeNotifier { /// CMD_GET_ALLOWED_REPEAT_FREQ exists from ver code 9 (client repeat). bool get supportsAllowedRepeatFreq => (_firmwareVerCode ?? 0) >= 9; + /// CMD_SEND_CONTROL_DATA / PUSH_CODE_CONTROL_DATA (node discover) exist + /// from ver code 8. + bool get supportsNodeDiscover => (_firmwareVerCode ?? 0) >= 8; + + /// CMD_GET/SET_DEFAULT_FLOOD_SCOPE exist from ver code 11 (v1.15.0). + bool get supportsDefaultFloodScope => (_firmwareVerCode ?? 0) >= 11; + + /// CMD_SET_FLOOD_SCOPE `[54,1]` (send unscoped, overriding the radio's + /// default scope) exists from ver code 12. + bool get supportsExplicitUnscopedFlood => (_firmwareVerCode ?? 0) >= 12; + + /// Name of the radio's default flood scope, or null when none is set. + String? get defaultFloodScopeName => _defaultFloodScopeName; + Uint8List? get defaultFloodScopeKey => _defaultFloodScopeKey; + /// Frequency ranges (kHz, inclusive) on which the firmware accepts client /// repeat mode. Null until RESP_ALLOWED_REPEAT_FREQ has been received. List? get allowedRepeatFreqRanges => @@ -696,6 +756,10 @@ class MeshCoreConnector extends ChangeNotifier { final windowedMessages = allMessages.length > _messageWindowSize ? allMessages.sublist(allMessages.length - _messageWindowSize) : allMessages; + final archivedMessages = allMessages.sublist( + 0, + allMessages.length - windowedMessages.length, + ); final currentMessages = _conversations[contactKeyHex] ?? const []; @@ -723,13 +787,22 @@ class MeshCoreConnector extends ChangeNotifier { // Re-sort after merging persisted and in-memory messages so the // conversation window remains stable after optimistic inserts. - mergedMessages.sort((a, b) => a.timestamp.compareTo(b.timestamp)); - final windowedMergedMessages = mergedMessages.length > _messageWindowSize - ? mergedMessages.sublist(mergedMessages.length - _messageWindowSize) - : mergedMessages; + mergedMessages.sort((a, b) => a.receivedAt.compareTo(b.receivedAt)); + final trimCount = mergedMessages.length > _messageWindowSize + ? mergedMessages.length - _messageWindowSize + : 0; + final windowedMergedMessages = mergedMessages.sublist(trimCount); + // Everything stored ahead of the window stays in storage on the next + // save instead of being overwritten by the window. + _messageStore.setArchived(contactKeyHex, [ + ...archivedMessages, + ...mergedMessages.sublist(0, trimCount), + ]); _conversations[contactKeyHex] = windowedMergedMessages; notifyListeners(); + } else { + _messageStore.setArchived(contactKeyHex, const []); } } @@ -749,15 +822,20 @@ class MeshCoreConnector extends ChangeNotifier { final allMessages = await _messageStore.loadMessages(contactKeyHex); final currentMessages = _conversations[contactKeyHex] ?? []; - if (allMessages.length <= currentMessages.length) { + // Storage holds the archived entries followed by the in-memory window. + final currentOffset = + (_messageStore.archivedCount(contactKeyHex) ?? + allMessages.length - currentMessages.length) + .clamp(0, allMessages.length); + if (currentOffset == 0) { return []; // No more messages to load } - final currentOffset = allMessages.length - currentMessages.length; final fetchCount = count.clamp(0, currentOffset); final startIndex = currentOffset - fetchCount; final olderMessages = allMessages.sublist(startIndex, currentOffset); + _messageStore.unarchiveNewest(contactKeyHex, olderMessages.length); // Prepend to current conversation _conversations[contactKeyHex] = [...olderMessages, ...currentMessages]; @@ -858,19 +936,68 @@ class MeshCoreConnector extends ChangeNotifier { return _contactUrlImagesEnabled[contactKeyHex] ?? false; } + /// True when the channel has its own (real) region assigned. bool hasChannelRegion(int channelIndex) { - return (_channelRegions[channelIndex] ?? '').isNotEmpty; + return getChannelRegion(channelIndex).isNotEmpty; } + /// The channel's own region, or '' when it follows the default or is set + /// to "no region" (see [isChannelExplicitlyUnscoped]). Region getChannelRegion(int channelIndex) { - return _channelRegions[channelIndex] ?? ''; + final region = _channelRegions[channelIndex] ?? ''; + return region == kUnscopedRegion ? '' : region; } + /// True when the user picked "no region" for this channel, overriding the + /// app and radio defaults. + bool isChannelExplicitlyUnscoped(int channelIndex) { + return _channelRegions[channelIndex] == kUnscopedRegion; + } + + /// The app default region ('' for none). [kUnscopedRegion] when the app + /// default is "no region". Region get defaultRegion => _defaultRegion; + /// The region a flood on this channel is scoped to by the app, as a real + /// region name, or '' when the app sends without a region (in which case + /// the radio's default flood scope, if any, may still apply — see + /// [channelUsesRadioDefaultScope]). Region getEffectiveChannelRegion(int channelIndex) { - final region = getChannelRegion(channelIndex); - return region.isNotEmpty ? region : _defaultRegion; + final scope = _channelSendScope(channelIndex); + return scope == kUnscopedRegion ? '' : scope; + } + + /// True when floods on this channel fall through to the radio's default + /// flood scope: no app region applies and the radio has a default that + /// this firmware cannot (or was not asked to) override. + bool channelUsesRadioDefaultScope(int channelIndex) { + if (_defaultFloodScopeName == null) return false; + final scope = _channelSendScope(channelIndex); + if (scope.isEmpty) return true; + return scope == kUnscopedRegion && !supportsExplicitUnscopedFlood; + } + + /// Precedence: channel assignment (region or "no region"), then the app + /// default (region or "no region"), then '' (the radio default applies). + Region _channelSendScope(int channelIndex) { + final own = _channelRegions[channelIndex] ?? ''; + if (own.isNotEmpty) return own; + return _defaultRegion; + } + + /// Stores [region] on the radio as its default flood scope ('' clears it), + /// then re-reads it. Throws on firmware without the command, on ERR or on + /// timeout. + Future setDefaultFloodScope(String region) async { + if (!isConnected) return; + if (!supportsDefaultFloodScope) { + throw UnsupportedError('Firmware does not support default flood scope'); + } + await sendFrame( + buildSetDefaultFloodScopeFrame(region), + waitForGenericAck: true, + ); + await sendFrame(buildGetDefaultFloodScopeFrame()); } Future setDefaultRegion(Region region) async { @@ -904,6 +1031,14 @@ class MeshCoreConnector extends ChangeNotifier { _unreadStateLoaded = true; _recalculateCachedUnreadTotals(); notifyListeners(); + syncAppBadge(); + } + + /// Sets the app icon badge to the current unread total, e.g. on resume, so + /// a badge left by delivered notifications doesn't outlive the unreads. + void syncAppBadge() { + if (!_unreadStateLoaded) return; + unawaited(_notificationService.setAppBadge(getTotalUnreadCount())); } Future loadCachedChannels() async { @@ -1200,15 +1335,19 @@ class MeshCoreConnector extends ChangeNotifier { final allMessages = await _channelMessageStore.loadChannelMessages( channelIndex, ); - if (allMessages.isNotEmpty) { - // Keep only the most recent N messages in memory to bound memory usage - final windowedMessages = allMessages.length > _messageWindowSize - ? allMessages.sublist(allMessages.length - _messageWindowSize) - : allMessages; - - _channelMessages[channelIndex] = windowedMessages; - notifyListeners(); - } + // Keep only the most recent N messages in memory to bound memory usage + final windowedMessages = allMessages.length > _messageWindowSize + ? allMessages.sublist(allMessages.length - _messageWindowSize) + : allMessages; + _channelMessageStore.setArchived( + channelIndex, + allMessages.sublist(0, allMessages.length - windowedMessages.length), + ); + // Replace even when nothing is stored so another radio's messages never + // linger under this index. + final hadMessages = _channelMessages[channelIndex]?.isNotEmpty ?? false; + _channelMessages[channelIndex] = windowedMessages; + if (hadMessages || windowedMessages.isNotEmpty) notifyListeners(); } /// Load older channel messages (pagination) @@ -1221,15 +1360,20 @@ class MeshCoreConnector extends ChangeNotifier { ); final currentMessages = _channelMessages[channelIndex] ?? []; - if (allMessages.length <= currentMessages.length) { + // Storage holds the archived entries followed by the in-memory window. + final currentOffset = + (_channelMessageStore.archivedCount(channelIndex) ?? + allMessages.length - currentMessages.length) + .clamp(0, allMessages.length); + if (currentOffset == 0) { return []; // No more messages to load } - final currentOffset = allMessages.length - currentMessages.length; final fetchCount = count.clamp(0, currentOffset); final startIndex = currentOffset - fetchCount; final olderMessages = allMessages.sublist(startIndex, currentOffset); + _channelMessageStore.unarchiveNewest(channelIndex, olderMessages.length); // Prepend to current conversation _channelMessages[channelIndex] = [...olderMessages, ...currentMessages]; @@ -2010,6 +2154,7 @@ class MeshCoreConnector extends ChangeNotifier { await stopScan(); _cancelReconnectTimer(); + _clearTcpReconnectTarget(); _manualDisconnect = false; _resetConnectionHandshakeState(); _activeTransport = MeshCoreTransportType.usb; @@ -2120,9 +2265,16 @@ class MeshCoreConnector extends ChangeNotifier { await stopScan(); _cancelReconnectTimer(); + if (!_tcpAutoReconnectAttempt) { + // A user-started connect replaces any earlier endpoint; it becomes the + // reconnect target only once its handshake completes. + _clearTcpReconnectTarget(); + _reconnectAttempts = 0; + } _manualDisconnect = false; _resetConnectionHandshakeState(); _activeTransport = MeshCoreTransportType.tcp; + final tcpGeneration = ++_tcpConnectGeneration; _setState(MeshCoreConnectionState.connecting); try { @@ -2201,6 +2353,17 @@ class MeshCoreConnector extends ChangeNotifier { if (!gotSelfInfo) { throw StateError('Timed out waiting for SELF_INFO during TCP connect'); } + if (tcpGeneration != _tcpConnectGeneration) { + _appDebugLogService?.info( + 'connectTcp superseded after SELF_INFO; leaving the connector to ' + 'the newer attempt', + tag: 'TCP', + ); + return; + } + _tcpReconnectHost = host; + _tcpReconnectPort = port; + _reconnectAttempts = 0; await syncTime(); } catch (error) { @@ -2250,6 +2413,7 @@ class MeshCoreConnector extends ChangeNotifier { await stopScan(); _cancelReconnectTimer(); + _clearTcpReconnectTarget(); _manualDisconnect = false; _resetConnectionHandshakeState(); _activeTransport = MeshCoreTransportType.review; @@ -2397,6 +2561,7 @@ class MeshCoreConnector extends ChangeNotifier { await stopScan(); _setState(MeshCoreConnectionState.connecting); + final connectGeneration = ++_bleConnectGeneration; _device = device; _deviceId = device.remoteId.toString(); if (displayName != null && displayName.trim().isNotEmpty) { @@ -2409,6 +2574,7 @@ class MeshCoreConnector extends ChangeNotifier { _lastDeviceDisplayName = _deviceDisplayName; _manualDisconnect = false; _cancelReconnectTimer(); + _clearTcpReconnectTarget(); _bleInitialSyncStarted = false; if (PlatformInfo.isWeb) { _resetConnectionHandshakeState(); @@ -2757,6 +2923,18 @@ class MeshCoreConnector extends ChangeNotifier { _reconnectAttempts = 0; } } catch (e) { + // The user cancelled (manual disconnect) or a newer connect took over + // while this attempt was in flight. Tearing down again here would + // re-arm auto-reconnect or kill the newer connection. + if (connectGeneration != _bleConnectGeneration || + _manualDisconnect || + !identical(_device, device)) { + _appDebugLogService?.info( + 'Ignoring error from cancelled connect attempt: $e', + tag: 'BLE Connect', + ); + rethrow; + } _appDebugLogService?.error('Connection error: $e', tag: 'BLE Connect'); final errorText = e.toString(); final lowerErrorText = errorText.toLowerCase(); @@ -3068,6 +3246,7 @@ class MeshCoreConnector extends ChangeNotifier { _queuedMessageSyncInFlight = false; _deferredQueuedContactMessageFrames.clear(); _pendingQueueSync = false; + _resetSyncFlowState(); _queueSyncTimeout?.cancel(); _queueSyncTimeout = null; _queueSyncRetries = 0; @@ -3079,6 +3258,7 @@ class MeshCoreConnector extends ChangeNotifier { _nextChannelIndexToRequest = 0; _totalChannelsToRequest = 0; _previousChannelsCache.clear(); + _unconfirmedChannelSlots.clear(); } bool get _shouldAutoReconnect => @@ -3087,6 +3267,20 @@ class MeshCoreConnector extends ChangeNotifier { _lastDeviceId != null && _activeTransport == MeshCoreTransportType.bluetooth; + /// TCP links drop when Android parks Wi-Fi in the background (#571), so a + /// non-manual TCP disconnect reconnects to the last handshaked endpoint. + /// USB is left alone: losing it almost always means the cable was pulled. + bool get _shouldAutoReconnectTcp => + !_disposed && + !_manualDisconnect && + _tcpReconnectHost != null && + _tcpReconnectPort != null; + + void _clearTcpReconnectTarget() { + _tcpReconnectHost = null; + _tcpReconnectPort = null; + } + bool get _shouldGateInitialChannelSync => _activeTransport == MeshCoreTransportType.usb || _activeTransport == MeshCoreTransportType.tcp || @@ -3133,6 +3327,37 @@ class MeshCoreConnector extends ChangeNotifier { }); } + void _scheduleTcpReconnect() { + if (!_shouldAutoReconnectTcp) return; + if (_reconnectTimer?.isActive == true) return; + + final delayMs = _nextReconnectDelayMs(); + _appDebugLogService?.info( + 'TCP reconnect to $_tcpReconnectHost:$_tcpReconnectPort in ${delayMs}ms ' + '(attempt $_reconnectAttempts)', + tag: 'TCP', + ); + _reconnectTimer = Timer(Duration(milliseconds: delayMs), () async { + if (!_shouldAutoReconnectTcp) return; + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + return; + } + final host = _tcpReconnectHost!; + final port = _tcpReconnectPort!; + _tcpAutoReconnectAttempt = true; + try { + await connectTcp(host: host, port: port); + } catch (_) { + // A failed attempt tears down through disconnect(manual: false), + // which already rescheduled; this only covers early failures. + _scheduleTcpReconnect(); + } finally { + _tcpAutoReconnectAttempt = false; + } + }); + } + Future disconnect({ bool manual = true, bool skipBleDeviceDisconnect = false, @@ -3145,6 +3370,7 @@ class MeshCoreConnector extends ChangeNotifier { // schedules an auto-reconnect the user did not ask for. _manualDisconnect = true; _cancelReconnectTimer(); + _clearTcpReconnectTarget(); unawaited(_backgroundService?.stop()); } return inFlight; @@ -3198,11 +3424,17 @@ class MeshCoreConnector extends ChangeNotifier { _manualDisconnect = true; _cancelReconnectTimer(); _reconnectAttempts = 0; + _clearTcpReconnectTarget(); unawaited(_backgroundService?.stop()); } else { _manualDisconnect = false; - // Only BLE reconnects on its own; nothing keeps TCP/USB alive. - if (transportAtDisconnect != MeshCoreTransportType.bluetooth) { + // BLE and handshaked TCP links reconnect on their own and keep the + // foreground service; nothing keeps USB alive. + final tcpWillReconnect = + transportAtDisconnect == MeshCoreTransportType.tcp && + _shouldAutoReconnectTcp; + if (transportAtDisconnect != MeshCoreTransportType.bluetooth && + !tcpWillReconnect) { unawaited(_backgroundService?.stop()); } } @@ -3217,6 +3449,7 @@ class MeshCoreConnector extends ChangeNotifier { await _tcpConnector.disconnect(); final wasReviewMode = transportAtDisconnect == MeshCoreTransportType.review; _reviewConnectGeneration++; + _tcpConnectGeneration++; await _reviewFrameSubscription?.cancel(); _reviewFrameSubscription = null; _reviewRadio?.dispose(); @@ -3271,9 +3504,8 @@ class MeshCoreConnector extends ChangeNotifier { _deviceId = null; _contacts.clear(); _discoveredContacts.clear(); - _conversations.clear(); - _loadedConversationKeys.clear(); - _selfPublicKey = null; + _clearSessionMessageState(); + _resetLinkSessionState(); _selfName = null; _selfLatitude = null; _selfLongitude = null; @@ -3285,17 +3517,7 @@ class MeshCoreConnector extends ChangeNotifier { _allowedRepeatFreqRanges = null; _autoAddMaxHops = null; _contactsStorageFull = false; - _batteryMillivolts = null; _repeaterBatterySnapshots.clear(); - _batteryRequested = false; - _awaitingSelfInfo = false; - _hasReceivedDeviceInfo = false; - _maxContacts = _defaultMaxContacts; - _maxChannels = _defaultMaxChannels; - _resetSyncProgressState(); - _pendingChannelSentQueue.clear(); - _pendingGenericAckQueue.clear(); - _reactionSendQueueSequence = 0; _activeTransport = MeshCoreTransportType.bluetooth; if (wasReviewMode) { @@ -3313,6 +3535,9 @@ class MeshCoreConnector extends ChangeNotifier { if (!manual && transportAtDisconnect == MeshCoreTransportType.bluetooth) { _scheduleReconnect(); } + if (!manual && transportAtDisconnect == MeshCoreTransportType.tcp) { + _scheduleTcpReconnect(); + } } Future sendFrame( @@ -3375,7 +3600,9 @@ class MeshCoreConnector extends ChangeNotifier { try { await pendingAck!.completer!.future.timeout(const Duration(seconds: 5)); } on TimeoutException { - _pendingGenericAckQueue.remove(pendingAck!); + // Keep a tombstone: the firmware still answers this command later, + // and that reply must not be credited to the next pending command. + _pendingGenericAckQueue.markTimedOut(pendingAck!); throw TimeoutException( 'Timed out waiting for firmware acknowledgement', ); @@ -3422,7 +3649,10 @@ class MeshCoreConnector extends ChangeNotifier { _gpsLocationPollTimer = null; return; } - unawaited(sendFrame(buildAppStartFrame()).catchError(_logTimerSendError)); + // Skipped mid contact sync: APP_START would abort the firmware's + // contact iteration. The next tick polls again. + if (_isLoadingContacts) return; + unawaited(_sendAppStart().catchError(_logTimerSendError)); }); } @@ -3560,7 +3790,7 @@ class MeshCoreConnector extends ChangeNotifier { _webInitialHandshakeRequestSent = true; } await sendFrame(buildDeviceQueryFrame()); - await sendFrame(buildAppStartFrame()); + await _sendAppStart(); await requestBatteryStatus(force: true); await sendFrame(buildGetCustomVarsFrame()); _deviceConfigRequested = false; @@ -3584,7 +3814,7 @@ class MeshCoreConnector extends ChangeNotifier { _webInitialHandshakeRequestSent = true; } await sendFrame(buildDeviceQueryFrame()); - await sendFrame(buildAppStartFrame()); + await _sendAppStart(); await sendFrame(buildGetCustomVarsFrame()); await requestBatteryStatus(); _deviceConfigRequested = false; @@ -3614,6 +3844,23 @@ class MeshCoreConnector extends ChangeNotifier { ).catchError(_logTimerSendError), ); } + if (supportsDefaultFloodScope) { + unawaited( + sendFrame( + buildGetDefaultFloodScopeFrame(), + ).catchError(_logTimerSendError), + ); + } + } + + /// Sends CMD_APP_START unless a contact sync is running, in which case it is + /// sent when the sync ends (see [_continueAfterContactSync]). + Future _sendAppStart() async { + if (_isLoadingContacts) { + _appStartDeferredForContactSync = true; + return; + } + await sendFrame(buildAppStartFrame()); } void _scheduleSelfInfoRetry() { @@ -3633,9 +3880,7 @@ class MeshCoreConnector extends ChangeNotifier { return; } attempts += 1; - unawaited( - sendFrame(buildAppStartFrame()).catchError(_logTimerSendError), - ); + unawaited(_sendAppStart().catchError(_logTimerSendError)); if (attempts >= maxAttempts) { timer.cancel(); } @@ -3653,7 +3898,7 @@ class MeshCoreConnector extends ChangeNotifier { timer.cancel(); return; } - unawaited(sendFrame(buildAppStartFrame()).catchError(_logTimerSendError)); + unawaited(_sendAppStart().catchError(_logTimerSendError)); }); } @@ -3693,6 +3938,7 @@ class MeshCoreConnector extends ChangeNotifier { _hasLoadedContacts = false; _contacts.clear(); } + _armContactSyncWatchdog(); notifyListeners(); try { @@ -3700,10 +3946,107 @@ class MeshCoreConnector extends ChangeNotifier { } catch (_) { _isLoadingContacts = false; notifyListeners(); + _continueAfterContactSync(); rethrow; } } + void _armContactSyncWatchdog() { + _contactSyncWatchdog?.cancel(); + _contactSyncWatchdog = Timer( + _contactSyncStallTimeout, + _handleContactSyncStalled, + ); + } + + void _handleContactSyncStalled() { + _contactSyncWatchdog = null; + if (!_isLoadingContacts || !isConnected) return; + _appDebugLogService?.warn( + 'Contact sync stalled (no END_OF_CONTACTS); ending it after ' + '$_contactSyncReceived contacts', + tag: 'Connector', + ); + // The partial list is not persisted so the stored contacts survive. + _isLoadingContacts = false; + _preserveContactsOnRefresh = false; + _contactSyncUsesSinceFilter = false; + notifyListeners(); + _continueAfterContactSync(); + } + + /// Runs the work that waits for a contact sync to end, whether it finished + /// with END_OF_CONTACTS, stalled, or failed to start. + void _continueAfterContactSync() { + _contactSyncWatchdog?.cancel(); + _contactSyncWatchdog = null; + if (!isConnected) return; + if (PlatformInfo.isWeb && + _activeTransport == MeshCoreTransportType.bluetooth && + _isSyncingChannels && + !_channelSyncInFlight) { + unawaited(_requestNextChannel()); + } + if (_appStartDeferredForContactSync) { + _appStartDeferredForContactSync = false; + unawaited(_sendAppStart().catchError(_logTimerSendError)); + } + unawaited(_replayUnknownSenderMessages()); + if (_deferQueuedContactMessagesUntilContacts) { + unawaited(_processDeferredQueuedContactMessages()); + } else if (_pendingQueueSync) { + _pendingQueueSync = false; + unawaited(syncQueuedMessages(force: true)); + } + } + + /// Clears the contact-sync follow-up state. Call on connection teardown. + void _resetSyncFlowState() { + _contactSyncWatchdog?.cancel(); + _contactSyncWatchdog = null; + _appStartDeferredForContactSync = false; + _unknownSenderMessageFrames.clear(); + } + + void _holdUnknownSenderMessage(Uint8List frame) { + if (_unknownSenderMessageFrames.length >= _maxUnknownSenderMessageFrames) { + _unknownSenderMessageFrames.removeAt(0); + appLogger.warn( + 'Too many messages from unknown contacts; dropping the oldest', + tag: 'Connector', + ); + } + _unknownSenderMessageFrames.add(Uint8List.fromList(frame)); + } + + /// Replays held unknown-sender messages exactly once. With + /// [onlyResolvable], frames whose sender is still unknown stay held (a + /// single CONTACT frame arrived); otherwise unresolved frames are dropped. + Future _replayUnknownSenderMessages({ + bool onlyResolvable = false, + }) async { + if (_unknownSenderMessageFrames.isEmpty) return; + final ready = []; + _unknownSenderMessageFrames.removeWhere((frame) { + if (onlyResolvable) { + final prefix = _extractSenderPrefix(frame); + if (prefix == null || + !_contacts.any((c) => _matchesPrefix(c.publicKey, prefix))) { + return false; + } + } + ready.add(frame); + return true; + }); + for (final frame in ready) { + await _handleIncomingMessage( + frame, + alreadyAdvancedQueueSync: true, + isUnknownSenderReplay: true, + ); + } + } + Future refreshContacts() async { await getContacts(preserveExisting: true); } @@ -4147,7 +4490,15 @@ class MeshCoreConnector extends ChangeNotifier { ChannelMessage? replyTo, }) async { if (!isConnected || text.isEmpty) return; - final sendRegion = region ?? getEffectiveChannelRegion(channel.index); + final sendScope = region ?? _channelSendScope(channel.index); + // Label only: with no app scope the radio applies its own default + // (and "no region" cannot force unscoped below ver 12). + final radioDefaultApplies = + sendScope.isEmpty || + (sendScope == kUnscopedRegion && !supportsExplicitUnscopedFlood); + final sendRegion = radioDefaultApplies + ? (_defaultFloodScopeName ?? '') + : (sendScope == kUnscopedRegion ? '' : sendScope); // Check if this is a reaction - if so, process it immediately instead of adding as a message final reactionInfo = ReactionHelper.parseReaction(text); @@ -4183,13 +4534,19 @@ class MeshCoreConnector extends ChangeNotifier { // Send the reaction to the device (don't add as a visible message) final reactionQueueId = _nextReactionSendQueueId(); _pendingChannelSentQueue.add(reactionQueueId); - await _runScopedChannelSend(() async { - await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); - await _sendFrameAndWaitForCommandAck( - buildSendChannelTextMsgFrame(channel.index, text), - channelSendQueueId: reactionQueueId, - ); - }, region: getEffectiveChannelRegion(channel.index)); + try { + await _runScopedChannelSend(() async { + await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); + await _sendFrameAndWaitForCommandAck( + buildSendChannelTextMsgFrame(channel.index, text), + channelSendQueueId: reactionQueueId, + ); + }, region: _channelSendScope(channel.index)); + } catch (_) { + // e.g. SET_FLOOD_SCOPE rejected or timed out: nothing was sent. + _pendingChannelSentQueue.remove(reactionQueueId); + rethrow; + } return; } // It looks like a reaction, but we did not find its target, so @@ -4224,8 +4581,17 @@ class MeshCoreConnector extends ChangeNotifier { ), channelSendQueueId: isResend ? null : message.messageId, ); - }, region: sendRegion); - await transmit(); + }, region: sendScope); + try { + await transmit(); + } catch (_) { + // A failed or timed-out SET_FLOOD_SCOPE (or text send) means no OK/ERR + // will resolve this message, so fail it here instead of leaving it + // pending forever. + _pendingChannelSentQueue.remove(message.messageId); + _markPendingChannelMessageFailedById(message.messageId); + rethrow; + } final settings = _appSettingsService?.settings; if (settings != null && settings.channelMinHopsEnabled) { @@ -4262,9 +4628,20 @@ class MeshCoreConnector extends ChangeNotifier { if (message == null) return; if (message.status == ChannelMessageStatus.failed) return; hops = message.pathLength ?? 0; - if (hops >= minHops) { + // Read live so toggling the setting mid-resend takes effect. + final countRepeaters = + _appSettingsService?.settings.channelMinHopsCountRepeaters ?? false; + if (channelResendSatisfied( + message, + minHops: minHops, + countDistinctRepeaters: countRepeaters, + selfPublicKey: _selfPublicKey, + )) { _appDebugLogService?.info( - 'Channel message reached $hops hops after $attempt resends', + hops >= minHops + ? 'Channel message reached $hops hops after $attempt resends' + : 'Channel message heard via ${distinctFirstHopRepeaters(message, selfPublicKey: _selfPublicKey).length} ' + 'first-hop repeaters after $attempt resends', tag: 'Channel resend', ); return; @@ -4388,7 +4765,7 @@ class MeshCoreConnector extends ChangeNotifier { ); onProgress?.call(i + 1, blobs.length); } - }, region: getEffectiveChannelRegion(channelIndex)); + }, region: _channelSendScope(channelIndex)); return sentAll; } @@ -4407,11 +4784,19 @@ class MeshCoreConnector extends ChangeNotifier { // firmware that predates CMD_SET_FLOOD_SCOPE. The lock is still held so an // unscoped send can't interleave with (and inherit the scope of) a // concurrent scoped send. - if (region.isEmpty) { + // "No region" can only override the radio's default scope on ver 12+; + // older firmware sends it like any unscoped channel. + final forceUnscoped = + region == kUnscopedRegion && supportsExplicitUnscopedFlood; + if (region.isEmpty || (region == kUnscopedRegion && !forceUnscoped)) { await action(); return; } - await _sendFrameAndWaitForCommandAck(buildSetFloodScopeFrame(region)); + await _sendFrameAndWaitForCommandAck( + forceUnscoped + ? buildSetFloodScopeUnscopedFrame() + : buildSetFloodScopeFrame(region), + ); try { await action(); } finally { @@ -4463,6 +4848,7 @@ class MeshCoreConnector extends ChangeNotifier { unawaited(_persistContacts()); _conversations.remove(contact.publicKeyHex); _loadedConversationKeys.remove(contact.publicKeyHex); + _messageStore.forgetArchive(contact.publicKeyHex); final removedCount = _contactUnreadCount[contact.publicKeyHex] ?? 0; _cachedContactsUnreadTotal = (_cachedContactsUnreadTotal - removedCount) .clamp(0, _cachedContactsUnreadTotal); @@ -4496,6 +4882,77 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// Broadcasts a zero-hop DISCOVER_REQ and emits each distinct node that + /// answers with our tag until [timeout]. Repeaters reply after a random + /// delay, and firmware rate-limits replies, so the window stays generous. + Stream discoverNearbyNodes({ + int typeMask = nodeDiscoverScanTypeMask, + Duration timeout = const Duration(seconds: 12), + }) { + late final StreamController controller; + StreamSubscription? subscription; + Timer? timer; + final seenKeys = {}; + final tag = math.Random.secure().nextInt(0xFFFFFFFF) + 1; + final selfKeyHex = selfPublicKeyHex; + + Future close() async { + timer?.cancel(); + await subscription?.cancel(); + if (!controller.isClosed) await controller.close(); + } + + controller = StreamController( + onListen: () async { + if (!isConnected || !supportsNodeDiscover) { + await close(); + return; + } + subscription = receivedFrames.listen((frame) { + final response = parseNodeDiscoverResponse(frame); + if (response == null || response.tag != tag) return; + final keyHex = response.publicKeyHex; + if (selfKeyHex.isNotEmpty && selfKeyHex.startsWith(keyHex)) return; + if (!seenKeys.add(keyHex)) return; + if (!controller.isClosed) controller.add(response); + }); + try { + await sendFrame( + buildSendControlDataFrame( + buildDiscoveryRequestPayload(tag, typeMask: typeMask), + ), + ); + } catch (e) { + if (!controller.isClosed) controller.addError(e); + await close(); + return; + } + timer = Timer(timeout, () => unawaited(close())); + }, + onCancel: close, + ); + return controller.stream; + } + + /// The best-known contact for a scan response: an existing contact or a + /// discovered advert with the same key, else a placeholder built from the + /// response (direct neighbour; firmware fills the name on its next advert). + Contact contactForDiscoverResponse(NodeDiscoverResponse response) { + final keyHex = response.publicKeyHex; + for (final contact in [..._contacts, ..._discoveredContacts]) { + if (contact.publicKeyHex.startsWith(keyHex)) return contact; + } + return Contact( + publicKey: response.publicKey, + name: keyHex.substring(0, math.min(8, keyHex.length)).toUpperCase(), + type: response.nodeType, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.now(), + isActive: false, + ); + } + Future importDiscoveredContact(Contact contact) async { if (!isConnected) return false; @@ -4684,14 +5141,6 @@ class MeshCoreConnector extends ChangeNotifier { } } - Future sendCliCommand(String command) async { - if (!isConnected) return; - final selfKey = _selfPublicKey; - if (selfKey == null) return; - _lastSentWasCliCommand = true; - await sendFrame(buildSendCliCommandFrame(selfKey, command)); - } - Future setNodeName(String name) async { if (!isConnected) return; await sendFrame(buildSetAdvertNameFrame(name)); @@ -4737,10 +5186,6 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildRebootFrame()); } - Future setPrivacyMode(bool enabled) async { - await sendCliCommand('set privacy ${enabled ? 'on' : 'off'}'); - } - Future setTelemetryModeBase( int base, int location, @@ -4786,6 +5231,7 @@ class MeshCoreConnector extends ChangeNotifier { _hasLoadedChannels = false; _previousChannelsCache = List.from(_channels); _channels.clear(); + _unconfirmedChannelSlots.clear(); _nextChannelIndexToRequest = 0; _totalChannelsToRequest = maxChannels ?? _maxChannels; _channelSyncRetries = 0; @@ -4866,7 +5312,8 @@ class MeshCoreConnector extends ChangeNotifier { ); } } catch (e) { - // No cached channel found, that's okay + // No cached copy: the slot's contents are unknown, not empty. + _unconfirmedChannelSlots.add(channelIndex); } // Move to next channel @@ -4878,6 +5325,20 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// The firmware answers GET_CHANNEL with ERR_NOT_FOUND only for an index + /// past its MAX_GROUP_CHANNELS, so every later index is out of range too: + /// finish the sync now instead of retrying each one until it times out. + void _handleChannelSyncNotFound() { + debugPrint( + '[ChannelSync] Channel $_nextChannelIndexToRequest not found; ' + 'device has $_nextChannelIndexToRequest channel slots', + ); + _channelSyncTimeout?.cancel(); + _channelSyncInFlight = false; + _totalChannelsToRequest = _nextChannelIndexToRequest; + _completeChannelSync(); + } + void _completeChannelSync() { _channelSyncTimeout?.cancel(); @@ -4953,6 +5414,7 @@ class MeshCoreConnector extends ChangeNotifier { await _channelMessageStore.clearChannelMessages(index); // Clear in-memory messages for this channel _channelMessages.remove(index); + _processedChannelReactions.remove(index); // Refresh channels after deleting await getChannels(force: true); } @@ -4988,6 +5450,7 @@ class MeshCoreConnector extends ChangeNotifier { } _isLoadingContacts = true; _contactSyncReceived = 0; + _armContactSyncWatchdog(); // Firmware v3+ includes total contacts after CONTACTS_START. // Incremental sync reports total contacts, not filtered result count. if (frame.length >= 5 && !_contactSyncUsesSinceFilter) { @@ -5020,6 +5483,11 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeContact: debugPrint('Got CONTACT'); _handleContact(frame, countTowardSync: !completedPendingReply); + if (_isLoadingContacts && !completedPendingReply) { + _armContactSyncWatchdog(); + } else if (!_isLoadingContacts) { + unawaited(_replayUnknownSenderMessages(onlyResolvable: true)); + } break; case pushCodeContactDeleted: _handleContactDeleted(frame); @@ -5039,6 +5507,12 @@ class MeshCoreConnector extends ChangeNotifier { ); notifyListeners(); break; + case respCodeDefaultFloodScope: + final scope = parseDefaultFloodScopeFrame(frame); + _defaultFloodScopeName = scope?.name; + _defaultFloodScopeKey = scope?.key; + notifyListeners(); + break; case respCodeEndOfContacts: debugPrint('Got END_OF_CONTACTS'); _isLoadingContacts = false; @@ -5051,18 +5525,7 @@ class MeshCoreConnector extends ChangeNotifier { unawaited(updateKnownDiscovered()); notifyListeners(); unawaited(_persistContacts()); - if (PlatformInfo.isWeb && - _activeTransport == MeshCoreTransportType.bluetooth && - _isSyncingChannels && - !_channelSyncInFlight) { - unawaited(_requestNextChannel()); - } - if (_deferQueuedContactMessagesUntilContacts) { - unawaited(_processDeferredQueuedContactMessages()); - } else if (_pendingQueueSync) { - _pendingQueueSync = false; - unawaited(syncQueuedMessages(force: true)); - } + _continueAfterContactSync(); break; case respCodeContactMsgRecv: case respCodeContactMsgRecvV3: @@ -5162,6 +5625,14 @@ class MeshCoreConnector extends ChangeNotifier { ); final failedAck = _pendingGenericAckQueue.takeErr(errCode); + if (failedAck != null && + failedAck.commandCode == cmdGetChannel && + errCode == _errCodeNotFound && + _isSyncingChannels && + _channelSyncInFlight) { + _handleChannelSyncNotFound(); + return; + } if (failedAck == null || failedAck.commandCode != cmdSendChannelTxtMsg || failedAck.channelSendQueueId == null) { @@ -5301,6 +5772,28 @@ class MeshCoreConnector extends ChangeNotifier { return; } + // A different radio answered (for example after a dropped BLE link): + // drop the previous radio's history before this radio's stores load. + if (_messageStateOwnerKey != null && + _messageStateOwnerKey != selfPublicKeyHex) { + _clearSessionMessageState(); + } + _messageStateOwnerKey = selfPublicKeyHex; + + if (_persistedStateLoadedKey == selfPublicKeyHex) { + _awaitingSelfInfo = false; + _selfInfoRetryTimer?.cancel(); + _selfInfoRetryTimer = null; + _maybeRequestDeviceConfig(); + notifyListeners(); + _maybeStartInitialChannelSync(); + if (_pendingQueueSync && _hasLoadedContacts && !_isLoadingContacts) { + _pendingQueueSync = false; + unawaited(syncQueuedMessages(force: true)); + } + return; + } + //set all the stores' public key so they can load the correct data _channelMessageStore.setPublicKeyHex = selfPublicKeyHex; _messageStore.setPublicKeyHex = selfPublicKeyHex; @@ -5324,6 +5817,7 @@ class MeshCoreConnector extends ChangeNotifier { loadAllChannelMessages(); loadUnreadState(); _loadDiscoveredContactCache(); + _persistedStateLoadedKey = selfPublicKeyHex; _awaitingSelfInfo = false; _selfInfoRetryTimer?.cancel(); @@ -5333,6 +5827,13 @@ class MeshCoreConnector extends ChangeNotifier { // Start the serialized initial sync pipeline after SELF_INFO. _maybeStartInitialChannelSync(); + + // A queue sync deferred while this SELF_INFO was awaited (e.g. a later + // refreshDeviceInfo) has nothing else to resume it. + if (_pendingQueueSync && _hasLoadedContacts && !_isLoadingContacts) { + _pendingQueueSync = false; + unawaited(syncQueuedMessages(force: true)); + } } void _handleDeviceInfo(Uint8List frame) { @@ -5977,6 +6478,7 @@ class MeshCoreConnector extends ChangeNotifier { Future _handleIncomingMessage( Uint8List frame, { bool alreadyAdvancedQueueSync = false, + bool isUnknownSenderReplay = false, }) async { if (_selfPublicKey == null) return; @@ -5988,24 +6490,26 @@ class MeshCoreConnector extends ChangeNotifier { var message = _parseContactMessage(frame); - // If message parsing failed due to unknown contact, refresh contacts and retry - if (message == null && !_isLoadingContacts) { + // Unknown sender: the firmware has already dropped this message from its + // offline queue, so hold it until the sender's CONTACT frame arrives + // rather than re-parsing before the refresh has delivered anything. + if (message == null && !isUnknownSenderReplay) { final senderPrefix = _extractSenderPrefix(frame); - if (senderPrefix != null) { - final hasContact = _contacts.any( - (c) => _matchesPrefix(c.publicKey, senderPrefix), - ); - if (!hasContact) { - debugPrint( - 'Received message from unknown contact, refreshing contacts...', - ); - await refreshContactsSinceLastmod(); - // Retry parsing after refresh - message = _parseContactMessage(frame); - if (message != null) { - debugPrint('Successfully parsed message after contact refresh'); + if (senderPrefix != null && + !_contacts.any((c) => _matchesPrefix(c.publicKey, senderPrefix))) { + debugPrint('Message from unknown contact; holding until contacts load'); + _holdUnknownSenderMessage(frame); + if (!_isLoadingContacts) { + try { + await refreshContactsSinceLastmod(); + } catch (e) { + appLogger.warn( + 'Contact refresh for unknown sender failed: $e', + tag: 'Connector', + ); } } + return; } } @@ -6137,10 +6641,10 @@ class MeshCoreConnector extends ChangeNotifier { timestampRaw * 1000, ); - final flags = txtType; - final shiftedType = flags >> 2; - final rawType = flags; - final isSigned = shiftedType == txtTypeSigned || rawType == txtTypeSigned; + // Companion frames carry the raw TXT_TYPE (0..3); legacy firmware sent + // it shifted into the upper six bits like the over-the-air flags byte. + final type = txtType <= _txtTypeCliCommand ? txtType : txtType >> 2; + final isSigned = type == txtTypeSigned; final Uint8List? roomAuthorPrefix; if (isSigned) { // Room-server pushed posts use signed/plain contact messages where this @@ -6153,13 +6657,12 @@ class MeshCoreConnector extends ChangeNotifier { final msgText = reader.readCString(); - final isPlain = - shiftedType == txtTypePlain || rawType == txtTypePlain || isSigned; - final isCli = shiftedType == txtTypeCliData || rawType == txtTypeCliData; + final isPlain = type == txtTypePlain || isSigned; + // TXT_TYPE_CLI_COMMAND is a remote CLI command the firmware did not run + // (sender lacks remote-CLI permission); show it as CLI, never as chat. + final isCli = type == txtTypeCliData || type == _txtTypeCliCommand; if (!isPlain && !isCli) { - appLogger.warn( - 'Unknown message type received: txtType=$txtType, shifted=$shiftedType, raw=$rawType', - ); + appLogger.warn('Unknown message type received: txtType=$txtType'); return null; } @@ -6186,6 +6689,7 @@ class MeshCoreConnector extends ChangeNotifier { senderKey: contact.publicKey, text: decodedText, timestamp: timestamp, + receivedAt: DateTime.now(), isOutgoing: false, isCli: isCli, status: MessageStatus.delivered, @@ -6514,6 +7018,7 @@ class MeshCoreConnector extends ChangeNotifier { senderName: parsed.senderName, text: decodedText, timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), + receivedAt: DateTime.now(), isOutgoing: false, status: ChannelMessageStatus.sent, pathLength: packet.isFlood ? packet.hopCount : 0, @@ -6570,14 +7075,6 @@ class MeshCoreConnector extends ChangeNotifier { final ackHash = reader.readUInt32LE(); final timeoutMs = reader.readUInt32LE(); - // Check if this is a CLI command ACK - if so, ignore it - if (_lastSentWasCliCommand) { - final ackHashHex = ackHashToHex(ackHash); - debugPrint('Ignoring CLI command ACK (sent): $ackHashHex'); - _lastSentWasCliCommand = false; - return; - } - if (_handleRepeaterCommandSent(ackHash, timeoutMs)) { return; } @@ -6681,8 +7178,6 @@ class MeshCoreConnector extends ChangeNotifier { final ackHash = reader.readUInt32LE(); final tripTimeMs = reader.readUInt32LE(); - // CLI command ACKs are already filtered in _handleMessageSent, so this should only see real messages - if (_handleRepeaterCommandAck(ackHash, tripTimeMs)) { return; } @@ -6738,6 +7233,7 @@ class MeshCoreConnector extends ChangeNotifier { void _handleChannelInfo(Uint8List frame) { final channel = Channel.fromFrame(frame); if (channel == null) return; + _unconfirmedChannelSlots.remove(channel.index); debugPrint( '[ChannelSync] Received channel ${channel.index}: ${channel.isEmpty ? "empty" : channel.name}', @@ -6992,7 +7488,9 @@ class MeshCoreConnector extends ChangeNotifier { messages.add(message); if (messages.length > _messageWindowSize) { - messages.removeRange(0, messages.length - _messageWindowSize); + final trimCount = messages.length - _messageWindowSize; + _messageStore.archive(pubKeyHex, messages.sublist(0, trimCount)); + messages.removeRange(0, trimCount); } _messageStore.saveMessages(pubKeyHex, messages); notifyListeners(); @@ -7134,18 +7632,35 @@ class MeshCoreConnector extends ChangeNotifier { // `foo` and `#foo` share a scope key, so dedupe without the prefix or a // region listed both ways would always look ambiguous. - final candidates = { + final names = { for (final region in [ ...RegionStore().loadRegions(), ..._channelRegions.values, _defaultRegion, ]) region.startsWith('#') ? region.substring(1) : region, - }.where((region) => region.trim().isNotEmpty).toList()..sort(); + }.where((region) => region.trim().isNotEmpty && region != kUnscopedRegion); + final keys = { + for (final name in names) name: floodScopeKeyForRegion(name), + }; + // The radio's default scope key may not be derived from its name (another + // client may have set it), so match on the stored key itself. + final radioDefaultName = _defaultFloodScopeName; + final radioDefaultKey = _defaultFloodScopeKey; + if (radioDefaultName != null && radioDefaultKey != null) { + final name = radioDefaultName.startsWith('#') + ? radioDefaultName.substring(1) + : radioDefaultName; + final derived = keys[name]; + if (derived == null || !_pathsEqual(derived, radioDefaultKey)) { + keys[name] = radioDefaultKey; + } + } + final candidates = keys.keys.toList()..sort(); String? match; for (final region in candidates) { final code = floodTransportCode( - scopeKey: floodScopeKeyForRegion(region), + scopeKey: keys[region]!, payloadType: packet.payloadType, payload: packet.payload, ); @@ -7296,6 +7811,7 @@ class MeshCoreConnector extends ChangeNotifier { translationStatus: message.translationStatus, translationModelId: message.translationModelId, timestamp: message.timestamp, + receivedAt: message.receivedAt, isOutgoing: message.isOutgoing, status: message.status, repeats: message.repeats, @@ -7530,6 +8046,31 @@ class MeshCoreConnector extends ChangeNotifier { } void _handleDisconnection() { + _resetLinkSessionState(); + + _notifySubscription?.cancel(); + _notifySubscription = null; + _connectionSubscription?.cancel(); + _connectionSubscription = null; + + _device = null; + _rxCharacteristic = null; + _txCharacteristic = null; + // Preserve deviceId and displayName for UI display during reconnection + // They're only cleared on manual disconnect via disconnect() method. + // Conversations are kept for an auto-reconnect to the same radio; + // _handleSelfInfo drops them if a different radio answers. + + _setState(MeshCoreConnectionState.disconnected); + _scheduleReconnect(); + } + + /// Per-link state shared by a full disconnect and a dropped BLE link: + /// polling timers, radio stats, battery and pending protocol replies. + void _resetLinkSessionState() { + _persistedStateLoadedKey = null; + _defaultFloodScopeName = null; + _defaultFloodScopeKey = null; _stopBatteryPolling(); _stopGpsLocationPolling(); _stopRadioStatsPolling(); @@ -7544,21 +8085,14 @@ class MeshCoreConnector extends ChangeNotifier { } _pendingRepeaterAcks.clear(); - _notifySubscription?.cancel(); - _notifySubscription = null; - _connectionSubscription?.cancel(); - _connectionSubscription = null; - - _device = null; - _rxCharacteristic = null; - _txCharacteristic = null; - // Preserve deviceId and displayName for UI display during reconnection - // They're only cleared on manual disconnect via disconnect() method _selfPublicKey = null; _awaitingSelfInfo = false; _selfInfoRetryTimer?.cancel(); _selfInfoRetryTimer = null; _hasReceivedDeviceInfo = false; + _batteryMillivolts = null; + _batteryRequested = false; + _pathHashByteWidth = 1; _maxContacts = _defaultMaxContacts; _maxChannels = _defaultMaxChannels; _resetSyncProgressState(); @@ -7566,9 +8100,22 @@ class MeshCoreConnector extends ChangeNotifier { _pendingGenericAckQueue.clear(); _reactionSendQueueSequence = 0; _retryService?.failAllPending(); + } - _setState(MeshCoreConnectionState.disconnected); - _scheduleReconnect(); + /// Drops the conversation and channel history held in memory, so a + /// different radio never shows or persists another radio's messages. + void _clearSessionMessageState() { + _conversations.clear(); + _loadedConversationKeys.clear(); + _channelMessages.clear(); + _processedChannelReactions.clear(); + _processedContactReactions.clear(); + _channelHopChecks.clear(); + _channelHopShortfalls.clear(); + _messageStore.forgetArchive(); + _channelMessageStore.forgetArchive(); + _messageStateOwnerKey = null; + _persistedStateLoadedKey = null; } String _nextReactionSendQueueId() { @@ -8244,7 +8791,8 @@ class MeshCoreConnector extends ChangeNotifier { final messages = _conversations[contactKeyHex]; if (messages == null) return; messages.clear(); - unawaited(_messageStore.saveMessages(contactKeyHex, messages)); + // Clear storage too, not just the in-memory window. + unawaited(_messageStore.clearMessages(contactKeyHex)); markContactRead(contactKeyHex); notifyListeners(); } @@ -8253,7 +8801,8 @@ class MeshCoreConnector extends ChangeNotifier { final messages = _channelMessages[channelIndex]; if (messages == null) return; messages.clear(); - unawaited(_channelMessageStore.saveChannelMessages(channelIndex, messages)); + // Clear storage too, not just the in-memory window. + unawaited(_channelMessageStore.clearChannelMessages(channelIndex)); markChannelRead(channelIndex); notifyListeners(); } @@ -8305,7 +8854,7 @@ bool _isPathLenValidForMode( Uint8List _reversePathByHop(Uint8List pathBytes, int pathHashWidth) { if (pathBytes.isEmpty) return Uint8List(0); - final width = pathHashWidth.clamp(1, 4).toInt(); + final width = pathHashWidth.clamp(1, maxPathHashWidth).toInt(); final reversed = []; for (var i = pathBytes.length; i > 0; i -= width) { final start = (i - width).clamp(0, pathBytes.length).toInt(); diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index f740969b..126110ad 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -133,9 +133,8 @@ class BufferWriter { void writeCString(String string, int maxLength) { final bytes = Uint8List(maxLength); final encoded = utf8.encode(string); - for (var i = 0; i < maxLength - 1 && i < encoded.length; i++) { - bytes[i] = encoded[i]; - } + final len = utf8BoundaryLength(encoded, maxLength - 1); + bytes.setRange(0, len, encoded); writeBytes(bytes); } @@ -215,6 +214,8 @@ const int cmdSetAutoAddConfig = 58; const int cmdGetAutoAddConfig = 59; const int cmdGetAllowedRepeatFreq = 60; const int cmdSetPathHashMode = 61; +const int cmdSetDefaultFloodScope = 63; // FIRMWARE_VER_CODE 11+ +const int cmdGetDefaultFloodScope = 64; // FIRMWARE_VER_CODE 11+ // Text message types const int txtTypePlain = 0; @@ -265,6 +266,12 @@ const int respCodeCustomVars = 21; const int respCodeAutoAddConfig = 25; const int respCodeAllowedRepeatFreq = 26; const int respCodeStats = 24; +const int respCodeDefaultFloodScope = 28; + +/// Region name field width in SET/GET_DEFAULT_FLOOD_SCOPE frames (NUL padded, +/// so at most 30 name bytes). +const int defaultFloodScopeNameSize = 31; +const int floodScopeKeySize = 16; const int statsTypeCore = 0; const int statsTypeRadio = 1; @@ -333,13 +340,34 @@ const int autoAddRoomServerFlag = const int autoAddSensorFlag = 1 << 4; // 0x10 - auto-add Sensor (ADV_TYPE_SENSOR) +/// Returns the largest prefix length of [bytes] that is at most [maxBytes] +/// and does not end in the middle of a UTF-8 encoded character. +int utf8BoundaryLength(List bytes, int maxBytes) { + if (bytes.length <= maxBytes) return bytes.length; + if (maxBytes <= 0) return 0; + var len = maxBytes; + // Back up over continuation bytes (10xxxxxx) to the lead byte, then drop + // that lead byte too since its character would be cut short. + while (len > 0 && (bytes[len] & 0xC0) == 0x80) { + len--; + } + return len; +} + // Sizes const int pubKeySize = 32; const int signatureSize = 64; const int maxPathSize = 64; const int pathHashSize = 1; const int maxNameSize = 32; +// Largest frame the app sends. Kept at 172 so commands still fit radios on +// firmware built before MAX_FRAME_SIZE grew to 176. const int maxFrameSize = 172; +// Largest frame current firmware may send (MAX_FRAME_SIZE 176, +4 bytes for +// region transport codes). Receive paths must accept frames up to this size. +const int maxRxFrameSize = 176; +// Widest per-hop path hash firmware accepts on air (mode 2); 4 is reserved. +const int maxPathHashWidth = 3; const int appProtocolVersion = 4; // Matches firmware MAX_TEXT_LEN (10 * CIPHER_BLOCK_SIZE). const int maxTextPayloadBytes = 160; @@ -599,7 +627,8 @@ Uint8List buildGetStatsFrame(int statsType) { return Uint8List.fromList([cmdGetStats, statsType & 0xFF]); } -/// Path hash width on air: [61][0][mode], mode 0..3 → (mode+1) bytes per hop hash. +/// Path hash width on air: [61][0][mode], mode 0..2 → (mode+1) bytes per hop +/// hash. Firmware rejects mode 3 (4-byte hashes are reserved). Uint8List buildSetPathHashModeFrame(int mode) { final m = mode.clamp(0, 2).toInt(); return Uint8List.fromList([cmdSetPathHashMode, 0, m]); @@ -623,9 +652,7 @@ Uint8List buildSendSelfAdvertFrame({bool flood = false}) { // Format: [cmd][name...] Uint8List buildSetAdvertNameFrame(String name) { final nameBytes = utf8.encode(name); - final nameLen = nameBytes.length < maxNameSize - ? nameBytes.length - : maxNameSize - 1; + final nameLen = utf8BoundaryLength(nameBytes, maxNameSize - 1); final writer = BufferWriter(); writer.writeByte(cmdSetAdvertName); writer.writeBytes(Uint8List.fromList(nameBytes.sublist(0, nameLen))); @@ -938,9 +965,72 @@ Uint8List buildDiscoveryRequestPayload( return writer.toBytes(); } +/// Node types a manual nearby-node scan asks for. Firmware repeaters and +/// sensors answer DISCOVER_REQ; room servers and companions currently don't, +/// but the room bit is harmless and lets future firmware reply. +const int nodeDiscoverScanTypeMask = + (1 << advTypeRepeater) | (1 << advTypeRoom) | (1 << advTypeSensor); + +/// One DISCOVER_RESP, as pushed by the companion in PUSH_CODE_CONTROL_DATA: +/// `[0x8E][snr x4 int8][rssi int8][path_len][0x9][snr x4 int8][tag u32 LE][pub_key 8|32]`. +class NodeDiscoverResponse { + NodeDiscoverResponse({ + required this.nodeType, + required this.snr, + required this.rssi, + required this.remoteSnr, + required this.tag, + required this.publicKey, + }); + + final int nodeType; + + /// SNR (dB) of the response as received by our radio. + final double snr; + final int rssi; + + /// SNR (dB) of our request as heard by the responding node. + final double remoteSnr; + final int tag; + + /// Full 32-byte key, or an 8-byte prefix when the request was prefix-only. + final Uint8List publicKey; + + bool get hasFullKey => publicKey.length == pubKeySize; + String get publicKeyHex => pubKeyToHex(publicKey); +} + +/// Parses a PUSH_CODE_CONTROL_DATA frame carrying a DISCOVER_RESP, or returns +/// null for any other or malformed frame. +NodeDiscoverResponse? parseNodeDiscoverResponse(Uint8List frame) { + // Push header (4) + type, snr, tag (6) + at least an 8-byte key prefix. + if (frame.length < 4 + 6 + 8 || frame[0] != pushCodeControlData) { + return null; + } + final reader = BufferReader(frame); + reader.skipBytes(1); + final snr = reader.readInt8() / 4.0; + final rssi = reader.readInt8(); + reader.skipBytes(1); // path_len: responses are sent zero-hop. + final typeByte = reader.readByte(); + if ((typeByte >> 4) != controlSubtypeDiscoverResp) return null; + final remoteSnr = reader.readInt8() / 4.0; + final tag = reader.readUInt32LE(); + final keyBytes = reader.readRemainingBytes(); + final keyLength = keyBytes.length >= pubKeySize ? pubKeySize : 8; + return NodeDiscoverResponse( + nodeType: typeByte & 0x0F, + snr: snr, + rssi: rssi, + remoteSnr: remoteSnr, + tag: tag, + publicKey: Uint8List.fromList(keyBytes.sublist(0, keyLength)), + ); +} + Uint8List _reversePathByHop(Uint8List path, int pathHashWidth) { if (path.isEmpty) return Uint8List(0); - final width = pathHashWidth.clamp(1, 4).toInt(); + final width = pathHashWidth.clamp(1, maxPathHashWidth).toInt(); if (path.length % width != 0) { return Uint8List.fromList(path.reversed.toList()); } @@ -963,7 +1053,7 @@ Uint8List buildSendAnonReqFrame( int replyHopCount = 0, int pathHashWidth = pathHashSize, }) { - final width = pathHashWidth.clamp(1, 4).toInt(); + final width = pathHashWidth.clamp(1, maxPathHashWidth).toInt(); final path = replyPath ?? Uint8List(0); final encodedPathLen = ((width - 1) << 6) | (replyHopCount & 0x3F); final writer = BufferWriter(); @@ -1086,6 +1176,63 @@ Uint8List buildSetFloodScopeFrame(String region) { return Uint8List.fromList([cmdSetFloodScope, 0, ...scope]); } +/// CMD_SET_FLOOD_SCOPE variant 1 (FIRMWARE_VER_CODE 12+): send floods with no +/// transport scope at all, overriding the radio's default flood scope. +Uint8List buildSetFloodScopeUnscopedFrame() { + return Uint8List.fromList([cmdSetFloodScope, 1]); +} + +Uint8List buildGetDefaultFloodScopeFrame() { + return Uint8List.fromList([cmdGetDefaultFloodScope]); +} + +/// CMD_SET_DEFAULT_FLOOD_SCOPE: `[63][name 31][key 16]` stores [region] as the +/// radio's default flood scope; an empty [region] clears it (`[63]`). +/// The name is stored without a leading '#'; the key uses the same derivation +/// as [buildSetFloodScopeFrame]. +Uint8List buildSetDefaultFloodScopeFrame(String region) { + final name = region.startsWith('#') ? region.substring(1) : region; + if (name.isEmpty) return Uint8List.fromList([cmdSetDefaultFloodScope]); + final nameBytes = utf8.encode(name); + if (nameBytes.length >= defaultFloodScopeNameSize) { + throw ArgumentError.value(region, 'region', 'name longer than 30 bytes'); + } + final frame = Uint8List(1 + defaultFloodScopeNameSize + floodScopeKeySize); + frame[0] = cmdSetDefaultFloodScope; + frame.setRange(1, 1 + nameBytes.length, nameBytes); + frame.setRange( + 1 + defaultFloodScopeNameSize, + frame.length, + floodScopeKeyForRegion(name), + ); + return frame; +} + +/// Parses RESP_CODE_DEFAULT_FLOOD_SCOPE. Returns null when the radio has no +/// default scope (`[28]` alone) or the frame is malformed. +({String name, Uint8List key})? parseDefaultFloodScopeFrame(Uint8List frame) { + if (frame.isEmpty || frame[0] != respCodeDefaultFloodScope) return null; + if (frame.length < 1 + defaultFloodScopeNameSize + floodScopeKeySize) { + return null; + } + final nameField = frame.sublist(1, 1 + defaultFloodScopeNameSize); + final end = nameField.indexOf(0); + final name = utf8 + .decode( + end >= 0 ? nameField.sublist(0, end) : nameField, + allowMalformed: true, + ) + .trim(); + if (name.isEmpty) return null; + final keyStart = 1 + defaultFloodScopeNameSize; + return ( + name: name, + key: Uint8List.fromList( + frame.sublist(keyStart, keyStart + floodScopeKeySize), + ), + ); +} + Uint8List floodScopeKeyForRegion(String region) { final name = region.startsWith('#') ? region : '#$region'; final hash = crypto.sha256.convert(utf8.encode(name)).bytes; diff --git a/lib/connector/pending_command_replies.dart b/lib/connector/pending_command_replies.dart index 43968c02..a0dc9b5d 100644 --- a/lib/connector/pending_command_replies.dart +++ b/lib/connector/pending_command_replies.dart @@ -17,7 +17,14 @@ class PendingCommandReply { final Uint8List? matchKey; final String? channelSendQueueId; final Completer? completer; - final DateTime createdAt = DateTime.now(); + final DateTime createdAt; + + /// Set when the sender gave up waiting. The entry then stays queued as a + /// tombstone so the firmware's late reply is absorbed here instead of being + /// credited to the next command. + DateTime? timedOutAt; + + bool get isTombstone => timedOutAt != null; PendingCommandReply({ required this.commandCode, @@ -25,7 +32,8 @@ class PendingCommandReply { this.matchKey, this.channelSendQueueId, this.completer, - }); + DateTime? createdAt, + }) : createdAt = createdAt ?? DateTime.now(); } /// Success reply for each command whose single reply is OK/ERR or a specific @@ -53,6 +61,7 @@ int? replyCodeForCommand(Uint8List data) { case cmdSetAutoAddConfig: case cmdSetPathHashMode: case cmdSendChannelData: + case cmdSetDefaultFloodScope: return respCodeOk; case cmdSendTxtMsg: case cmdSendLogin: @@ -88,6 +97,8 @@ int? replyCodeForCommand(Uint8List data) { return respCodeAutoAddConfig; case cmdGetAllowedRepeatFreq: return respCodeAllowedRepeatFreq; + case cmdGetDefaultFloodScope: + return respCodeDefaultFloodScope; } return null; } @@ -96,11 +107,20 @@ int? replyCodeForCommand(Uint8List data) { /// and answers each with OK, ERR or a specific RESP_CODE, so an ERR belongs /// to the oldest pending command and an OK to the oldest one expecting OK. class PendingCommandReplies { - PendingCommandReplies({required this.staleAfter}); + PendingCommandReplies({ + required this.staleAfter, + this.tombstoneLifetime = const Duration(seconds: 10), + DateTime Function()? clock, + }) : _clock = clock ?? DateTime.now; /// Entries older than this are dropped so a lost reply cannot swallow a /// later, unrelated OK/ERR. Awaited entries time out in sendFrame first. final Duration staleAfter; + + /// How long a timed-out entry waits for its late reply. Kept short so a + /// reply that never comes swallows at most a brief window of replies. + final Duration tombstoneLifetime; + final DateTime Function() _clock; final List _queue = []; int get length => _queue.length; @@ -123,6 +143,7 @@ class PendingCommandReplies { : null, channelSendQueueId: channelSendQueueId, completer: waitForReply ? Completer() : null, + createdAt: _clock(), ); if (pending.completer != null) { // The sender awaits this future after transport I/O; attach an error @@ -135,11 +156,19 @@ class PendingCommandReplies { void remove(PendingCommandReply pending) => _queue.remove(pending); + /// Marks [pending] as abandoned by its sender. It keeps its place in the + /// FIFO so a late reply is consumed by it rather than misattributed. + void markTimedOut(PendingCommandReply pending) { + if (!_queue.contains(pending)) return; + pending.timedOutAt = _clock(); + } + void clear() => _queue.clear(); /// Completes the oldest command whose success reply is [frame]'s code. bool completeReply(Uint8List frame) { if (frame.isEmpty) return false; + _pruneStale(); final code = frame[0]; if (code == respCodeOk || code == respCodeErr) return false; final key = code == respCodeContact && frame.length >= 1 + pubKeySize @@ -156,20 +185,24 @@ class PendingCommandReplies { } /// Attributes RESP_CODE_OK; commands expecting a specific reply are skipped. + /// Returns null when no command matches or a timed-out entry absorbed it. PendingCommandReply? takeOk() { _pruneStale(); final index = _queue.indexWhere((p) => p.replyCode == respCodeOk); if (index < 0) return null; final pending = _queue.removeAt(index); + if (pending.isTombstone) return null; pending.completer?.complete(); return pending; } /// Attributes RESP_CODE_ERR to the oldest pending command. + /// Returns null when nothing is pending or a timed-out entry absorbed it. PendingCommandReply? takeErr(int errCode) { _pruneStale(); if (_queue.isEmpty) return null; final pending = _queue.removeAt(0); + if (pending.isTombstone) return null; pending.completer?.completeError( Exception('Command failed with error code $errCode'), ); @@ -177,7 +210,13 @@ class PendingCommandReplies { } void _pruneStale() { - final cutoff = DateTime.now().subtract(staleAfter); - _queue.removeWhere((p) => p.createdAt.isBefore(cutoff)); + final now = _clock(); + final cutoff = now.subtract(staleAfter); + final tombstoneCutoff = now.subtract(tombstoneLifetime); + _queue.removeWhere( + (p) => + p.createdAt.isBefore(cutoff) || + (p.timedOutAt?.isBefore(tombstoneCutoff) ?? false), + ); } } diff --git a/lib/helpers/channel_resend_coverage.dart b/lib/helpers/channel_resend_coverage.dart new file mode 100644 index 00000000..d2eca9d3 --- /dev/null +++ b/lib/helpers/channel_resend_coverage.dart @@ -0,0 +1,53 @@ +import 'dart:typed_data'; + +import '../models/channel_message.dart'; + +/// Distinct first-hop repeaters heard echoing [message], across every resend +/// (echoes of all attempts merge into the same message's path variants). +/// +/// Each first hop is the leading `pathHashWidth` bytes of an echo's path. +/// Zero-hop echoes and a first hop matching our own key prefix are ignored. +Set distinctFirstHopRepeaters( + ChannelMessage message, { + Uint8List? selfPublicKey, +}) { + final width = (message.pathHashWidth ?? 1).clamp(1, 3).toInt(); + String? selfPrefix; + if (selfPublicKey != null && selfPublicKey.length >= width) { + selfPrefix = _hex(selfPublicKey, width); + } + final hops = {}; + for (final path in [message.pathBytes, ...message.pathVariants]) { + if (path.length < width) continue; + final hop = _hex(path, width); + if (hop != selfPrefix) hops.add(hop); + } + return hops; +} + +/// Whether a channel resend has heard [message] travel far enough: +/// an echo through at least [minHops] repeaters, or, when +/// [countDistinctRepeaters] is on, echoes from at least [minHops] different +/// first-hop repeaters. +bool channelResendSatisfied( + ChannelMessage message, { + required int minHops, + required bool countDistinctRepeaters, + Uint8List? selfPublicKey, +}) { + if ((message.pathLength ?? 0) >= minHops) return true; + if (!countDistinctRepeaters) return false; + return distinctFirstHopRepeaters( + message, + selfPublicKey: selfPublicKey, + ).length >= + minHops; +} + +String _hex(Uint8List bytes, int length) { + final buffer = StringBuffer(); + for (var i = 0; i < length; i++) { + buffer.write(bytes[i].toRadixString(16).padLeft(2, '0')); + } + return buffer.toString(); +} diff --git a/lib/helpers/cyr2lat.dart b/lib/helpers/cyr2lat.dart index a7ec5dde..d5d0c23b 100644 --- a/lib/helpers/cyr2lat.dart +++ b/lib/helpers/cyr2lat.dart @@ -24,7 +24,9 @@ class Cyr2Lat { 'х': 'x', }; - static final RegExp _prefixRegExp = RegExp(r'\@\[[\S\s]+\] '); + // Non-greedy so only the leading "@[name] " mention is treated as the + // sender prefix, not everything up to the last "] " in the message. + static final RegExp _prefixRegExp = RegExp(r'@\[[\S\s]+?\] '); static void setCharMap(Map charMap) { _charMap = Map.from(charMap); diff --git a/lib/helpers/link_handler.dart b/lib/helpers/link_handler.dart index 980369da..41acba45 100644 --- a/lib/helpers/link_handler.dart +++ b/lib/helpers/link_handler.dart @@ -15,6 +15,19 @@ class LinkHandler { return base.copyWith(color: orange, decoration: TextDecoration.underline); } + /// The system text scale as a linear factor for [style]'s size. + /// + /// flutter_linkify only takes a `textScaleFactor` (default 1.0, which + /// ignores the system font size), so the ambient [TextScaler] is sampled + /// at the style's font size to keep Android's nonlinear scaling. The + /// in-app chat text scale is already part of `style.fontSize`. + static double systemTextScaleFactor(BuildContext context, TextStyle style) { + final fontSize = + style.fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14; + if (fontSize <= 0) return 1.0; + return MediaQuery.textScalerOf(context).scale(fontSize) / fontSize; + } + /// Returns a [SelectableLinkify] on desktop or a [Linkify] on mobile. static Widget buildLinkifyText({ required BuildContext context, @@ -27,6 +40,7 @@ class LinkHandler { const options = LinkifyOptions(humanize: false, defaultToHttps: false); const linkifiers = [UrlLinkifier(), EmailLinkifier()]; void onOpen(LinkableElement link) => handleLinkTap(context, link.url); + final textScaleFactor = systemTextScaleFactor(context, style); if (PlatformInfo.isDesktop) { final linkify = SelectableLinkify( @@ -36,6 +50,7 @@ class LinkHandler { options: options, linkifiers: linkifiers, onOpen: onOpen, + textScaleFactor: textScaleFactor, ); if (onSecondaryTap == null) return linkify; return Listener( @@ -53,6 +68,7 @@ class LinkHandler { options: options, linkifiers: linkifiers, onOpen: onOpen, + textScaleFactor: textScaleFactor, ); } diff --git a/lib/helpers/reaction_helper.dart b/lib/helpers/reaction_helper.dart index 58928284..982ce48c 100644 --- a/lib/helpers/reaction_helper.dart +++ b/lib/helpers/reaction_helper.dart @@ -120,11 +120,32 @@ class ReactionHelper { final input = senderName != null ? '$timestampSeconds$senderName$first5' : '$timestampSeconds$first5'; - // Use hashCode and take lower 16 bits, format as 4 hex chars - final hash = input.hashCode & 0xFFFF; + // Take the lower 16 bits of the string hash, format as 4 hex chars + final hash = stableStringHash(input) & 0xFFFF; return hash.toRadixString(16).padLeft(4, '0'); } + /// Platform-independent reimplementation of the Dart VM's + /// `String.hashCode` (one-at-a-time hash over UTF-16 code units, finalized + /// to 30 bits). Reaction hashes were originally computed with + /// `String.hashCode`, which differs on the web (dart2js), so this keeps + /// the wire format identical to existing native clients while giving web + /// builds the same result. + static int stableStringHash(String input) { + const mask32 = 0xFFFFFFFF; + var hash = 0; + for (final unit in input.codeUnits) { + hash = (hash + unit) & mask32; + hash = (hash + ((hash << 10) & mask32)) & mask32; + hash ^= hash >> 6; + } + hash = (hash + ((hash << 3) & mask32)) & mask32; + hash ^= hash >> 11; + hash = (hash + ((hash << 15) & mask32)) & mask32; + hash &= 0x3FFFFFFF; + return hash == 0 ? 1 : hash; + } + // Compute the type of reaction hash used by MeshCoreOne. static String computeReactionHashMC1( int timestampSeconds, diff --git a/lib/helpers/smaz.dart b/lib/helpers/smaz.dart index de34ddee..aefae7e1 100644 --- a/lib/helpers/smaz.dart +++ b/lib/helpers/smaz.dart @@ -281,19 +281,41 @@ class Smaz { return text; } + /// Decodes text produced by [encodeIfSmaller]. Returns null when [text] is + /// not a compressed payload. + /// + /// Plain text can also start with `s:` followed by base64-looking + /// characters ("s:test"), so a payload only counts as compressed when it + /// satisfies the encoder's invariants: valid UTF-8, re-compressing the + /// result yields the same bytes, and the encoded form is shorter than the + /// decoded text. Very short ambiguous inputs can still match. static String? tryDecodePrefixed(String text) { final trimmedLeft = text.trimLeft(); if (!trimmedLeft.startsWith('s:') || trimmedLeft.length <= 2) return null; final encoded = trimmedLeft.substring(2); try { final compressed = _decodeBase64Flexible(encoded); + if (compressed.isEmpty) return null; final decompressed = decompressBytes(compressed); - return utf8.decode(decompressed, allowMalformed: true); + final decoded = utf8.decode(decompressed); + final recompressed = compressBytes(decompressed); + if (!_bytesEqual(recompressed, compressed)) return null; + final candidateLength = 2 + base64Encode(compressed).length; + if (candidateLength >= decompressed.length) return null; + return decoded; } catch (_) { return null; } } + static bool _bytesEqual(List a, List b) { + if (a.length != b.length) return false; + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + static Uint8List compressBytes(Uint8List input) { final out = BytesBuilder(copy: false); final verbatim = []; diff --git a/lib/helpers/utf8_length_limiter.dart b/lib/helpers/utf8_length_limiter.dart index 235b84b2..e03061ec 100644 --- a/lib/helpers/utf8_length_limiter.dart +++ b/lib/helpers/utf8_length_limiter.dart @@ -72,3 +72,33 @@ class Utf8LengthLimitingTextInputFormatter extends TextInputFormatter { bool _isLowSurrogate(int codeUnit) => codeUnit >= 0xDC00 && codeUnit <= 0xDFFF; } + +/// Longest name (in UTF-8 bytes) the radio stores for channels and the node +/// advert name: a 32-byte field that keeps one byte for the NUL terminator. +const int maxRadioNameBytes = 31; + +int utf8ByteLength(String text) => utf8.encode(text).length; + +/// Cuts [text] to at most [maxBytes] UTF-8 bytes without splitting a +/// character (grapheme cluster). +String truncateUtf8(String text, int maxBytes) { + if (maxBytes <= 0) return ''; + if (utf8ByteLength(text) <= maxBytes) return text; + final kept = StringBuffer(); + var used = 0; + for (final char in text.characters) { + final size = utf8ByteLength(char); + if (used + size > maxBytes) break; + kept.write(char); + used += size; + } + return kept.toString(); +} + +/// Builds `"