From 88dcc5943ff1b7a0341599fb7acce739158bb806 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 15:17:01 -0700 Subject: [PATCH 1/8] UI refresh: shared widgets, screen cleanups, and full translations - Extract reusable widgets (chat composer/send pipeline, message bubble frame, reaction chips, path map scaffold, radio settings dialog, translation settings section, map POI clusters, nav tiles, etc.) and slim down the screens that used them - Map: hide/remove markers with restore, confirm before setting node location, POI clustering, semantics labels - Map cache: cancellable downloads and a bulk tile limit - Repeater: unsaved-changes guard, CLI search/copy/share transcript, framed-command debug preview, disconnected banner - Confirm before clearing chats and debug logs - Keep cached unread totals in sync on per-contact/channel updates - Move remaining hardcoded strings into l10n and translate the 98 new keys into all 17 non-English locales --- lib/connector/meshcore_connector.dart | 8 + lib/l10n/app_bg.arb | 100 +- lib/l10n/app_de.arb | 100 +- lib/l10n/app_en.arb | 141 +- lib/l10n/app_es.arb | 100 +- lib/l10n/app_fr.arb | 100 +- lib/l10n/app_hu.arb | 100 +- lib/l10n/app_it.arb | 100 +- lib/l10n/app_ja.arb | 100 +- lib/l10n/app_ko.arb | 100 +- lib/l10n/app_localizations.dart | 593 +++++ lib/l10n/app_localizations_bg.dart | 401 ++++ lib/l10n/app_localizations_de.dart | 399 ++++ lib/l10n/app_localizations_en.dart | 395 ++++ lib/l10n/app_localizations_es.dart | 398 ++++ lib/l10n/app_localizations_fr.dart | 399 ++++ lib/l10n/app_localizations_hu.dart | 397 ++++ lib/l10n/app_localizations_it.dart | 398 ++++ lib/l10n/app_localizations_ja.dart | 385 ++++ lib/l10n/app_localizations_ko.dart | 385 ++++ lib/l10n/app_localizations_nl.dart | 398 ++++ lib/l10n/app_localizations_pl.dart | 397 ++++ lib/l10n/app_localizations_pt.dart | 398 ++++ lib/l10n/app_localizations_ru.dart | 397 ++++ lib/l10n/app_localizations_sk.dart | 397 ++++ lib/l10n/app_localizations_sl.dart | 396 ++++ lib/l10n/app_localizations_sv.dart | 396 ++++ lib/l10n/app_localizations_uk.dart | 397 ++++ lib/l10n/app_localizations_zh.dart | 382 ++++ lib/l10n/app_nl.arb | 100 +- lib/l10n/app_pl.arb | 100 +- lib/l10n/app_pt.arb | 100 +- lib/l10n/app_ru.arb | 100 +- lib/l10n/app_sk.arb | 100 +- lib/l10n/app_sl.arb | 100 +- lib/l10n/app_sv.arb | 100 +- lib/l10n/app_uk.arb | 100 +- lib/l10n/app_zh.arb | 100 +- lib/screens/app_debug_log_screen.dart | 75 +- lib/screens/app_settings_screen.dart | 1971 +++-------------- lib/screens/ble_debug_log_screen.dart | 66 +- lib/screens/channel_chat_screen.dart | 1045 ++++----- lib/screens/channel_message_path_screen.dart | 879 +++----- lib/screens/channels_screen.dart | 1904 ++++++++-------- lib/screens/chat_screen.dart | 704 ++---- lib/screens/community_qr_scanner_screen.dart | 163 +- lib/screens/companion_radio_stats_screen.dart | 8 +- lib/screens/contact_qr_scanner_screen.dart | 81 +- lib/screens/contacts_screen.dart | 845 +++---- lib/screens/discovery_screen.dart | 216 +- lib/screens/line_of_sight_map_screen.dart | 813 +++---- lib/screens/map_cache_screen.dart | 500 +++-- lib/screens/map_screen.dart | 854 ++++--- lib/screens/neighbors_screen.dart | 70 +- lib/screens/path_trace_map.dart | 496 ++--- lib/screens/region_management_screen.dart | 339 ++- lib/screens/repeater_cli_screen.dart | 557 +++-- lib/screens/repeater_hub_screen.dart | 15 +- lib/screens/repeater_settings_screen.dart | 436 ++-- lib/screens/repeater_status_screen.dart | 143 +- lib/screens/scanner_screen.dart | 17 +- lib/screens/settings_screen.dart | 1833 ++++++--------- lib/screens/tcp_screen.dart | 43 +- lib/screens/telemetry_screen.dart | 149 +- lib/screens/usb_screen.dart | 105 +- lib/services/map_tile_cache_service.dart | 25 + lib/services/repeater_command_service.dart | 19 + lib/widgets/battery_indicator.dart | 2 +- lib/widgets/byte_count_input.dart | 4 +- lib/widgets/chat_composer.dart | 291 +++ lib/widgets/chat_day_separator.dart | 2 +- lib/widgets/chat_send_pipeline.dart | 192 ++ lib/widgets/confirm_clear_dialog.dart | 35 + lib/widgets/contact_visuals.dart | 123 + lib/widgets/cyr2lat_profile_dialog.dart | 151 ++ lib/widgets/debug_frame_viewer.dart | 4 +- lib/widgets/device_tile.dart | 10 +- lib/widgets/gif_picker.dart | 2 +- lib/widgets/language_picker_sheet.dart | 77 + lib/widgets/map_poi_cluster.dart | 121 + lib/widgets/mesh_nav_tile.dart | 127 ++ lib/widgets/mesh_ui.dart | 43 +- lib/widgets/message_bubble_frame.dart | 129 ++ lib/widgets/node_scan_sheet.dart | 33 +- lib/widgets/path_map_scaffold.dart | 506 +++++ lib/widgets/path_map_ui.dart | 184 +- lib/widgets/qr_scanner_widget.dart | 184 +- lib/widgets/radio_disconnected_banner.dart | 58 + lib/widgets/radio_settings_dialog.dart | 794 +++++++ lib/widgets/reaction_chips.dart | 150 ++ lib/widgets/received_image_message.dart | 20 +- lib/widgets/repeater_login_dialog.dart | 4 +- lib/widgets/room_login_dialog.dart | 4 +- lib/widgets/routing_sheet.dart | 4 +- lib/widgets/snr_indicator.dart | 2 +- lib/widgets/telemetry_location_map.dart | 2 +- lib/widgets/translation_settings_section.dart | 611 +++++ lib/widgets/unread_badge.dart | 2 +- lib/widgets/unread_divider.dart | 2 +- test/widgets/path_map_bottom_panel_test.dart | 144 ++ 100 files changed, 19778 insertions(+), 8167 deletions(-) create mode 100644 lib/widgets/chat_composer.dart create mode 100644 lib/widgets/chat_send_pipeline.dart create mode 100644 lib/widgets/confirm_clear_dialog.dart create mode 100644 lib/widgets/contact_visuals.dart create mode 100644 lib/widgets/cyr2lat_profile_dialog.dart create mode 100644 lib/widgets/language_picker_sheet.dart create mode 100644 lib/widgets/map_poi_cluster.dart create mode 100644 lib/widgets/mesh_nav_tile.dart create mode 100644 lib/widgets/message_bubble_frame.dart create mode 100644 lib/widgets/path_map_scaffold.dart create mode 100644 lib/widgets/radio_disconnected_banner.dart create mode 100644 lib/widgets/radio_settings_dialog.dart create mode 100644 lib/widgets/reaction_chips.dart create mode 100644 lib/widgets/translation_settings_section.dart create mode 100644 test/widgets/path_map_bottom_panel_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03e82f25..bf05ab44 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -1116,7 +1116,12 @@ class MeshCoreConnector extends ChangeNotifier { } void setContactUnreadCount(String contactKeyHex, int count) { + final previousCount = _contactUnreadCount[contactKeyHex] ?? 0; _contactUnreadCount[contactKeyHex] = count; + if (_shouldTrackUnreadForContactKey(contactKeyHex)) { + final total = _cachedContactsUnreadTotal + (count - previousCount); + _cachedContactsUnreadTotal = total < 0 ? 0 : total; + } _unreadStore.saveContactUnreadCount( Map.from(_contactUnreadCount), ); @@ -1126,7 +1131,10 @@ class MeshCoreConnector extends ChangeNotifier { void setChannelUnreadCount(int channelIndex, int count) { final channel = _findChannelByIndex(channelIndex); if (channel != null) { + final previousCount = channel.unreadCount; channel.unreadCount = count; + final total = _cachedChannelsUnreadTotal + (count - previousCount); + _cachedChannelsUnreadTotal = total < 0 ? 0 : total; unawaited( _channelStore.saveChannels( _channels.isNotEmpty ? _channels : _cachedChannels, diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 469f05fd..0bf147d4 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3162,5 +3162,103 @@ "qr_cameraPermissionDenied": "Достъпът до камерата е отказан.\nМоля, разрешете достъп до камерата в настройките.", "qr_cameraUnsupported": "Камерата не се поддържа на това устройство.", "qr_cameraStartFailed": "Камерата не можа да се стартира.\n{details}", - "imageMessages_downloadFailedWithError": "Моделът за изображения не можа да се изтегли: {error}" + "imageMessages_downloadFailedWithError": "Моделът за изображения не можа да се изтегли: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Скриване: скрит, докато не напуснете картата.", + "map_markerRemoveHint": "Премахване: остава скрит, докато не го възстановите от менюто за филтър.", + "map_markerRemoved": "Маркерът е премахнат", + "map_restoreRemovedMarkers": "Възстановяване на премахнатите маркери", + "map_restoreRemovedMarkersSubtitle": "{count} премахнати", + "map_markersRestored": "Възстановени маркери: {count}", + "map_setLocationConfirmTitle": "Задаване като ваша локация?", + "map_setLocationConfirmBody": "Вашият възел ще обявява тази позиция:\n{lat}, {lon}", + "map_setLocationAction": "Задай локация", + "map_locationSetSuccess": "Локацията на възела е обновена", + "map_locationSetFailed": "Устройството не потвърди новата локация. Опитайте отново.", + "map_poiClusterTitle": "{count} маркера тук", + "map_poiClusterSemantics": "{count} споделени маркера. Докоснете, за да ги видите.", + "map_youWithMarkers": "Вие и {count} маркера", + "map_sharedMarkerSemantics": "Споделен маркер: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Мащаб {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Изтеглянето е отменено. Кеширани плочки: {count}.", + "mapCache_tooManyTilesTitle": "Районът е твърде голям", + "mapCache_tooManyTiles": "Този район изисква {count} плочки, повече от лимита от {max}. Изберете по-малък район или по-малък максимален мащаб.", + "chat_clearChatConfirm": "Това изтрива всяко съобщение в този разговор от това устройство. Действието не може да бъде отменено.", + "channels_clearChatConfirm": "Това изтрива всяко съобщение в този канал от това устройство, включително получените изображения. Действието не може да бъде отменено.", + "channels_timeNow": "сега", + "channels_timeMinutes": "{minutes}м", + "channels_timeHours": "{hours}ч", + "channels_timeDays": "{days}д", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Неизвестен", + "pathMap_noSelfGpsFix": "Локалният възел няма GPS фиксиране", + "pathTrace_sendFailed": "Пътната трасировка не можа да бъде изпратена: {error}", + "losErrorNoInternet": "Данните за надморска височина изискват интернет връзка", + "losResultStale": "Остарял резултат: височината на антената е променена", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Зареждане на телеметрия…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Няма връзка с радио. Свържете се и опитайте отново.", + "settings_requiresConnection": "Свържете се с радио, за да използвате това", + "settings_txPowerInvalidRange": "Невалидна TX мощност (от {min} до {max} dBm)", + "settings_contactSettingsSaved": "Настройките на контакта са запазени", + "settings_batteryToggleHint": "Докоснете, за да превключите между процент и напрежение", + "settings_publicKeyCopyHint": "Копиране на публичния ключ", + "settings_locationClearHelper": "Оставете и двете полета празни, за да премахнете локацията си.", + "settings_locationCleared": "Локацията е премахната", + "settings_regionFetchDiscovering": "Търсене на близки ретранслатори…", + "settings_regionFetchProgress": "Запитване към ретранслатор {current} от {total}…", + "settings_regionFetchNoRepeaters": "Все още няма известни ретранслатори. Добавете ретранслатор като контакт или изчакайте някой да обяви присъствие, после опитайте отново.", + "settings_regionFetchNoneResponded": "Нито един близък ретранслатор не отговори. Приближете се до ретранслатор и опитайте отново.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Маршрутизиране", + "appSettings_imageMessagesSection": "Съобщения с изображения", + "appSettings_showApiKey": "Показване на API ключа", + "appSettings_hideApiKey": "Скриване на API ключа", + "translation_defaultModelName": "Модел", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Радиото е изключено", + "repeater_radioDisconnectedHint": "Свържете се отново с радиото, за да изпращате команди, да опреснявате или да запазвате промени.", + "repeater_cliSend": "Изпрати команда", + "repeater_cliCopyTranscript": "Копирай транскрипта", + "repeater_cliShareTranscript": "Сподели транскрипта", + "repeater_cliTranscriptCopied": "Транскриптът е копиран", + "repeater_cliClearHistoryConfirm": "Да се изчисти ли историята на командите? Действието не може да бъде отменено.", + "repeater_cliSearchCommands": "Търсене на команди", + "repeater_cliNoMatchingCommands": "Няма съвпадащи команди", + "debugLog_clearConfirm": "Да се изчистят ли всички записи в дневника? Действието не може да бъде отменено.", + "repeater_unsavedChangesTitle": "Незапазени промени", + "repeater_unsavedChangesMessage": "Имате промени, които не са запазени в ретранслатора.", + "repeater_discardChanges": "Отхвърли", + "repeater_actionSentNoReply": "{action}: командата е изпратена. Ретранслаторът не отговаря на тази команда.", + "repeater_invalidSettingValue": "{setting}: {value} не е валидна стойност", + "repeater_txPowerOutOfRange": "TX мощността {value} е извън диапазона (от {min} до {max} dBm)", + "repeater_prvKeyLengthError": "Частният ключ трябва да е точно {length} шестнадесетични знака", + "contacts_advertFailed": "Рекламата не можа да бъде изпратена", + "contacts_manageGroups": "Управление на групи", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Свързан с", + "usbChooseSerialPort": "Изберете сериен порт", + "neighbors_durationSeconds": "{seconds}с", + "neighbors_durationMinutes": "{minutes}м {seconds}с", + "neighbors_durationHours": "{hours}ч {minutes}м" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 29ca0dc4..ebd007b5 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3297,5 +3297,103 @@ "qr_cameraPermissionDenied": "Kamerazugriff verweigert.\nBitte aktivieren Sie den Kamerazugriff in den Einstellungen.", "qr_cameraUnsupported": "Kamera wird auf diesem Gerät nicht unterstützt.", "qr_cameraStartFailed": "Kamera konnte nicht gestartet werden.\n{details}", - "imageMessages_downloadFailedWithError": "Das Bildmodell konnte nicht heruntergeladen werden: {error}" + "imageMessages_downloadFailedWithError": "Das Bildmodell konnte nicht heruntergeladen werden: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Ausblenden: bleibt ausgeblendet, bis du die Karte verlässt.", + "map_markerRemoveHint": "Entfernen: bleibt ausgeblendet, bis du es über das Filtermenü wiederherstellst.", + "map_markerRemoved": "Marker entfernt", + "map_restoreRemovedMarkers": "Entfernte Marker wiederherstellen", + "map_restoreRemovedMarkersSubtitle": "{count} entfernt", + "map_markersRestored": "{count} Marker wiederhergestellt", + "map_setLocationConfirmTitle": "Als deinen Standort festlegen?", + "map_setLocationConfirmBody": "Dein Knoten wird diese Position bekannt geben:\n{lat}, {lon}", + "map_setLocationAction": "Standort festlegen", + "map_locationSetSuccess": "Knotenstandort aktualisiert", + "map_locationSetFailed": "Das Gerät hat den neuen Standort nicht bestätigt. Versuche es erneut.", + "map_poiClusterTitle": "{count} Marker hier", + "map_poiClusterSemantics": "{count} geteilte Marker. Tippen, um sie aufzulisten.", + "map_youWithMarkers": "Du und {count} Marker", + "map_sharedMarkerSemantics": "Geteilter Marker: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Download abgebrochen. {count} Kacheln im Cache.", + "mapCache_tooManyTilesTitle": "Bereich zu groß", + "mapCache_tooManyTiles": "Dieser Bereich benötigt {count} Kacheln, mehr als das Limit von {max}. Wähle einen kleineren Bereich oder verringere den maximalen Zoom.", + "chat_clearChatConfirm": "Dadurch werden alle Nachrichten dieser Unterhaltung von diesem Gerät gelöscht. Das kann nicht rückgängig gemacht werden.", + "channels_clearChatConfirm": "Dadurch werden alle Nachrichten dieses Kanals von diesem Gerät gelöscht, einschließlich empfangener Bilder. Das kann nicht rückgängig gemacht werden.", + "channels_timeNow": "jetzt", + "channels_timeMinutes": "{minutes} Min.", + "channels_timeHours": "{hours} Std.", + "channels_timeDays": "{days} T.", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Unbekannt", + "pathMap_noSelfGpsFix": "Lokaler Knoten hat keinen GPS-Fix", + "pathTrace_sendFailed": "Pfadverfolgung konnte nicht gesendet werden: {error}", + "losErrorNoInternet": "Für Höhendaten wird eine Internetverbindung benötigt", + "losResultStale": "Veraltet: Antennenhöhe wurde geändert", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Telemetrie wird geladen…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Nicht mit einem Funkgerät verbunden. Verbinde dich und versuche es erneut.", + "settings_requiresConnection": "Verbinde dich mit einem Funkgerät, um dies zu nutzen", + "settings_txPowerInvalidRange": "Ungültige Sendeleistung ({min} bis {max} dBm)", + "settings_contactSettingsSaved": "Kontakteinstellungen gespeichert", + "settings_batteryToggleHint": "Tippen, um zwischen Prozent und Spannung zu wechseln", + "settings_publicKeyCopyHint": "Öffentlichen Schlüssel kopieren", + "settings_locationClearHelper": "Lass beide Felder leer, um deinen Standort zu entfernen.", + "settings_locationCleared": "Standort entfernt", + "settings_regionFetchDiscovering": "Suche nach Repeatern in der Nähe…", + "settings_regionFetchProgress": "Frage Repeater {current} von {total} ab…", + "settings_regionFetchNoRepeaters": "Noch keine Repeater bekannt. Füge einen Repeater als Kontakt hinzu oder warte, bis einer sich ankündigt, und versuche es dann erneut.", + "settings_regionFetchNoneResponded": "Kein Repeater in der Nähe hat geantwortet. Gehe näher an einen Repeater heran und versuche es erneut.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Routing", + "appSettings_imageMessagesSection": "Bildnachrichten", + "appSettings_showApiKey": "API-Schlüssel anzeigen", + "appSettings_hideApiKey": "API-Schlüssel verbergen", + "translation_defaultModelName": "Modell", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Funkgerät getrennt", + "repeater_radioDisconnectedHint": "Verbinde dich erneut mit deinem Funkgerät, um Befehle zu senden, zu aktualisieren oder Änderungen zu speichern.", + "repeater_cliSend": "Befehl senden", + "repeater_cliCopyTranscript": "Protokoll kopieren", + "repeater_cliShareTranscript": "Protokoll teilen", + "repeater_cliTranscriptCopied": "Protokoll kopiert", + "repeater_cliClearHistoryConfirm": "Befehlsverlauf löschen? Das kann nicht rückgängig gemacht werden.", + "repeater_cliSearchCommands": "Befehle suchen", + "repeater_cliNoMatchingCommands": "Keine passenden Befehle", + "debugLog_clearConfirm": "Alle Protokolleinträge löschen? Das kann nicht rückgängig gemacht werden.", + "repeater_unsavedChangesTitle": "Ungespeicherte Änderungen", + "repeater_unsavedChangesMessage": "Es gibt Änderungen, die nicht im Repeater gespeichert wurden.", + "repeater_discardChanges": "Verwerfen", + "repeater_actionSentNoReply": "{action}: Befehl gesendet. Der Repeater antwortet auf diesen Befehl nicht.", + "repeater_invalidSettingValue": "{setting}: {value} ist ungültig", + "repeater_txPowerOutOfRange": "Sendeleistung {value} liegt außerhalb des Bereichs ({min} bis {max} dBm)", + "repeater_prvKeyLengthError": "Der private Schlüssel muss genau {length} Hex-Zeichen lang sein", + "contacts_advertFailed": "Advert konnte nicht gesendet werden", + "contacts_manageGroups": "Gruppen verwalten", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Verbunden mit", + "usbChooseSerialPort": "Serielle Schnittstelle wählen", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} Min. {seconds} s", + "neighbors_durationHours": "{hours} Std. {minutes} Min." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index caa51590..4f02a208 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3304,5 +3304,144 @@ "qr_cameraStartFailed": "Failed to start camera.\n{details}", "@qr_cameraStartFailed": {"placeholders": {"details": {"type": "String"}}}, "imageMessages_downloadFailedWithError": "The image model could not be downloaded: {error}", - "@imageMessages_downloadFailedWithError": {"placeholders": {"error": {"type": "String"}}} + "@imageMessages_downloadFailedWithError": {"placeholders": {"error": {"type": "String"}}}, + "map_nodeId": "ID", + "map_markerHideHint": "Hide: hidden until you leave the map.", + "map_markerRemoveHint": "Remove: stays hidden until you restore it from the filter menu.", + "map_markerRemoved": "Marker removed", + "map_restoreRemovedMarkers": "Restore removed markers", + "map_restoreRemovedMarkersSubtitle": "{count} removed", + "@map_restoreRemovedMarkersSubtitle": {"placeholders": {"count": {"type": "int"}}}, + "map_markersRestored": "Restored {count} markers", + "@map_markersRestored": {"placeholders": {"count": {"type": "int"}}}, + "map_setLocationConfirmTitle": "Set as your location?", + "map_setLocationConfirmBody": "Your node will advertise this position:\n{lat}, {lon}", + "@map_setLocationConfirmBody": {"placeholders": {"lat": {"type": "String"}, "lon": {"type": "String"}}}, + "map_setLocationAction": "Set location", + "map_locationSetSuccess": "Node location updated", + "map_locationSetFailed": "The device did not confirm the new location. Try again.", + "map_poiClusterTitle": "{count} markers here", + "@map_poiClusterTitle": {"placeholders": {"count": {"type": "int"}}}, + "map_poiClusterSemantics": "{count} shared markers. Tap to list them.", + "@map_poiClusterSemantics": {"placeholders": {"count": {"type": "int"}}}, + "map_youWithMarkers": "You and {count} markers", + "@map_youWithMarkers": {"placeholders": {"count": {"type": "int"}}}, + "map_sharedMarkerSemantics": "Shared marker: {label}", + "@map_sharedMarkerSemantics": {"placeholders": {"label": {"type": "String"}}}, + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "@map_nodeMarkerSemantics": {"placeholders": {"name": {"type": "String"}, "type": {"type": "String"}, "status": {"type": "String"}}}, + "mapCache_zoomLevel": "Zoom {zoom}", + "@mapCache_zoomLevel": {"placeholders": {"zoom": {"type": "int"}}}, + "mapCache_sizeBytes": "{size} B", + "@mapCache_sizeBytes": {"placeholders": {"size": {"type": "String"}}}, + "mapCache_sizeKilobytes": "{size} KB", + "@mapCache_sizeKilobytes": {"placeholders": {"size": {"type": "String"}}}, + "mapCache_sizeMegabytes": "{size} MB", + "@mapCache_sizeMegabytes": {"placeholders": {"size": {"type": "String"}}}, + "mapCache_sizeGigabytes": "{size} GB", + "@mapCache_sizeGigabytes": {"placeholders": {"size": {"type": "String"}}}, + "mapCache_downloadCancelled": "Download cancelled. Cached {count} tiles.", + "@mapCache_downloadCancelled": {"placeholders": {"count": {"type": "int"}}}, + "mapCache_tooManyTilesTitle": "Area too large", + "mapCache_tooManyTiles": "This area needs {count} tiles, more than the limit of {max}. Pick a smaller area or lower the maximum zoom.", + "@mapCache_tooManyTiles": {"placeholders": {"count": {"type": "int"}, "max": {"type": "int"}}}, + "chat_clearChatConfirm": "This erases every message in this conversation from this device. It cannot be undone.", + "channels_clearChatConfirm": "This erases every message in this channel from this device, including received images. It cannot be undone.", + "channels_timeNow": "now", + "channels_timeMinutes": "{minutes}m", + "@channels_timeMinutes": {"placeholders": {"minutes": {"type": "int"}}}, + "channels_timeHours": "{hours}h", + "@channels_timeHours": {"placeholders": {"hours": {"type": "int"}}}, + "channels_timeDays": "{days}d", + "@channels_timeDays": {"placeholders": {"days": {"type": "int"}}}, + "channels_indexChip": "CH {index}", + "@channels_indexChip": {"placeholders": {"index": {"type": "int"}}}, + "reaction_unknownSender": "Unknown", + "pathMap_noSelfGpsFix": "Local node has no GPS fix", + "pathTrace_sendFailed": "Could not send the path trace: {error}", + "@pathTrace_sendFailed": {"placeholders": {"error": {"type": "String"}}}, + "losErrorNoInternet": "Elevation data needs an internet connection", + "losResultStale": "Out of date: antenna height changed", + "losSnrValue": "{snr} dB", + "@losSnrValue": {"placeholders": {"snr": {"type": "String"}}}, + "losFrequencyValue": "{frequency} MHz", + "@losFrequencyValue": {"placeholders": {"frequency": {"type": "String"}}}, + "losKFactorValue": "k={kFactor}", + "@losKFactorValue": {"placeholders": {"kFactor": {"type": "String"}}}, + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Loading telemetry…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "@telemetry_axisValue": {"placeholders": {"x": {"type": "String"}, "y": {"type": "String"}, "z": {"type": "String"}}}, + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "@telemetry_colourValue": {"placeholders": {"red": {"type": "String"}, "green": {"type": "String"}, "blue": {"type": "String"}}}, + "telemetry_altitudeValueFeet": "{feet} ft", + "@telemetry_altitudeValueFeet": {"placeholders": {"feet": {"type": "String"}}}, + "telemetry_distanceValueFeet": "{feet} ft", + "@telemetry_distanceValueFeet": {"placeholders": {"feet": {"type": "String"}}}, + "settings_notConnectedError": "Not connected to a radio. Connect and try again.", + "settings_requiresConnection": "Connect to a radio to use this", + "settings_txPowerInvalidRange": "Invalid TX power ({min} to {max} dBm)", + "@settings_txPowerInvalidRange": {"placeholders": {"min": {"type": "int"}, "max": {"type": "int"}}}, + "settings_contactSettingsSaved": "Contact settings saved", + "settings_batteryToggleHint": "Tap to switch between percent and voltage", + "settings_publicKeyCopyHint": "Copy public key", + "settings_locationClearHelper": "Leave both fields empty to remove your location.", + "settings_locationCleared": "Location removed", + "settings_regionFetchDiscovering": "Looking for nearby repeaters…", + "settings_regionFetchProgress": "Asking repeater {current} of {total}…", + "@settings_regionFetchProgress": {"placeholders": {"current": {"type": "int"}, "total": {"type": "int"}}}, + "settings_regionFetchNoRepeaters": "No repeaters are known yet. Add a repeater as a contact or wait for one to advertise, then try again.", + "settings_regionFetchNoneResponded": "No nearby repeaters answered. Move closer to a repeater and try again.", + "appSettings_sourceSummary": "{label} - {description}", + "@appSettings_sourceSummary": {"placeholders": {"label": {"type": "String"}, "description": {"type": "String"}}}, + "appSettings_routingSection": "Routing", + "appSettings_imageMessagesSection": "Image messages", + "appSettings_showApiKey": "Show API key", + "appSettings_hideApiKey": "Hide API key", + "translation_defaultModelName": "Model", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "@translation_downloadProgressBytes": {"placeholders": {"fileName": {"type": "String"}, "current": {"type": "String"}}}, + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "@translation_downloadProgressTotal": {"placeholders": {"fileName": {"type": "String"}, "current": {"type": "String"}, "total": {"type": "String"}, "percent": {"type": "String"}}}, + "translation_downloadedModelDetails": "{size} MB • {source}", + "@translation_downloadedModelDetails": {"placeholders": {"size": {"type": "String"}, "source": {"type": "String"}}}, + "repeater_radioDisconnected": "Radio disconnected", + "repeater_radioDisconnectedHint": "Reconnect to your radio to send commands, refresh or save changes.", + "repeater_cliSend": "Send command", + "repeater_cliCopyTranscript": "Copy transcript", + "repeater_cliShareTranscript": "Share transcript", + "repeater_cliTranscriptCopied": "Transcript copied", + "repeater_cliClearHistoryConfirm": "Clear the command history? This cannot be undone.", + "repeater_cliSearchCommands": "Search commands", + "repeater_cliNoMatchingCommands": "No matching commands", + "debugLog_clearConfirm": "Clear all log entries? This cannot be undone.", + "repeater_unsavedChangesTitle": "Unsaved changes", + "repeater_unsavedChangesMessage": "You have changes that haven't been saved to the repeater.", + "repeater_discardChanges": "Discard", + "repeater_actionSentNoReply": "{action}: command sent. The repeater does not reply to this command.", + "@repeater_actionSentNoReply": {"placeholders": {"action": {"type": "String"}}}, + "repeater_invalidSettingValue": "{setting}: {value} is not valid", + "@repeater_invalidSettingValue": {"placeholders": {"setting": {"type": "String"}, "value": {"type": "String"}}}, + "repeater_txPowerOutOfRange": "TX power {value} is out of range ({min} to {max} dBm)", + "@repeater_txPowerOutOfRange": {"placeholders": {"value": {"type": "String"}, "min": {"type": "int"}, "max": {"type": "int"}}}, + "repeater_prvKeyLengthError": "Private key must be exactly {length} hex characters", + "@repeater_prvKeyLengthError": {"placeholders": {"length": {"type": "int"}}}, + "contacts_advertFailed": "Couldn't send advertisement", + "contacts_manageGroups": "Manage groups", + "community_shortId": "ID: {id}…", + "@community_shortId": {"placeholders": {"id": {"type": "String"}}}, + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Connected to", + "usbChooseSerialPort": "Choose serial port", + "neighbors_durationSeconds": "{seconds}s", + "@neighbors_durationSeconds": {"placeholders": {"seconds": {"type": "String"}}}, + "neighbors_durationMinutes": "{minutes}m {seconds}s", + "@neighbors_durationMinutes": {"placeholders": {"minutes": {"type": "int"}, "seconds": {"type": "String"}}}, + "neighbors_durationHours": "{hours}h {minutes}m", + "@neighbors_durationHours": {"placeholders": {"hours": {"type": "int"}, "minutes": {"type": "int"}}} } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 8dc61268..3b8e8a94 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3296,5 +3296,103 @@ "qr_cameraPermissionDenied": "Permiso de cámara denegado.\nActiva el acceso a la cámara en los ajustes.", "qr_cameraUnsupported": "Cámara no compatible con este dispositivo.", "qr_cameraStartFailed": "No se pudo iniciar la cámara.\n{details}", - "imageMessages_downloadFailedWithError": "No se pudo descargar el modelo de imagen: {error}" + "imageMessages_downloadFailedWithError": "No se pudo descargar el modelo de imagen: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Ocultar: permanece oculto hasta que salgas del mapa.", + "map_markerRemoveHint": "Eliminar: permanece oculto hasta que lo restaures desde el menú de filtros.", + "map_markerRemoved": "Marcador eliminado", + "map_restoreRemovedMarkers": "Restaurar marcadores eliminados", + "map_restoreRemovedMarkersSubtitle": "{count} eliminados", + "map_markersRestored": "{count} marcadores restaurados", + "map_setLocationConfirmTitle": "¿Establecer como tu ubicación?", + "map_setLocationConfirmBody": "Tu nodo anunciará esta posición:\n{lat}, {lon}", + "map_setLocationAction": "Establecer ubicación", + "map_locationSetSuccess": "Ubicación del nodo actualizada", + "map_locationSetFailed": "El dispositivo no confirmó la nueva ubicación. Inténtalo de nuevo.", + "map_poiClusterTitle": "{count} marcadores aquí", + "map_poiClusterSemantics": "{count} marcadores compartidos. Toca para verlos.", + "map_youWithMarkers": "Tú y {count} marcadores", + "map_sharedMarkerSemantics": "Marcador compartido: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Descarga cancelada. {count} teselas en caché.", + "mapCache_tooManyTilesTitle": "Área demasiado grande", + "mapCache_tooManyTiles": "Esta área necesita {count} teselas, más que el límite de {max}. Elige un área más pequeña o reduce el zoom máximo.", + "chat_clearChatConfirm": "Esto borra todos los mensajes de esta conversación de este dispositivo. No se puede deshacer.", + "channels_clearChatConfirm": "Esto borra todos los mensajes de este canal de este dispositivo, incluidas las imágenes recibidas. No se puede deshacer.", + "channels_timeNow": "ahora", + "channels_timeMinutes": "{minutes} min", + "channels_timeHours": "{hours} h", + "channels_timeDays": "{days} d", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Desconocido", + "pathMap_noSelfGpsFix": "El nodo local no tiene fijación GPS", + "pathTrace_sendFailed": "No se pudo enviar el trazado de ruta: {error}", + "losErrorNoInternet": "Los datos de elevación requieren conexión a internet", + "losResultStale": "Desactualizado: la altura de la antena cambió", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Cargando telemetría…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "No hay conexión con una radio. Conéctate e inténtalo de nuevo.", + "settings_requiresConnection": "Conéctate a una radio para usar esto", + "settings_txPowerInvalidRange": "Potencia TX inválida ({min} a {max} dBm)", + "settings_contactSettingsSaved": "Ajustes del contacto guardados", + "settings_batteryToggleHint": "Toca para alternar entre porcentaje y voltaje", + "settings_publicKeyCopyHint": "Copiar clave pública", + "settings_locationClearHelper": "Deja ambos campos vacíos para eliminar tu ubicación.", + "settings_locationCleared": "Ubicación eliminada", + "settings_regionFetchDiscovering": "Buscando repetidores cercanos…", + "settings_regionFetchProgress": "Consultando al repetidor {current} de {total}…", + "settings_regionFetchNoRepeaters": "Aún no se conoce ningún repetidor. Añade un repetidor como contacto o espera a que anuncie su presencia, e inténtalo de nuevo.", + "settings_regionFetchNoneResponded": "Ningún repetidor cercano respondió. Acércate a un repetidor e inténtalo de nuevo.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Enrutamiento", + "appSettings_imageMessagesSection": "Mensajes con imágenes", + "appSettings_showApiKey": "Mostrar clave de API", + "appSettings_hideApiKey": "Ocultar clave de API", + "translation_defaultModelName": "Modelo", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Radio desconectada", + "repeater_radioDisconnectedHint": "Vuelve a conectarte a tu radio para enviar comandos, actualizar o guardar cambios.", + "repeater_cliSend": "Enviar comando", + "repeater_cliCopyTranscript": "Copiar transcripción", + "repeater_cliShareTranscript": "Compartir transcripción", + "repeater_cliTranscriptCopied": "Transcripción copiada", + "repeater_cliClearHistoryConfirm": "¿Borrar el historial de comandos? No se puede deshacer.", + "repeater_cliSearchCommands": "Buscar comandos", + "repeater_cliNoMatchingCommands": "Ningún comando coincide", + "debugLog_clearConfirm": "¿Borrar todas las entradas del registro? No se puede deshacer.", + "repeater_unsavedChangesTitle": "Cambios sin guardar", + "repeater_unsavedChangesMessage": "Tienes cambios que no se han guardado en el repetidor.", + "repeater_discardChanges": "Descartar", + "repeater_actionSentNoReply": "{action}: comando enviado. El repetidor no responde a este comando.", + "repeater_invalidSettingValue": "{setting}: {value} no es válido", + "repeater_txPowerOutOfRange": "La potencia TX {value} está fuera de rango ({min} a {max} dBm)", + "repeater_prvKeyLengthError": "La clave privada debe tener exactamente {length} caracteres hexadecimales", + "contacts_advertFailed": "No se pudo enviar el anuncio", + "contacts_manageGroups": "Gestionar grupos", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Conectado a", + "usbChooseSerialPort": "Elegir puerto serie", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} min {seconds} s", + "neighbors_durationHours": "{hours} h {minutes} min" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 964eb772..8323736d 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3296,5 +3296,103 @@ "qr_cameraPermissionDenied": "Autorisation de la caméra refusée.\nVeuillez activer l'accès à la caméra dans les réglages.", "qr_cameraUnsupported": "Caméra non prise en charge sur cet appareil.", "qr_cameraStartFailed": "Échec du démarrage de la caméra.\n{details}", - "imageMessages_downloadFailedWithError": "Le modèle d'image n'a pas pu être téléchargé : {error}" + "imageMessages_downloadFailedWithError": "Le modèle d'image n'a pas pu être téléchargé : {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Masquer : masqué jusqu'à ce que vous quittiez la carte.", + "map_markerRemoveHint": "Supprimer : reste masqué jusqu'à sa restauration depuis le menu des filtres.", + "map_markerRemoved": "Marqueur supprimé", + "map_restoreRemovedMarkers": "Restaurer les marqueurs supprimés", + "map_restoreRemovedMarkersSubtitle": "{count} supprimé(s)", + "map_markersRestored": "{count} marqueurs restaurés", + "map_setLocationConfirmTitle": "Définir comme votre position ?", + "map_setLocationConfirmBody": "Votre nœud annoncera cette position :\n{lat}, {lon}", + "map_setLocationAction": "Définir la position", + "map_locationSetSuccess": "Position du nœud mise à jour", + "map_locationSetFailed": "L'appareil n'a pas confirmé la nouvelle position. Réessayez.", + "map_poiClusterTitle": "{count} marqueurs ici", + "map_poiClusterSemantics": "{count} marqueurs partagés. Touchez pour les lister.", + "map_youWithMarkers": "Vous et {count} marqueurs", + "map_sharedMarkerSemantics": "Marqueur partagé : {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} o", + "mapCache_sizeKilobytes": "{size} Ko", + "mapCache_sizeMegabytes": "{size} Mo", + "mapCache_sizeGigabytes": "{size} Go", + "mapCache_downloadCancelled": "Téléchargement annulé. {count} tuiles mises en cache.", + "mapCache_tooManyTilesTitle": "Zone trop grande", + "mapCache_tooManyTiles": "Cette zone nécessite {count} tuiles, soit plus que la limite de {max}. Choisissez une zone plus petite ou réduisez le zoom maximal.", + "chat_clearChatConfirm": "Cela efface tous les messages de cette conversation sur cet appareil. Action irréversible.", + "channels_clearChatConfirm": "Cela efface tous les messages de ce canal sur cet appareil, y compris les images reçues. Action irréversible.", + "channels_timeNow": "maint.", + "channels_timeMinutes": "{minutes} min", + "channels_timeHours": "{hours} h", + "channels_timeDays": "{days} j", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Inconnu", + "pathMap_noSelfGpsFix": "Le nœud local n'a pas de position GPS", + "pathTrace_sendFailed": "Impossible d'envoyer la trace du chemin : {error}", + "losErrorNoInternet": "Les données d'altitude nécessitent une connexion Internet", + "losResultStale": "Obsolète : la hauteur de l'antenne a changé", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Chargement de la télémétrie…", + "telemetry_axisValue": "X : {x}, Y : {y}, Z : {z}", + "telemetry_colourValue": "R : {red}, V : {green}, B : {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Non connecté à une radio. Connectez-vous et réessayez.", + "settings_requiresConnection": "Connectez-vous à une radio pour l'utiliser", + "settings_txPowerInvalidRange": "Puissance TX invalide ({min} à {max} dBm)", + "settings_contactSettingsSaved": "Paramètres du contact enregistrés", + "settings_batteryToggleHint": "Touchez pour basculer entre pourcentage et tension", + "settings_publicKeyCopyHint": "Copier la clé publique", + "settings_locationClearHelper": "Laissez les deux champs vides pour supprimer votre position.", + "settings_locationCleared": "Position supprimée", + "settings_regionFetchDiscovering": "Recherche de répéteurs à proximité…", + "settings_regionFetchProgress": "Interrogation du répéteur {current} sur {total}…", + "settings_regionFetchNoRepeaters": "Aucun répéteur connu pour le moment. Ajoutez un répéteur comme contact ou attendez qu'un répéteur s'annonce, puis réessayez.", + "settings_regionFetchNoneResponded": "Aucun répéteur à proximité n'a répondu. Rapprochez-vous d'un répéteur et réessayez.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Routage", + "appSettings_imageMessagesSection": "Messages image", + "appSettings_showApiKey": "Afficher la clé API", + "appSettings_hideApiKey": "Masquer la clé API", + "translation_defaultModelName": "Modèle", + "translation_downloadProgressBytes": "{fileName} : {current} Mo", + "translation_downloadProgressTotal": "{fileName} : {current} / {total} Mo ({percent} %)", + "translation_downloadedModelDetails": "{size} Mo • {source}", + "repeater_radioDisconnected": "Radio déconnectée", + "repeater_radioDisconnectedHint": "Reconnectez-vous à votre radio pour envoyer des commandes, actualiser ou enregistrer les modifications.", + "repeater_cliSend": "Envoyer la commande", + "repeater_cliCopyTranscript": "Copier la transcription", + "repeater_cliShareTranscript": "Partager la transcription", + "repeater_cliTranscriptCopied": "Transcription copiée", + "repeater_cliClearHistoryConfirm": "Effacer l'historique des commandes ? Action irréversible.", + "repeater_cliSearchCommands": "Rechercher des commandes", + "repeater_cliNoMatchingCommands": "Aucune commande correspondante", + "debugLog_clearConfirm": "Effacer toutes les entrées du journal ? Action irréversible.", + "repeater_unsavedChangesTitle": "Modifications non enregistrées", + "repeater_unsavedChangesMessage": "Vous avez des modifications non enregistrées sur le répéteur.", + "repeater_discardChanges": "Abandonner", + "repeater_actionSentNoReply": "{action} : commande envoyée. Le répéteur ne répond pas à cette commande.", + "repeater_invalidSettingValue": "{setting} : {value} n'est pas valide", + "repeater_txPowerOutOfRange": "Puissance TX {value} hors plage ({min} à {max} dBm)", + "repeater_prvKeyLengthError": "La clé privée doit comporter exactement {length} caractères hexadécimaux", + "contacts_advertFailed": "Impossible d'envoyer l'annonce", + "contacts_manageGroups": "Gérer les groupes", + "community_shortId": "ID : {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Connecté à", + "usbChooseSerialPort": "Choisir le port série", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} min {seconds} s", + "neighbors_durationHours": "{hours} h {minutes} min" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index cb85933b..dbebcfd0 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3201,5 +3201,103 @@ "qr_cameraPermissionDenied": "Kamera-engedély megtagadva.\nEngedélyezze a kamera hozzáférést a beállításokban.", "qr_cameraUnsupported": "A kamera nem támogatott ezen az eszközön.", "qr_cameraStartFailed": "A kamera indítása sikertelen.\n{details}", - "imageMessages_downloadFailedWithError": "A képmodell letöltése sikertelen: {error}" + "imageMessages_downloadFailedWithError": "A képmodell letöltése sikertelen: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Elrejtés: a térkép elhagyásáig rejtve marad.", + "map_markerRemoveHint": "Eltávolítás: a szűrőmenüből való visszaállításig rejtve marad.", + "map_markerRemoved": "Jelölő eltávolítva", + "map_restoreRemovedMarkers": "Eltávolított jelölők visszaállítása", + "map_restoreRemovedMarkersSubtitle": "{count} eltávolítva", + "map_markersRestored": "{count} jelölő visszaállítva", + "map_setLocationConfirmTitle": "Beállítja saját helyzetként?", + "map_setLocationConfirmBody": "A csomópont ezt a pozíciót fogja hirdetni:\n{lat}, {lon}", + "map_setLocationAction": "Helyzet beállítása", + "map_locationSetSuccess": "A csomópont helyzete frissítve", + "map_locationSetFailed": "Az eszköz nem erősítette meg az új helyzetet. Próbálja újra.", + "map_poiClusterTitle": "{count} jelölő itt", + "map_poiClusterSemantics": "{count} megosztott jelölő. Koppintson a listázáshoz.", + "map_youWithMarkers": "Ön és {count} jelölő", + "map_sharedMarkerSemantics": "Megosztott jelölő: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Nagyítás: {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "A letöltés megszakítva. {count} csempe gyorsítótárazva.", + "mapCache_tooManyTilesTitle": "Túl nagy terület", + "mapCache_tooManyTiles": "Ehhez a területhez {count} csempe kell, ami meghaladja a {max} korlátot. Válasszon kisebb területet, vagy csökkentse a maximális nagyítást.", + "chat_clearChatConfirm": "Ez törli a beszélgetés összes üzenetét erről az eszközről. A művelet nem vonható vissza.", + "channels_clearChatConfirm": "Ez törli a csatorna összes üzenetét erről az eszközről, a fogadott képekkel együtt. A művelet nem vonható vissza.", + "channels_timeNow": "most", + "channels_timeMinutes": "{minutes} p", + "channels_timeHours": "{hours} ó", + "channels_timeDays": "{days} n", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Ismeretlen", + "pathMap_noSelfGpsFix": "A helyi csomópontnak nincs GPS-jelzése", + "pathTrace_sendFailed": "Nem sikerült elküldeni az útvonalkövetést: {error}", + "losErrorNoInternet": "A magassági adatokhoz internetkapcsolat szükséges", + "losResultStale": "Elavult: az antennamagasság megváltozott", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Telemetria betöltése…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Nincs kapcsolat rádióval. Csatlakozzon, és próbálja újra.", + "settings_requiresConnection": "A használathoz csatlakozzon egy rádióhoz", + "settings_txPowerInvalidRange": "Érvénytelen TX teljesítmény ({min} – {max} dBm)", + "settings_contactSettingsSaved": "Kapcsolatbeállítások mentve", + "settings_batteryToggleHint": "Koppintson a százalék és a feszültség közötti váltáshoz", + "settings_publicKeyCopyHint": "Nyilvános kulcs másolása", + "settings_locationClearHelper": "A helyzet törléséhez hagyja üresen mindkét mezőt.", + "settings_locationCleared": "Helyzet eltávolítva", + "settings_regionFetchDiscovering": "Közeli átjátszók keresése…", + "settings_regionFetchProgress": "{current}. átjátszó lekérdezése ({total} közül)…", + "settings_regionFetchNoRepeaters": "Még nem ismert egyetlen átjátszó sem. Adjon hozzá egy átjátszót kapcsolatként, vagy várja meg, amíg egy hirdet, majd próbálja újra.", + "settings_regionFetchNoneResponded": "Egyik közeli átjátszó sem válaszolt. Menjen közelebb egy átjátszóhoz, és próbálja újra.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Útválasztás", + "appSettings_imageMessagesSection": "Képüzenetek", + "appSettings_showApiKey": "API-kulcs megjelenítése", + "appSettings_hideApiKey": "API-kulcs elrejtése", + "translation_defaultModelName": "Modell", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "A rádió lecsatlakozott", + "repeater_radioDisconnectedHint": "Csatlakozzon újra a rádióhoz parancsok küldéséhez, frissítéshez vagy a módosítások mentéséhez.", + "repeater_cliSend": "Parancs küldése", + "repeater_cliCopyTranscript": "Átirat másolása", + "repeater_cliShareTranscript": "Átirat megosztása", + "repeater_cliTranscriptCopied": "Átirat másolva", + "repeater_cliClearHistoryConfirm": "Törli a parancselőzményeket? A művelet nem vonható vissza.", + "repeater_cliSearchCommands": "Parancsok keresése", + "repeater_cliNoMatchingCommands": "Nincs egyező parancs", + "debugLog_clearConfirm": "Törli az összes naplóbejegyzést? A művelet nem vonható vissza.", + "repeater_unsavedChangesTitle": "Nem mentett módosítások", + "repeater_unsavedChangesMessage": "Vannak módosítások, amelyek nincsenek elmentve az átjátszóra.", + "repeater_discardChanges": "Elvetés", + "repeater_actionSentNoReply": "{action}: parancs elküldve. Az átjátszó nem válaszol erre a parancsra.", + "repeater_invalidSettingValue": "{setting}: {value} érvénytelen", + "repeater_txPowerOutOfRange": "A(z) {value} TX teljesítmény tartományon kívül van ({min} – {max} dBm)", + "repeater_prvKeyLengthError": "A privát kulcsnak pontosan {length} hexadecimális karakterből kell állnia", + "contacts_advertFailed": "Nem sikerült elküldeni a hirdetést", + "contacts_manageGroups": "Csoportok kezelése", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Csatlakozva:", + "usbChooseSerialPort": "Soros port kiválasztása", + "neighbors_durationSeconds": "{seconds} mp", + "neighbors_durationMinutes": "{minutes} p {seconds} mp", + "neighbors_durationHours": "{hours} ó {minutes} p" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index e76b8132..5bc6ff80 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3296,5 +3296,103 @@ "qr_cameraPermissionDenied": "Permesso della fotocamera negato.\nAbilita l'accesso alla fotocamera nelle impostazioni.", "qr_cameraUnsupported": "Fotocamera non supportata su questo dispositivo.", "qr_cameraStartFailed": "Avvio della fotocamera non riuscito.\n{details}", - "imageMessages_downloadFailedWithError": "Impossibile scaricare il modello di immagine: {error}" + "imageMessages_downloadFailedWithError": "Impossibile scaricare il modello di immagine: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Nascondi: resta nascosto finché non lasci la mappa.", + "map_markerRemoveHint": "Rimuovi: resta nascosto finché non lo ripristini dal menu dei filtri.", + "map_markerRemoved": "Segnaposto rimosso", + "map_restoreRemovedMarkers": "Ripristina segnaposti rimossi", + "map_restoreRemovedMarkersSubtitle": "{count} rimossi", + "map_markersRestored": "{count} segnaposti ripristinati", + "map_setLocationConfirmTitle": "Impostare come tua posizione?", + "map_setLocationConfirmBody": "Il tuo nodo annuncerà questa posizione:\n{lat}, {lon}", + "map_setLocationAction": "Imposta posizione", + "map_locationSetSuccess": "Posizione del nodo aggiornata", + "map_locationSetFailed": "Il dispositivo non ha confermato la nuova posizione. Riprova.", + "map_poiClusterTitle": "{count} segnaposti qui", + "map_poiClusterSemantics": "{count} segnaposti condivisi. Tocca per elencarli.", + "map_youWithMarkers": "Tu e {count} segnaposti", + "map_sharedMarkerSemantics": "Segnaposto condiviso: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Download annullato. {count} tile salvate nella cache.", + "mapCache_tooManyTilesTitle": "Area troppo grande", + "mapCache_tooManyTiles": "Quest'area richiede {count} tile, più del limite di {max}. Scegli un'area più piccola o riduci lo zoom massimo.", + "chat_clearChatConfirm": "Questo cancella tutti i messaggi di questa conversazione da questo dispositivo. Non può essere annullato.", + "channels_clearChatConfirm": "Questo cancella tutti i messaggi di questo canale da questo dispositivo, comprese le immagini ricevute. Non può essere annullato.", + "channels_timeNow": "ora", + "channels_timeMinutes": "{minutes} min", + "channels_timeHours": "{hours} h", + "channels_timeDays": "{days} g", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Sconosciuto", + "pathMap_noSelfGpsFix": "Il nodo locale non ha un fix GPS", + "pathTrace_sendFailed": "Impossibile inviare il tracciamento del percorso: {error}", + "losErrorNoInternet": "I dati di altitudine richiedono una connessione a Internet", + "losResultStale": "Non aggiornato: l'altezza dell'antenna è cambiata", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Caricamento della telemetria…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Non connesso a una radio. Connettiti e riprova.", + "settings_requiresConnection": "Connettiti a una radio per usarlo", + "settings_txPowerInvalidRange": "Potenza TX non valida ({min} - {max} dBm)", + "settings_contactSettingsSaved": "Impostazioni del contatto salvate", + "settings_batteryToggleHint": "Tocca per passare tra percentuale e tensione", + "settings_publicKeyCopyHint": "Copia chiave pubblica", + "settings_locationClearHelper": "Lascia vuoti entrambi i campi per rimuovere la tua posizione.", + "settings_locationCleared": "Posizione rimossa", + "settings_regionFetchDiscovering": "Ricerca di ripetitori vicini…", + "settings_regionFetchProgress": "Interrogazione del ripetitore {current} di {total}…", + "settings_regionFetchNoRepeaters": "Nessun ripetitore noto per ora. Aggiungi un ripetitore come contatto o attendi che ne annunci uno, poi riprova.", + "settings_regionFetchNoneResponded": "Nessun ripetitore vicino ha risposto. Avvicinati a un ripetitore e riprova.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Instradamento", + "appSettings_imageMessagesSection": "Messaggi immagine", + "appSettings_showApiKey": "Mostra chiave API", + "appSettings_hideApiKey": "Nascondi chiave API", + "translation_defaultModelName": "Modello", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Radio disconnessa", + "repeater_radioDisconnectedHint": "Riconnettiti alla radio per inviare comandi, aggiornare o salvare le modifiche.", + "repeater_cliSend": "Invia comando", + "repeater_cliCopyTranscript": "Copia trascrizione", + "repeater_cliShareTranscript": "Condividi trascrizione", + "repeater_cliTranscriptCopied": "Trascrizione copiata", + "repeater_cliClearHistoryConfirm": "Cancellare la cronologia dei comandi? Non può essere annullato.", + "repeater_cliSearchCommands": "Cerca comandi", + "repeater_cliNoMatchingCommands": "Nessun comando corrispondente", + "debugLog_clearConfirm": "Cancellare tutte le voci del registro? Non può essere annullato.", + "repeater_unsavedChangesTitle": "Modifiche non salvate", + "repeater_unsavedChangesMessage": "Hai modifiche non salvate sul ripetitore.", + "repeater_discardChanges": "Scarta", + "repeater_actionSentNoReply": "{action}: comando inviato. Il ripetitore non risponde a questo comando.", + "repeater_invalidSettingValue": "{setting}: {value} non è valido", + "repeater_txPowerOutOfRange": "Potenza TX {value} fuori intervallo ({min} - {max} dBm)", + "repeater_prvKeyLengthError": "La chiave privata deve essere di esattamente {length} caratteri esadecimali", + "contacts_advertFailed": "Impossibile inviare l'annuncio", + "contacts_manageGroups": "Gestisci gruppi", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Connesso a", + "usbChooseSerialPort": "Scegli porta seriale", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} min {seconds} s", + "neighbors_durationHours": "{hours} h {minutes} min" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 0e11366f..f4fd5e12 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -3296,5 +3296,103 @@ "qr_cameraPermissionDenied": "カメラの権限が拒否されました。\n設定でカメラへのアクセスを有効にしてください。", "qr_cameraUnsupported": "この端末ではカメラがサポートされていません。", "qr_cameraStartFailed": "カメラを起動できませんでした。\n{details}", - "imageMessages_downloadFailedWithError": "画像モデルをダウンロードできませんでした:{error}" + "imageMessages_downloadFailedWithError": "画像モデルをダウンロードできませんでした:{error}", + "map_nodeId": "ID", + "map_markerHideHint": "非表示:マップを離れるまで非表示になります。", + "map_markerRemoveHint": "削除:フィルターメニューから復元するまで非表示のままです。", + "map_markerRemoved": "マーカーを削除しました", + "map_restoreRemovedMarkers": "削除したマーカーを復元", + "map_restoreRemovedMarkersSubtitle": "{count}件削除済み", + "map_markersRestored": "{count}件のマーカーを復元しました", + "map_setLocationConfirmTitle": "この位置を自分の位置に設定しますか?", + "map_setLocationConfirmBody": "ノードは次の位置をアドバートします:\n{lat}, {lon}", + "map_setLocationAction": "位置を設定", + "map_locationSetSuccess": "ノードの位置を更新しました", + "map_locationSetFailed": "デバイスが新しい位置を確認しませんでした。もう一度お試しください。", + "map_poiClusterTitle": "ここに{count}件のマーカー", + "map_poiClusterSemantics": "共有マーカー{count}件。タップして一覧を表示します。", + "map_youWithMarkers": "自分と{count}件のマーカー", + "map_sharedMarkerSemantics": "共有マーカー: {label}", + "map_nodeMarkerSemantics": "{name}、{type}、{status}", + "mapCache_zoomLevel": "ズーム {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "ダウンロードをキャンセルしました。{count}枚のタイルをキャッシュしました。", + "mapCache_tooManyTilesTitle": "エリアが大きすぎます", + "mapCache_tooManyTiles": "このエリアには{count}枚のタイルが必要で、上限の{max}枚を超えています。より小さいエリアを選ぶか、最大ズームを下げてください。", + "chat_clearChatConfirm": "この会話のすべてのメッセージをこのデバイスから消去します。元に戻せません。", + "channels_clearChatConfirm": "このチャンネルのすべてのメッセージを、受信した画像も含めてこのデバイスから消去します。元に戻せません。", + "channels_timeNow": "今", + "channels_timeMinutes": "{minutes}分", + "channels_timeHours": "{hours}時間", + "channels_timeDays": "{days}日", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "不明", + "pathMap_noSelfGpsFix": "ローカルノードにGPS測位がありません", + "pathTrace_sendFailed": "パストレースを送信できませんでした: {error}", + "losErrorNoInternet": "標高データにはインターネット接続が必要です", + "losResultStale": "古い結果: アンテナ高が変更されました", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "テレメトリを読み込み中…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "無線機に接続されていません。接続してからもう一度お試しください。", + "settings_requiresConnection": "使用するには無線機に接続してください", + "settings_txPowerInvalidRange": "TX出力が無効です({min}~{max} dBm)", + "settings_contactSettingsSaved": "連絡先設定を保存しました", + "settings_batteryToggleHint": "タップでパーセントと電圧を切り替え", + "settings_publicKeyCopyHint": "公開鍵をコピー", + "settings_locationClearHelper": "位置情報を削除するには、両方の欄を空にしてください。", + "settings_locationCleared": "位置情報を削除しました", + "settings_regionFetchDiscovering": "近くのリピータを検索中…", + "settings_regionFetchProgress": "リピータ {current}/{total} に問い合わせ中…", + "settings_regionFetchNoRepeaters": "既知のリピータがまだありません。リピータを連絡先に追加するか、アドバートを待ってからもう一度お試しください。", + "settings_regionFetchNoneResponded": "近くのリピータから応答がありませんでした。リピータに近づいてもう一度お試しください。", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "ルーティング", + "appSettings_imageMessagesSection": "画像メッセージ", + "appSettings_showApiKey": "APIキーを表示", + "appSettings_hideApiKey": "APIキーを非表示", + "translation_defaultModelName": "モデル", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "無線機が切断されました", + "repeater_radioDisconnectedHint": "コマンドの送信、更新、変更の保存を行うには、無線機に再接続してください。", + "repeater_cliSend": "コマンドを送信", + "repeater_cliCopyTranscript": "履歴をコピー", + "repeater_cliShareTranscript": "履歴を共有", + "repeater_cliTranscriptCopied": "履歴をコピーしました", + "repeater_cliClearHistoryConfirm": "コマンド履歴を消去しますか?元に戻せません。", + "repeater_cliSearchCommands": "コマンドを検索", + "repeater_cliNoMatchingCommands": "一致するコマンドがありません", + "debugLog_clearConfirm": "すべてのログを消去しますか?元に戻せません。", + "repeater_unsavedChangesTitle": "未保存の変更", + "repeater_unsavedChangesMessage": "リピータに保存されていない変更があります。", + "repeater_discardChanges": "破棄", + "repeater_actionSentNoReply": "{action}: コマンドを送信しました。リピータはこのコマンドに応答しません。", + "repeater_invalidSettingValue": "{setting}: {value}は無効です", + "repeater_txPowerOutOfRange": "TX出力 {value} は範囲外です({min}~{max} dBm)", + "repeater_prvKeyLengthError": "秘密鍵は16進数でちょうど{length}文字である必要があります", + "contacts_advertFailed": "アドバートを送信できませんでした", + "contacts_manageGroups": "グループを管理", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "接続先", + "usbChooseSerialPort": "シリアルポートを選択", + "neighbors_durationSeconds": "{seconds}秒", + "neighbors_durationMinutes": "{minutes}分{seconds}秒", + "neighbors_durationHours": "{hours}時間{minutes}分" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index bbcde8f0..33414974 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3296,5 +3296,103 @@ "qr_cameraPermissionDenied": "카메라 권한이 거부되었습니다.\n설정에서 카메라 접근을 허용해 주세요.", "qr_cameraUnsupported": "이 기기는 카메라를 지원하지 않습니다.", "qr_cameraStartFailed": "카메라를 시작하지 못했습니다.\n{details}", - "imageMessages_downloadFailedWithError": "이미지 모델을 다운로드하지 못했습니다: {error}" + "imageMessages_downloadFailedWithError": "이미지 모델을 다운로드하지 못했습니다: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "숨기기: 지도를 벗어날 때까지 숨겨집니다.", + "map_markerRemoveHint": "삭제: 필터 메뉴에서 복원하기 전까지 숨겨진 상태로 유지됩니다.", + "map_markerRemoved": "마커를 삭제했습니다", + "map_restoreRemovedMarkers": "삭제한 마커 복원", + "map_restoreRemovedMarkersSubtitle": "{count}개 삭제됨", + "map_markersRestored": "마커 {count}개를 복원했습니다", + "map_setLocationConfirmTitle": "내 위치로 설정할까요?", + "map_setLocationConfirmBody": "노드가 다음 위치를 어드버트합니다:\n{lat}, {lon}", + "map_setLocationAction": "위치 설정", + "map_locationSetSuccess": "노드 위치를 업데이트했습니다", + "map_locationSetFailed": "장치가 새 위치를 확인하지 않았습니다. 다시 시도하세요.", + "map_poiClusterTitle": "여기에 마커 {count}개", + "map_poiClusterSemantics": "공유 마커 {count}개. 탭하여 목록을 확인하세요.", + "map_youWithMarkers": "나와 마커 {count}개", + "map_sharedMarkerSemantics": "공유 마커: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "줌 {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "다운로드가 취소되었습니다. 타일 {count}개를 캐시했습니다.", + "mapCache_tooManyTilesTitle": "영역이 너무 큽니다", + "mapCache_tooManyTiles": "이 영역에는 타일 {count}개가 필요하며 제한인 {max}개를 초과합니다. 더 작은 영역을 선택하거나 최대 줌을 낮추세요.", + "chat_clearChatConfirm": "이 대화의 모든 메시지를 이 기기에서 삭제합니다. 되돌릴 수 없습니다.", + "channels_clearChatConfirm": "받은 이미지를 포함해 이 채널의 모든 메시지를 이 기기에서 삭제합니다. 되돌릴 수 없습니다.", + "channels_timeNow": "지금", + "channels_timeMinutes": "{minutes}분", + "channels_timeHours": "{hours}시간", + "channels_timeDays": "{days}일", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "알 수 없음", + "pathMap_noSelfGpsFix": "로컬 노드에 GPS 위치가 없습니다", + "pathTrace_sendFailed": "경로 추적을 보낼 수 없습니다: {error}", + "losErrorNoInternet": "고도 데이터에는 인터넷 연결이 필요합니다", + "losResultStale": "오래된 결과: 안테나 높이가 변경되었습니다", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "텔레메트리 불러오는 중…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "무전기에 연결되어 있지 않습니다. 연결한 후 다시 시도하세요.", + "settings_requiresConnection": "사용하려면 무전기에 연결하세요", + "settings_txPowerInvalidRange": "잘못된 TX 출력입니다({min}~{max} dBm)", + "settings_contactSettingsSaved": "연락처 설정을 저장했습니다", + "settings_batteryToggleHint": "탭하여 퍼센트와 전압 전환", + "settings_publicKeyCopyHint": "공개 키 복사", + "settings_locationClearHelper": "위치를 삭제하려면 두 입력란을 모두 비워 두세요.", + "settings_locationCleared": "위치를 삭제했습니다", + "settings_regionFetchDiscovering": "주변 리피터를 찾는 중…", + "settings_regionFetchProgress": "리피터 {current}/{total}에 요청하는 중…", + "settings_regionFetchNoRepeaters": "알려진 리피터가 아직 없습니다. 리피터를 연락처로 추가하거나 어드버트를 기다린 후 다시 시도하세요.", + "settings_regionFetchNoneResponded": "응답한 주변 리피터가 없습니다. 리피터에 더 가까이 이동한 후 다시 시도하세요.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "라우팅", + "appSettings_imageMessagesSection": "이미지 메시지", + "appSettings_showApiKey": "API 키 표시", + "appSettings_hideApiKey": "API 키 숨기기", + "translation_defaultModelName": "모델", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "무전기 연결 끊김", + "repeater_radioDisconnectedHint": "명령을 보내거나 새로고침 또는 변경 사항을 저장하려면 무전기에 다시 연결하세요.", + "repeater_cliSend": "명령 보내기", + "repeater_cliCopyTranscript": "기록 복사", + "repeater_cliShareTranscript": "기록 공유", + "repeater_cliTranscriptCopied": "기록을 복사했습니다", + "repeater_cliClearHistoryConfirm": "명령 기록을 지울까요? 되돌릴 수 없습니다.", + "repeater_cliSearchCommands": "명령 검색", + "repeater_cliNoMatchingCommands": "일치하는 명령이 없습니다", + "debugLog_clearConfirm": "모든 로그 항목을 지울까요? 되돌릴 수 없습니다.", + "repeater_unsavedChangesTitle": "저장하지 않은 변경 사항", + "repeater_unsavedChangesMessage": "리피터에 저장되지 않은 변경 사항이 있습니다.", + "repeater_discardChanges": "취소", + "repeater_actionSentNoReply": "{action}: 명령을 보냈습니다. 리피터는 이 명령에 응답하지 않습니다.", + "repeater_invalidSettingValue": "{setting}: {value}은(는) 올바르지 않습니다", + "repeater_txPowerOutOfRange": "TX 출력 {value}이(가) 범위를 벗어났습니다({min}~{max} dBm)", + "repeater_prvKeyLengthError": "개인 키는 정확히 16진수 {length}자여야 합니다", + "contacts_advertFailed": "어드버트를 보낼 수 없습니다", + "contacts_manageGroups": "그룹 관리", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "연결 대상", + "usbChooseSerialPort": "시리얼 포트 선택", + "neighbors_durationSeconds": "{seconds}초", + "neighbors_durationMinutes": "{minutes}분 {seconds}초", + "neighbors_durationHours": "{hours}시간 {minutes}분" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 4b1af121..64af168c 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -9757,6 +9757,599 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'The image model could not be downloaded: {error}'** String imageMessages_downloadFailedWithError(String error); + + /// No description provided for @map_nodeId. + /// + /// In en, this message translates to: + /// **'ID'** + String get map_nodeId; + + /// No description provided for @map_markerHideHint. + /// + /// In en, this message translates to: + /// **'Hide: hidden until you leave the map.'** + String get map_markerHideHint; + + /// No description provided for @map_markerRemoveHint. + /// + /// In en, this message translates to: + /// **'Remove: stays hidden until you restore it from the filter menu.'** + String get map_markerRemoveHint; + + /// No description provided for @map_markerRemoved. + /// + /// In en, this message translates to: + /// **'Marker removed'** + String get map_markerRemoved; + + /// No description provided for @map_restoreRemovedMarkers. + /// + /// In en, this message translates to: + /// **'Restore removed markers'** + String get map_restoreRemovedMarkers; + + /// No description provided for @map_restoreRemovedMarkersSubtitle. + /// + /// In en, this message translates to: + /// **'{count} removed'** + String map_restoreRemovedMarkersSubtitle(int count); + + /// No description provided for @map_markersRestored. + /// + /// In en, this message translates to: + /// **'Restored {count} markers'** + String map_markersRestored(int count); + + /// No description provided for @map_setLocationConfirmTitle. + /// + /// In en, this message translates to: + /// **'Set as your location?'** + String get map_setLocationConfirmTitle; + + /// No description provided for @map_setLocationConfirmBody. + /// + /// In en, this message translates to: + /// **'Your node will advertise this position:\n{lat}, {lon}'** + String map_setLocationConfirmBody(String lat, String lon); + + /// No description provided for @map_setLocationAction. + /// + /// In en, this message translates to: + /// **'Set location'** + String get map_setLocationAction; + + /// No description provided for @map_locationSetSuccess. + /// + /// In en, this message translates to: + /// **'Node location updated'** + String get map_locationSetSuccess; + + /// No description provided for @map_locationSetFailed. + /// + /// In en, this message translates to: + /// **'The device did not confirm the new location. Try again.'** + String get map_locationSetFailed; + + /// No description provided for @map_poiClusterTitle. + /// + /// In en, this message translates to: + /// **'{count} markers here'** + String map_poiClusterTitle(int count); + + /// No description provided for @map_poiClusterSemantics. + /// + /// In en, this message translates to: + /// **'{count} shared markers. Tap to list them.'** + String map_poiClusterSemantics(int count); + + /// No description provided for @map_youWithMarkers. + /// + /// In en, this message translates to: + /// **'You and {count} markers'** + String map_youWithMarkers(int count); + + /// No description provided for @map_sharedMarkerSemantics. + /// + /// In en, this message translates to: + /// **'Shared marker: {label}'** + String map_sharedMarkerSemantics(String label); + + /// No description provided for @map_nodeMarkerSemantics. + /// + /// In en, this message translates to: + /// **'{name}, {type}, {status}'** + String map_nodeMarkerSemantics(String name, String type, String status); + + /// No description provided for @mapCache_zoomLevel. + /// + /// In en, this message translates to: + /// **'Zoom {zoom}'** + String mapCache_zoomLevel(int zoom); + + /// No description provided for @mapCache_sizeBytes. + /// + /// In en, this message translates to: + /// **'{size} B'** + String mapCache_sizeBytes(String size); + + /// No description provided for @mapCache_sizeKilobytes. + /// + /// In en, this message translates to: + /// **'{size} KB'** + String mapCache_sizeKilobytes(String size); + + /// No description provided for @mapCache_sizeMegabytes. + /// + /// In en, this message translates to: + /// **'{size} MB'** + String mapCache_sizeMegabytes(String size); + + /// No description provided for @mapCache_sizeGigabytes. + /// + /// In en, this message translates to: + /// **'{size} GB'** + String mapCache_sizeGigabytes(String size); + + /// No description provided for @mapCache_downloadCancelled. + /// + /// In en, this message translates to: + /// **'Download cancelled. Cached {count} tiles.'** + String mapCache_downloadCancelled(int count); + + /// No description provided for @mapCache_tooManyTilesTitle. + /// + /// In en, this message translates to: + /// **'Area too large'** + String get mapCache_tooManyTilesTitle; + + /// No description provided for @mapCache_tooManyTiles. + /// + /// In en, this message translates to: + /// **'This area needs {count} tiles, more than the limit of {max}. Pick a smaller area or lower the maximum zoom.'** + String mapCache_tooManyTiles(int count, int max); + + /// No description provided for @chat_clearChatConfirm. + /// + /// In en, this message translates to: + /// **'This erases every message in this conversation from this device. It cannot be undone.'** + String get chat_clearChatConfirm; + + /// No description provided for @channels_clearChatConfirm. + /// + /// In en, this message translates to: + /// **'This erases every message in this channel from this device, including received images. It cannot be undone.'** + String get channels_clearChatConfirm; + + /// No description provided for @channels_timeNow. + /// + /// In en, this message translates to: + /// **'now'** + String get channels_timeNow; + + /// No description provided for @channels_timeMinutes. + /// + /// In en, this message translates to: + /// **'{minutes}m'** + String channels_timeMinutes(int minutes); + + /// No description provided for @channels_timeHours. + /// + /// In en, this message translates to: + /// **'{hours}h'** + String channels_timeHours(int hours); + + /// No description provided for @channels_timeDays. + /// + /// In en, this message translates to: + /// **'{days}d'** + String channels_timeDays(int days); + + /// No description provided for @channels_indexChip. + /// + /// In en, this message translates to: + /// **'CH {index}'** + String channels_indexChip(int index); + + /// No description provided for @reaction_unknownSender. + /// + /// In en, this message translates to: + /// **'Unknown'** + String get reaction_unknownSender; + + /// No description provided for @pathMap_noSelfGpsFix. + /// + /// In en, this message translates to: + /// **'Local node has no GPS fix'** + String get pathMap_noSelfGpsFix; + + /// No description provided for @pathTrace_sendFailed. + /// + /// In en, this message translates to: + /// **'Could not send the path trace: {error}'** + String pathTrace_sendFailed(String error); + + /// No description provided for @losErrorNoInternet. + /// + /// In en, this message translates to: + /// **'Elevation data needs an internet connection'** + String get losErrorNoInternet; + + /// No description provided for @losResultStale. + /// + /// In en, this message translates to: + /// **'Out of date: antenna height changed'** + String get losResultStale; + + /// No description provided for @losSnrValue. + /// + /// In en, this message translates to: + /// **'{snr} dB'** + String losSnrValue(String snr); + + /// No description provided for @losFrequencyValue. + /// + /// In en, this message translates to: + /// **'{frequency} MHz'** + String losFrequencyValue(String frequency); + + /// No description provided for @losKFactorValue. + /// + /// In en, this message translates to: + /// **'k={kFactor}'** + String losKFactorValue(String kFactor); + + /// No description provided for @losEndpointA. + /// + /// In en, this message translates to: + /// **'A'** + String get losEndpointA; + + /// No description provided for @losEndpointB. + /// + /// In en, this message translates to: + /// **'B'** + String get losEndpointB; + + /// No description provided for @units_km. + /// + /// In en, this message translates to: + /// **'km'** + String get units_km; + + /// No description provided for @units_mi. + /// + /// In en, this message translates to: + /// **'mi'** + String get units_mi; + + /// No description provided for @units_m. + /// + /// In en, this message translates to: + /// **'m'** + String get units_m; + + /// No description provided for @units_ft. + /// + /// In en, this message translates to: + /// **'ft'** + String get units_ft; + + /// No description provided for @telemetry_loading. + /// + /// In en, this message translates to: + /// **'Loading telemetry…'** + String get telemetry_loading; + + /// No description provided for @telemetry_axisValue. + /// + /// In en, this message translates to: + /// **'X: {x}, Y: {y}, Z: {z}'** + String telemetry_axisValue(String x, String y, String z); + + /// No description provided for @telemetry_colourValue. + /// + /// In en, this message translates to: + /// **'R: {red}, G: {green}, B: {blue}'** + String telemetry_colourValue(String red, String green, String blue); + + /// No description provided for @telemetry_altitudeValueFeet. + /// + /// In en, this message translates to: + /// **'{feet} ft'** + String telemetry_altitudeValueFeet(String feet); + + /// No description provided for @telemetry_distanceValueFeet. + /// + /// In en, this message translates to: + /// **'{feet} ft'** + String telemetry_distanceValueFeet(String feet); + + /// No description provided for @settings_notConnectedError. + /// + /// In en, this message translates to: + /// **'Not connected to a radio. Connect and try again.'** + String get settings_notConnectedError; + + /// No description provided for @settings_requiresConnection. + /// + /// In en, this message translates to: + /// **'Connect to a radio to use this'** + String get settings_requiresConnection; + + /// No description provided for @settings_txPowerInvalidRange. + /// + /// In en, this message translates to: + /// **'Invalid TX power ({min} to {max} dBm)'** + String settings_txPowerInvalidRange(int min, int max); + + /// No description provided for @settings_contactSettingsSaved. + /// + /// In en, this message translates to: + /// **'Contact settings saved'** + String get settings_contactSettingsSaved; + + /// No description provided for @settings_batteryToggleHint. + /// + /// In en, this message translates to: + /// **'Tap to switch between percent and voltage'** + String get settings_batteryToggleHint; + + /// No description provided for @settings_publicKeyCopyHint. + /// + /// In en, this message translates to: + /// **'Copy public key'** + String get settings_publicKeyCopyHint; + + /// No description provided for @settings_locationClearHelper. + /// + /// In en, this message translates to: + /// **'Leave both fields empty to remove your location.'** + String get settings_locationClearHelper; + + /// No description provided for @settings_locationCleared. + /// + /// In en, this message translates to: + /// **'Location removed'** + String get settings_locationCleared; + + /// No description provided for @settings_regionFetchDiscovering. + /// + /// In en, this message translates to: + /// **'Looking for nearby repeaters…'** + String get settings_regionFetchDiscovering; + + /// No description provided for @settings_regionFetchProgress. + /// + /// In en, this message translates to: + /// **'Asking repeater {current} of {total}…'** + String settings_regionFetchProgress(int current, int total); + + /// No description provided for @settings_regionFetchNoRepeaters. + /// + /// In en, this message translates to: + /// **'No repeaters are known yet. Add a repeater as a contact or wait for one to advertise, then try again.'** + String get settings_regionFetchNoRepeaters; + + /// No description provided for @settings_regionFetchNoneResponded. + /// + /// In en, this message translates to: + /// **'No nearby repeaters answered. Move closer to a repeater and try again.'** + String get settings_regionFetchNoneResponded; + + /// No description provided for @appSettings_sourceSummary. + /// + /// In en, this message translates to: + /// **'{label} - {description}'** + String appSettings_sourceSummary(String label, String description); + + /// No description provided for @appSettings_routingSection. + /// + /// In en, this message translates to: + /// **'Routing'** + String get appSettings_routingSection; + + /// No description provided for @appSettings_imageMessagesSection. + /// + /// In en, this message translates to: + /// **'Image messages'** + String get appSettings_imageMessagesSection; + + /// No description provided for @appSettings_showApiKey. + /// + /// In en, this message translates to: + /// **'Show API key'** + String get appSettings_showApiKey; + + /// No description provided for @appSettings_hideApiKey. + /// + /// In en, this message translates to: + /// **'Hide API key'** + String get appSettings_hideApiKey; + + /// No description provided for @translation_defaultModelName. + /// + /// In en, this message translates to: + /// **'Model'** + String get translation_defaultModelName; + + /// No description provided for @translation_downloadProgressBytes. + /// + /// In en, this message translates to: + /// **'{fileName}: {current} MB'** + String translation_downloadProgressBytes(String fileName, String current); + + /// No description provided for @translation_downloadProgressTotal. + /// + /// In en, this message translates to: + /// **'{fileName}: {current} / {total} MB ({percent}%)'** + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ); + + /// No description provided for @translation_downloadedModelDetails. + /// + /// In en, this message translates to: + /// **'{size} MB • {source}'** + String translation_downloadedModelDetails(String size, String source); + + /// No description provided for @repeater_radioDisconnected. + /// + /// In en, this message translates to: + /// **'Radio disconnected'** + String get repeater_radioDisconnected; + + /// No description provided for @repeater_radioDisconnectedHint. + /// + /// In en, this message translates to: + /// **'Reconnect to your radio to send commands, refresh or save changes.'** + String get repeater_radioDisconnectedHint; + + /// No description provided for @repeater_cliSend. + /// + /// In en, this message translates to: + /// **'Send command'** + String get repeater_cliSend; + + /// No description provided for @repeater_cliCopyTranscript. + /// + /// In en, this message translates to: + /// **'Copy transcript'** + String get repeater_cliCopyTranscript; + + /// No description provided for @repeater_cliShareTranscript. + /// + /// In en, this message translates to: + /// **'Share transcript'** + String get repeater_cliShareTranscript; + + /// No description provided for @repeater_cliTranscriptCopied. + /// + /// In en, this message translates to: + /// **'Transcript copied'** + String get repeater_cliTranscriptCopied; + + /// No description provided for @repeater_cliClearHistoryConfirm. + /// + /// In en, this message translates to: + /// **'Clear the command history? This cannot be undone.'** + String get repeater_cliClearHistoryConfirm; + + /// No description provided for @repeater_cliSearchCommands. + /// + /// In en, this message translates to: + /// **'Search commands'** + String get repeater_cliSearchCommands; + + /// No description provided for @repeater_cliNoMatchingCommands. + /// + /// In en, this message translates to: + /// **'No matching commands'** + String get repeater_cliNoMatchingCommands; + + /// No description provided for @debugLog_clearConfirm. + /// + /// In en, this message translates to: + /// **'Clear all log entries? This cannot be undone.'** + String get debugLog_clearConfirm; + + /// No description provided for @repeater_unsavedChangesTitle. + /// + /// In en, this message translates to: + /// **'Unsaved changes'** + String get repeater_unsavedChangesTitle; + + /// No description provided for @repeater_unsavedChangesMessage. + /// + /// In en, this message translates to: + /// **'You have changes that haven\'t been saved to the repeater.'** + String get repeater_unsavedChangesMessage; + + /// No description provided for @repeater_discardChanges. + /// + /// In en, this message translates to: + /// **'Discard'** + String get repeater_discardChanges; + + /// No description provided for @repeater_actionSentNoReply. + /// + /// In en, this message translates to: + /// **'{action}: command sent. The repeater does not reply to this command.'** + String repeater_actionSentNoReply(String action); + + /// No description provided for @repeater_invalidSettingValue. + /// + /// In en, this message translates to: + /// **'{setting}: {value} is not valid'** + String repeater_invalidSettingValue(String setting, String value); + + /// No description provided for @repeater_txPowerOutOfRange. + /// + /// In en, this message translates to: + /// **'TX power {value} is out of range ({min} to {max} dBm)'** + String repeater_txPowerOutOfRange(String value, int min, int max); + + /// No description provided for @repeater_prvKeyLengthError. + /// + /// In en, this message translates to: + /// **'Private key must be exactly {length} hex characters'** + String repeater_prvKeyLengthError(int length); + + /// No description provided for @contacts_advertFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t send advertisement'** + String get contacts_advertFailed; + + /// No description provided for @contacts_manageGroups. + /// + /// In en, this message translates to: + /// **'Manage groups'** + String get contacts_manageGroups; + + /// No description provided for @community_shortId. + /// + /// In en, this message translates to: + /// **'ID: {id}…'** + String community_shortId(String id); + + /// No description provided for @tcpSectionTitle. + /// + /// In en, this message translates to: + /// **'TCP / IP'** + String get tcpSectionTitle; + + /// No description provided for @tcpConnectedToHeader. + /// + /// In en, this message translates to: + /// **'Connected to'** + String get tcpConnectedToHeader; + + /// No description provided for @usbChooseSerialPort. + /// + /// In en, this message translates to: + /// **'Choose serial port'** + String get usbChooseSerialPort; + + /// No description provided for @neighbors_durationSeconds. + /// + /// In en, this message translates to: + /// **'{seconds}s'** + String neighbors_durationSeconds(String seconds); + + /// No description provided for @neighbors_durationMinutes. + /// + /// In en, this message translates to: + /// **'{minutes}m {seconds}s'** + String neighbors_durationMinutes(int minutes, String seconds); + + /// No description provided for @neighbors_durationHours. + /// + /// In en, this message translates to: + /// **'{hours}h {minutes}m'** + String neighbors_durationHours(int hours, int minutes); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index bb999a01..7e143c2a 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -5779,4 +5779,405 @@ class AppLocalizationsBg extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Моделът за изображения не можа да се изтегли: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Скриване: скрит, докато не напуснете картата.'; + + @override + String get map_markerRemoveHint => + 'Премахване: остава скрит, докато не го възстановите от менюто за филтър.'; + + @override + String get map_markerRemoved => 'Маркерът е премахнат'; + + @override + String get map_restoreRemovedMarkers => + 'Възстановяване на премахнатите маркери'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count премахнати'; + } + + @override + String map_markersRestored(int count) { + return 'Възстановени маркери: $count'; + } + + @override + String get map_setLocationConfirmTitle => 'Задаване като ваша локация?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Вашият възел ще обявява тази позиция:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Задай локация'; + + @override + String get map_locationSetSuccess => 'Локацията на възела е обновена'; + + @override + String get map_locationSetFailed => + 'Устройството не потвърди новата локация. Опитайте отново.'; + + @override + String map_poiClusterTitle(int count) { + return '$count маркера тук'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count споделени маркера. Докоснете, за да ги видите.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Вие и $count маркера'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Споделен маркер: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Мащаб $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Изтеглянето е отменено. Кеширани плочки: $count.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Районът е твърде голям'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Този район изисква $count плочки, повече от лимита от $max. Изберете по-малък район или по-малък максимален мащаб.'; + } + + @override + String get chat_clearChatConfirm => + 'Това изтрива всяко съобщение в този разговор от това устройство. Действието не може да бъде отменено.'; + + @override + String get channels_clearChatConfirm => + 'Това изтрива всяко съобщение в този канал от това устройство, включително получените изображения. Действието не може да бъде отменено.'; + + @override + String get channels_timeNow => 'сега'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutesм'; + } + + @override + String channels_timeHours(int hours) { + return '$hoursч'; + } + + @override + String channels_timeDays(int days) { + return '$daysд'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Неизвестен'; + + @override + String get pathMap_noSelfGpsFix => 'Локалният възел няма GPS фиксиране'; + + @override + String pathTrace_sendFailed(String error) { + return 'Пътната трасировка не можа да бъде изпратена: $error'; + } + + @override + String get losErrorNoInternet => + 'Данните за надморска височина изискват интернет връзка'; + + @override + String get losResultStale => + 'Остарял резултат: височината на антената е променена'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Зареждане на телеметрия…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Няма връзка с радио. Свържете се и опитайте отново.'; + + @override + String get settings_requiresConnection => + 'Свържете се с радио, за да използвате това'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Невалидна TX мощност (от $min до $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => + 'Настройките на контакта са запазени'; + + @override + String get settings_batteryToggleHint => + 'Докоснете, за да превключите между процент и напрежение'; + + @override + String get settings_publicKeyCopyHint => 'Копиране на публичния ключ'; + + @override + String get settings_locationClearHelper => + 'Оставете и двете полета празни, за да премахнете локацията си.'; + + @override + String get settings_locationCleared => 'Локацията е премахната'; + + @override + String get settings_regionFetchDiscovering => + 'Търсене на близки ретранслатори…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Запитване към ретранслатор $current от $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Все още няма известни ретранслатори. Добавете ретранслатор като контакт или изчакайте някой да обяви присъствие, после опитайте отново.'; + + @override + String get settings_regionFetchNoneResponded => + 'Нито един близък ретранслатор не отговори. Приближете се до ретранслатор и опитайте отново.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Маршрутизиране'; + + @override + String get appSettings_imageMessagesSection => 'Съобщения с изображения'; + + @override + String get appSettings_showApiKey => 'Показване на API ключа'; + + @override + String get appSettings_hideApiKey => 'Скриване на API ключа'; + + @override + String get translation_defaultModelName => 'Модел'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Радиото е изключено'; + + @override + String get repeater_radioDisconnectedHint => + 'Свържете се отново с радиото, за да изпращате команди, да опреснявате или да запазвате промени.'; + + @override + String get repeater_cliSend => 'Изпрати команда'; + + @override + String get repeater_cliCopyTranscript => 'Копирай транскрипта'; + + @override + String get repeater_cliShareTranscript => 'Сподели транскрипта'; + + @override + String get repeater_cliTranscriptCopied => 'Транскриптът е копиран'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Да се изчисти ли историята на командите? Действието не може да бъде отменено.'; + + @override + String get repeater_cliSearchCommands => 'Търсене на команди'; + + @override + String get repeater_cliNoMatchingCommands => 'Няма съвпадащи команди'; + + @override + String get debugLog_clearConfirm => + 'Да се изчистят ли всички записи в дневника? Действието не може да бъде отменено.'; + + @override + String get repeater_unsavedChangesTitle => 'Незапазени промени'; + + @override + String get repeater_unsavedChangesMessage => + 'Имате промени, които не са запазени в ретранслатора.'; + + @override + String get repeater_discardChanges => 'Отхвърли'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: командата е изпратена. Ретранслаторът не отговаря на тази команда.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value не е валидна стойност'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX мощността $value е извън диапазона (от $min до $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Частният ключ трябва да е точно $length шестнадесетични знака'; + } + + @override + String get contacts_advertFailed => 'Рекламата не можа да бъде изпратена'; + + @override + String get contacts_manageGroups => 'Управление на групи'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Свързан с'; + + @override + String get usbChooseSerialPort => 'Изберете сериен порт'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$secondsс'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutesм $secondsс'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hoursч $minutesм'; + } } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 7c099a2a..92b6653a 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -5796,4 +5796,403 @@ class AppLocalizationsDe extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Das Bildmodell konnte nicht heruntergeladen werden: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Ausblenden: bleibt ausgeblendet, bis du die Karte verlässt.'; + + @override + String get map_markerRemoveHint => + 'Entfernen: bleibt ausgeblendet, bis du es über das Filtermenü wiederherstellst.'; + + @override + String get map_markerRemoved => 'Marker entfernt'; + + @override + String get map_restoreRemovedMarkers => 'Entfernte Marker wiederherstellen'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count entfernt'; + } + + @override + String map_markersRestored(int count) { + return '$count Marker wiederhergestellt'; + } + + @override + String get map_setLocationConfirmTitle => 'Als deinen Standort festlegen?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Dein Knoten wird diese Position bekannt geben:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Standort festlegen'; + + @override + String get map_locationSetSuccess => 'Knotenstandort aktualisiert'; + + @override + String get map_locationSetFailed => + 'Das Gerät hat den neuen Standort nicht bestätigt. Versuche es erneut.'; + + @override + String map_poiClusterTitle(int count) { + return '$count Marker hier'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count geteilte Marker. Tippen, um sie aufzulisten.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Du und $count Marker'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Geteilter Marker: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Download abgebrochen. $count Kacheln im Cache.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Bereich zu groß'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Dieser Bereich benötigt $count Kacheln, mehr als das Limit von $max. Wähle einen kleineren Bereich oder verringere den maximalen Zoom.'; + } + + @override + String get chat_clearChatConfirm => + 'Dadurch werden alle Nachrichten dieser Unterhaltung von diesem Gerät gelöscht. Das kann nicht rückgängig gemacht werden.'; + + @override + String get channels_clearChatConfirm => + 'Dadurch werden alle Nachrichten dieses Kanals von diesem Gerät gelöscht, einschließlich empfangener Bilder. Das kann nicht rückgängig gemacht werden.'; + + @override + String get channels_timeNow => 'jetzt'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes Min.'; + } + + @override + String channels_timeHours(int hours) { + return '$hours Std.'; + } + + @override + String channels_timeDays(int days) { + return '$days T.'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Unbekannt'; + + @override + String get pathMap_noSelfGpsFix => 'Lokaler Knoten hat keinen GPS-Fix'; + + @override + String pathTrace_sendFailed(String error) { + return 'Pfadverfolgung konnte nicht gesendet werden: $error'; + } + + @override + String get losErrorNoInternet => + 'Für Höhendaten wird eine Internetverbindung benötigt'; + + @override + String get losResultStale => 'Veraltet: Antennenhöhe wurde geändert'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Telemetrie wird geladen…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Nicht mit einem Funkgerät verbunden. Verbinde dich und versuche es erneut.'; + + @override + String get settings_requiresConnection => + 'Verbinde dich mit einem Funkgerät, um dies zu nutzen'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Ungültige Sendeleistung ($min bis $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => + 'Kontakteinstellungen gespeichert'; + + @override + String get settings_batteryToggleHint => + 'Tippen, um zwischen Prozent und Spannung zu wechseln'; + + @override + String get settings_publicKeyCopyHint => 'Öffentlichen Schlüssel kopieren'; + + @override + String get settings_locationClearHelper => + 'Lass beide Felder leer, um deinen Standort zu entfernen.'; + + @override + String get settings_locationCleared => 'Standort entfernt'; + + @override + String get settings_regionFetchDiscovering => + 'Suche nach Repeatern in der Nähe…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Frage Repeater $current von $total ab…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Noch keine Repeater bekannt. Füge einen Repeater als Kontakt hinzu oder warte, bis einer sich ankündigt, und versuche es dann erneut.'; + + @override + String get settings_regionFetchNoneResponded => + 'Kein Repeater in der Nähe hat geantwortet. Gehe näher an einen Repeater heran und versuche es erneut.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Routing'; + + @override + String get appSettings_imageMessagesSection => 'Bildnachrichten'; + + @override + String get appSettings_showApiKey => 'API-Schlüssel anzeigen'; + + @override + String get appSettings_hideApiKey => 'API-Schlüssel verbergen'; + + @override + String get translation_defaultModelName => 'Modell'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Funkgerät getrennt'; + + @override + String get repeater_radioDisconnectedHint => + 'Verbinde dich erneut mit deinem Funkgerät, um Befehle zu senden, zu aktualisieren oder Änderungen zu speichern.'; + + @override + String get repeater_cliSend => 'Befehl senden'; + + @override + String get repeater_cliCopyTranscript => 'Protokoll kopieren'; + + @override + String get repeater_cliShareTranscript => 'Protokoll teilen'; + + @override + String get repeater_cliTranscriptCopied => 'Protokoll kopiert'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Befehlsverlauf löschen? Das kann nicht rückgängig gemacht werden.'; + + @override + String get repeater_cliSearchCommands => 'Befehle suchen'; + + @override + String get repeater_cliNoMatchingCommands => 'Keine passenden Befehle'; + + @override + String get debugLog_clearConfirm => + 'Alle Protokolleinträge löschen? Das kann nicht rückgängig gemacht werden.'; + + @override + String get repeater_unsavedChangesTitle => 'Ungespeicherte Änderungen'; + + @override + String get repeater_unsavedChangesMessage => + 'Es gibt Änderungen, die nicht im Repeater gespeichert wurden.'; + + @override + String get repeater_discardChanges => 'Verwerfen'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: Befehl gesendet. Der Repeater antwortet auf diesen Befehl nicht.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value ist ungültig'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Sendeleistung $value liegt außerhalb des Bereichs ($min bis $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Der private Schlüssel muss genau $length Hex-Zeichen lang sein'; + } + + @override + String get contacts_advertFailed => 'Advert konnte nicht gesendet werden'; + + @override + String get contacts_manageGroups => 'Gruppen verwalten'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Verbunden mit'; + + @override + String get usbChooseSerialPort => 'Serielle Schnittstelle wählen'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes Min. $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours Std. $minutes Min.'; + } } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ce4fc6cc..76da02cd 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -5699,4 +5699,399 @@ class AppLocalizationsEn extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'The image model could not be downloaded: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => 'Hide: hidden until you leave the map.'; + + @override + String get map_markerRemoveHint => + 'Remove: stays hidden until you restore it from the filter menu.'; + + @override + String get map_markerRemoved => 'Marker removed'; + + @override + String get map_restoreRemovedMarkers => 'Restore removed markers'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count removed'; + } + + @override + String map_markersRestored(int count) { + return 'Restored $count markers'; + } + + @override + String get map_setLocationConfirmTitle => 'Set as your location?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Your node will advertise this position:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Set location'; + + @override + String get map_locationSetSuccess => 'Node location updated'; + + @override + String get map_locationSetFailed => + 'The device did not confirm the new location. Try again.'; + + @override + String map_poiClusterTitle(int count) { + return '$count markers here'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count shared markers. Tap to list them.'; + } + + @override + String map_youWithMarkers(int count) { + return 'You and $count markers'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Shared marker: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Download cancelled. Cached $count tiles.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Area too large'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'This area needs $count tiles, more than the limit of $max. Pick a smaller area or lower the maximum zoom.'; + } + + @override + String get chat_clearChatConfirm => + 'This erases every message in this conversation from this device. It cannot be undone.'; + + @override + String get channels_clearChatConfirm => + 'This erases every message in this channel from this device, including received images. It cannot be undone.'; + + @override + String get channels_timeNow => 'now'; + + @override + String channels_timeMinutes(int minutes) { + return '${minutes}m'; + } + + @override + String channels_timeHours(int hours) { + return '${hours}h'; + } + + @override + String channels_timeDays(int days) { + return '${days}d'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Unknown'; + + @override + String get pathMap_noSelfGpsFix => 'Local node has no GPS fix'; + + @override + String pathTrace_sendFailed(String error) { + return 'Could not send the path trace: $error'; + } + + @override + String get losErrorNoInternet => + 'Elevation data needs an internet connection'; + + @override + String get losResultStale => 'Out of date: antenna height changed'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Loading telemetry…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Not connected to a radio. Connect and try again.'; + + @override + String get settings_requiresConnection => 'Connect to a radio to use this'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Invalid TX power ($min to $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Contact settings saved'; + + @override + String get settings_batteryToggleHint => + 'Tap to switch between percent and voltage'; + + @override + String get settings_publicKeyCopyHint => 'Copy public key'; + + @override + String get settings_locationClearHelper => + 'Leave both fields empty to remove your location.'; + + @override + String get settings_locationCleared => 'Location removed'; + + @override + String get settings_regionFetchDiscovering => 'Looking for nearby repeaters…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Asking repeater $current of $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'No repeaters are known yet. Add a repeater as a contact or wait for one to advertise, then try again.'; + + @override + String get settings_regionFetchNoneResponded => + 'No nearby repeaters answered. Move closer to a repeater and try again.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Routing'; + + @override + String get appSettings_imageMessagesSection => 'Image messages'; + + @override + String get appSettings_showApiKey => 'Show API key'; + + @override + String get appSettings_hideApiKey => 'Hide API key'; + + @override + String get translation_defaultModelName => 'Model'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio disconnected'; + + @override + String get repeater_radioDisconnectedHint => + 'Reconnect to your radio to send commands, refresh or save changes.'; + + @override + String get repeater_cliSend => 'Send command'; + + @override + String get repeater_cliCopyTranscript => 'Copy transcript'; + + @override + String get repeater_cliShareTranscript => 'Share transcript'; + + @override + String get repeater_cliTranscriptCopied => 'Transcript copied'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Clear the command history? This cannot be undone.'; + + @override + String get repeater_cliSearchCommands => 'Search commands'; + + @override + String get repeater_cliNoMatchingCommands => 'No matching commands'; + + @override + String get debugLog_clearConfirm => + 'Clear all log entries? This cannot be undone.'; + + @override + String get repeater_unsavedChangesTitle => 'Unsaved changes'; + + @override + String get repeater_unsavedChangesMessage => + 'You have changes that haven\'t been saved to the repeater.'; + + @override + String get repeater_discardChanges => 'Discard'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: command sent. The repeater does not reply to this command.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value is not valid'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX power $value is out of range ($min to $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Private key must be exactly $length hex characters'; + } + + @override + String get contacts_advertFailed => 'Couldn\'t send advertisement'; + + @override + String get contacts_manageGroups => 'Manage groups'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Connected to'; + + @override + String get usbChooseSerialPort => 'Choose serial port'; + + @override + String neighbors_durationSeconds(String seconds) { + return '${seconds}s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '${minutes}m ${seconds}s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '${hours}h ${minutes}m'; + } } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 21d23fdd..ed53314a 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -5785,4 +5785,402 @@ class AppLocalizationsEs extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'No se pudo descargar el modelo de imagen: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Ocultar: permanece oculto hasta que salgas del mapa.'; + + @override + String get map_markerRemoveHint => + 'Eliminar: permanece oculto hasta que lo restaures desde el menú de filtros.'; + + @override + String get map_markerRemoved => 'Marcador eliminado'; + + @override + String get map_restoreRemovedMarkers => 'Restaurar marcadores eliminados'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count eliminados'; + } + + @override + String map_markersRestored(int count) { + return '$count marcadores restaurados'; + } + + @override + String get map_setLocationConfirmTitle => '¿Establecer como tu ubicación?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Tu nodo anunciará esta posición:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Establecer ubicación'; + + @override + String get map_locationSetSuccess => 'Ubicación del nodo actualizada'; + + @override + String get map_locationSetFailed => + 'El dispositivo no confirmó la nueva ubicación. Inténtalo de nuevo.'; + + @override + String map_poiClusterTitle(int count) { + return '$count marcadores aquí'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count marcadores compartidos. Toca para verlos.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Tú y $count marcadores'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Marcador compartido: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Descarga cancelada. $count teselas en caché.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Área demasiado grande'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Esta área necesita $count teselas, más que el límite de $max. Elige un área más pequeña o reduce el zoom máximo.'; + } + + @override + String get chat_clearChatConfirm => + 'Esto borra todos los mensajes de esta conversación de este dispositivo. No se puede deshacer.'; + + @override + String get channels_clearChatConfirm => + 'Esto borra todos los mensajes de este canal de este dispositivo, incluidas las imágenes recibidas. No se puede deshacer.'; + + @override + String get channels_timeNow => 'ahora'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes min'; + } + + @override + String channels_timeHours(int hours) { + return '$hours h'; + } + + @override + String channels_timeDays(int days) { + return '$days d'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Desconocido'; + + @override + String get pathMap_noSelfGpsFix => 'El nodo local no tiene fijación GPS'; + + @override + String pathTrace_sendFailed(String error) { + return 'No se pudo enviar el trazado de ruta: $error'; + } + + @override + String get losErrorNoInternet => + 'Los datos de elevación requieren conexión a internet'; + + @override + String get losResultStale => 'Desactualizado: la altura de la antena cambió'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Cargando telemetría…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'No hay conexión con una radio. Conéctate e inténtalo de nuevo.'; + + @override + String get settings_requiresConnection => + 'Conéctate a una radio para usar esto'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Potencia TX inválida ($min a $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Ajustes del contacto guardados'; + + @override + String get settings_batteryToggleHint => + 'Toca para alternar entre porcentaje y voltaje'; + + @override + String get settings_publicKeyCopyHint => 'Copiar clave pública'; + + @override + String get settings_locationClearHelper => + 'Deja ambos campos vacíos para eliminar tu ubicación.'; + + @override + String get settings_locationCleared => 'Ubicación eliminada'; + + @override + String get settings_regionFetchDiscovering => + 'Buscando repetidores cercanos…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Consultando al repetidor $current de $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Aún no se conoce ningún repetidor. Añade un repetidor como contacto o espera a que anuncie su presencia, e inténtalo de nuevo.'; + + @override + String get settings_regionFetchNoneResponded => + 'Ningún repetidor cercano respondió. Acércate a un repetidor e inténtalo de nuevo.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Enrutamiento'; + + @override + String get appSettings_imageMessagesSection => 'Mensajes con imágenes'; + + @override + String get appSettings_showApiKey => 'Mostrar clave de API'; + + @override + String get appSettings_hideApiKey => 'Ocultar clave de API'; + + @override + String get translation_defaultModelName => 'Modelo'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio desconectada'; + + @override + String get repeater_radioDisconnectedHint => + 'Vuelve a conectarte a tu radio para enviar comandos, actualizar o guardar cambios.'; + + @override + String get repeater_cliSend => 'Enviar comando'; + + @override + String get repeater_cliCopyTranscript => 'Copiar transcripción'; + + @override + String get repeater_cliShareTranscript => 'Compartir transcripción'; + + @override + String get repeater_cliTranscriptCopied => 'Transcripción copiada'; + + @override + String get repeater_cliClearHistoryConfirm => + '¿Borrar el historial de comandos? No se puede deshacer.'; + + @override + String get repeater_cliSearchCommands => 'Buscar comandos'; + + @override + String get repeater_cliNoMatchingCommands => 'Ningún comando coincide'; + + @override + String get debugLog_clearConfirm => + '¿Borrar todas las entradas del registro? No se puede deshacer.'; + + @override + String get repeater_unsavedChangesTitle => 'Cambios sin guardar'; + + @override + String get repeater_unsavedChangesMessage => + 'Tienes cambios que no se han guardado en el repetidor.'; + + @override + String get repeater_discardChanges => 'Descartar'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: comando enviado. El repetidor no responde a este comando.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value no es válido'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'La potencia TX $value está fuera de rango ($min a $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'La clave privada debe tener exactamente $length caracteres hexadecimales'; + } + + @override + String get contacts_advertFailed => 'No se pudo enviar el anuncio'; + + @override + String get contacts_manageGroups => 'Gestionar grupos'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Conectado a'; + + @override + String get usbChooseSerialPort => 'Elegir puerto serie'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours h $minutes min'; + } } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 94a4133f..7a18939c 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -5809,4 +5809,403 @@ class AppLocalizationsFr extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Le modèle d\'image n\'a pas pu être téléchargé : $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Masquer : masqué jusqu\'à ce que vous quittiez la carte.'; + + @override + String get map_markerRemoveHint => + 'Supprimer : reste masqué jusqu\'à sa restauration depuis le menu des filtres.'; + + @override + String get map_markerRemoved => 'Marqueur supprimé'; + + @override + String get map_restoreRemovedMarkers => 'Restaurer les marqueurs supprimés'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count supprimé(s)'; + } + + @override + String map_markersRestored(int count) { + return '$count marqueurs restaurés'; + } + + @override + String get map_setLocationConfirmTitle => 'Définir comme votre position ?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Votre nœud annoncera cette position :\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Définir la position'; + + @override + String get map_locationSetSuccess => 'Position du nœud mise à jour'; + + @override + String get map_locationSetFailed => + 'L\'appareil n\'a pas confirmé la nouvelle position. Réessayez.'; + + @override + String map_poiClusterTitle(int count) { + return '$count marqueurs ici'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count marqueurs partagés. Touchez pour les lister.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Vous et $count marqueurs'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Marqueur partagé : $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size o'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size Ko'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size Mo'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size Go'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Téléchargement annulé. $count tuiles mises en cache.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Zone trop grande'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Cette zone nécessite $count tuiles, soit plus que la limite de $max. Choisissez une zone plus petite ou réduisez le zoom maximal.'; + } + + @override + String get chat_clearChatConfirm => + 'Cela efface tous les messages de cette conversation sur cet appareil. Action irréversible.'; + + @override + String get channels_clearChatConfirm => + 'Cela efface tous les messages de ce canal sur cet appareil, y compris les images reçues. Action irréversible.'; + + @override + String get channels_timeNow => 'maint.'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes min'; + } + + @override + String channels_timeHours(int hours) { + return '$hours h'; + } + + @override + String channels_timeDays(int days) { + return '$days j'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Inconnu'; + + @override + String get pathMap_noSelfGpsFix => 'Le nœud local n\'a pas de position GPS'; + + @override + String pathTrace_sendFailed(String error) { + return 'Impossible d\'envoyer la trace du chemin : $error'; + } + + @override + String get losErrorNoInternet => + 'Les données d\'altitude nécessitent une connexion Internet'; + + @override + String get losResultStale => 'Obsolète : la hauteur de l\'antenne a changé'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Chargement de la télémétrie…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X : $x, Y : $y, Z : $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R : $red, V : $green, B : $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Non connecté à une radio. Connectez-vous et réessayez.'; + + @override + String get settings_requiresConnection => + 'Connectez-vous à une radio pour l\'utiliser'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Puissance TX invalide ($min à $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => + 'Paramètres du contact enregistrés'; + + @override + String get settings_batteryToggleHint => + 'Touchez pour basculer entre pourcentage et tension'; + + @override + String get settings_publicKeyCopyHint => 'Copier la clé publique'; + + @override + String get settings_locationClearHelper => + 'Laissez les deux champs vides pour supprimer votre position.'; + + @override + String get settings_locationCleared => 'Position supprimée'; + + @override + String get settings_regionFetchDiscovering => + 'Recherche de répéteurs à proximité…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Interrogation du répéteur $current sur $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Aucun répéteur connu pour le moment. Ajoutez un répéteur comme contact ou attendez qu\'un répéteur s\'annonce, puis réessayez.'; + + @override + String get settings_regionFetchNoneResponded => + 'Aucun répéteur à proximité n\'a répondu. Rapprochez-vous d\'un répéteur et réessayez.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Routage'; + + @override + String get appSettings_imageMessagesSection => 'Messages image'; + + @override + String get appSettings_showApiKey => 'Afficher la clé API'; + + @override + String get appSettings_hideApiKey => 'Masquer la clé API'; + + @override + String get translation_defaultModelName => 'Modèle'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName : $current Mo'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName : $current / $total Mo ($percent %)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size Mo • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio déconnectée'; + + @override + String get repeater_radioDisconnectedHint => + 'Reconnectez-vous à votre radio pour envoyer des commandes, actualiser ou enregistrer les modifications.'; + + @override + String get repeater_cliSend => 'Envoyer la commande'; + + @override + String get repeater_cliCopyTranscript => 'Copier la transcription'; + + @override + String get repeater_cliShareTranscript => 'Partager la transcription'; + + @override + String get repeater_cliTranscriptCopied => 'Transcription copiée'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Effacer l\'historique des commandes ? Action irréversible.'; + + @override + String get repeater_cliSearchCommands => 'Rechercher des commandes'; + + @override + String get repeater_cliNoMatchingCommands => 'Aucune commande correspondante'; + + @override + String get debugLog_clearConfirm => + 'Effacer toutes les entrées du journal ? Action irréversible.'; + + @override + String get repeater_unsavedChangesTitle => 'Modifications non enregistrées'; + + @override + String get repeater_unsavedChangesMessage => + 'Vous avez des modifications non enregistrées sur le répéteur.'; + + @override + String get repeater_discardChanges => 'Abandonner'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action : commande envoyée. Le répéteur ne répond pas à cette commande.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting : $value n\'est pas valide'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Puissance TX $value hors plage ($min à $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'La clé privée doit comporter exactement $length caractères hexadécimaux'; + } + + @override + String get contacts_advertFailed => 'Impossible d\'envoyer l\'annonce'; + + @override + String get contacts_manageGroups => 'Gérer les groupes'; + + @override + String community_shortId(String id) { + return 'ID : $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Connecté à'; + + @override + String get usbChooseSerialPort => 'Choisir le port série'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours h $minutes min'; + } } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index d02c4227..5c7eb236 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -5774,4 +5774,401 @@ class AppLocalizationsHu extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'A képmodell letöltése sikertelen: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Elrejtés: a térkép elhagyásáig rejtve marad.'; + + @override + String get map_markerRemoveHint => + 'Eltávolítás: a szűrőmenüből való visszaállításig rejtve marad.'; + + @override + String get map_markerRemoved => 'Jelölő eltávolítva'; + + @override + String get map_restoreRemovedMarkers => 'Eltávolított jelölők visszaállítása'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count eltávolítva'; + } + + @override + String map_markersRestored(int count) { + return '$count jelölő visszaállítva'; + } + + @override + String get map_setLocationConfirmTitle => 'Beállítja saját helyzetként?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'A csomópont ezt a pozíciót fogja hirdetni:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Helyzet beállítása'; + + @override + String get map_locationSetSuccess => 'A csomópont helyzete frissítve'; + + @override + String get map_locationSetFailed => + 'Az eszköz nem erősítette meg az új helyzetet. Próbálja újra.'; + + @override + String map_poiClusterTitle(int count) { + return '$count jelölő itt'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count megosztott jelölő. Koppintson a listázáshoz.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Ön és $count jelölő'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Megosztott jelölő: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Nagyítás: $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'A letöltés megszakítva. $count csempe gyorsítótárazva.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Túl nagy terület'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Ehhez a területhez $count csempe kell, ami meghaladja a $max korlátot. Válasszon kisebb területet, vagy csökkentse a maximális nagyítást.'; + } + + @override + String get chat_clearChatConfirm => + 'Ez törli a beszélgetés összes üzenetét erről az eszközről. A művelet nem vonható vissza.'; + + @override + String get channels_clearChatConfirm => + 'Ez törli a csatorna összes üzenetét erről az eszközről, a fogadott képekkel együtt. A művelet nem vonható vissza.'; + + @override + String get channels_timeNow => 'most'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes p'; + } + + @override + String channels_timeHours(int hours) { + return '$hours ó'; + } + + @override + String channels_timeDays(int days) { + return '$days n'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Ismeretlen'; + + @override + String get pathMap_noSelfGpsFix => 'A helyi csomópontnak nincs GPS-jelzése'; + + @override + String pathTrace_sendFailed(String error) { + return 'Nem sikerült elküldeni az útvonalkövetést: $error'; + } + + @override + String get losErrorNoInternet => + 'A magassági adatokhoz internetkapcsolat szükséges'; + + @override + String get losResultStale => 'Elavult: az antennamagasság megváltozott'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Telemetria betöltése…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Nincs kapcsolat rádióval. Csatlakozzon, és próbálja újra.'; + + @override + String get settings_requiresConnection => + 'A használathoz csatlakozzon egy rádióhoz'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Érvénytelen TX teljesítmény ($min – $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Kapcsolatbeállítások mentve'; + + @override + String get settings_batteryToggleHint => + 'Koppintson a százalék és a feszültség közötti váltáshoz'; + + @override + String get settings_publicKeyCopyHint => 'Nyilvános kulcs másolása'; + + @override + String get settings_locationClearHelper => + 'A helyzet törléséhez hagyja üresen mindkét mezőt.'; + + @override + String get settings_locationCleared => 'Helyzet eltávolítva'; + + @override + String get settings_regionFetchDiscovering => 'Közeli átjátszók keresése…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return '$current. átjátszó lekérdezése ($total közül)…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Még nem ismert egyetlen átjátszó sem. Adjon hozzá egy átjátszót kapcsolatként, vagy várja meg, amíg egy hirdet, majd próbálja újra.'; + + @override + String get settings_regionFetchNoneResponded => + 'Egyik közeli átjátszó sem válaszolt. Menjen közelebb egy átjátszóhoz, és próbálja újra.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Útválasztás'; + + @override + String get appSettings_imageMessagesSection => 'Képüzenetek'; + + @override + String get appSettings_showApiKey => 'API-kulcs megjelenítése'; + + @override + String get appSettings_hideApiKey => 'API-kulcs elrejtése'; + + @override + String get translation_defaultModelName => 'Modell'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'A rádió lecsatlakozott'; + + @override + String get repeater_radioDisconnectedHint => + 'Csatlakozzon újra a rádióhoz parancsok küldéséhez, frissítéshez vagy a módosítások mentéséhez.'; + + @override + String get repeater_cliSend => 'Parancs küldése'; + + @override + String get repeater_cliCopyTranscript => 'Átirat másolása'; + + @override + String get repeater_cliShareTranscript => 'Átirat megosztása'; + + @override + String get repeater_cliTranscriptCopied => 'Átirat másolva'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Törli a parancselőzményeket? A művelet nem vonható vissza.'; + + @override + String get repeater_cliSearchCommands => 'Parancsok keresése'; + + @override + String get repeater_cliNoMatchingCommands => 'Nincs egyező parancs'; + + @override + String get debugLog_clearConfirm => + 'Törli az összes naplóbejegyzést? A művelet nem vonható vissza.'; + + @override + String get repeater_unsavedChangesTitle => 'Nem mentett módosítások'; + + @override + String get repeater_unsavedChangesMessage => + 'Vannak módosítások, amelyek nincsenek elmentve az átjátszóra.'; + + @override + String get repeater_discardChanges => 'Elvetés'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: parancs elküldve. Az átjátszó nem válaszol erre a parancsra.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value érvénytelen'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'A(z) $value TX teljesítmény tartományon kívül van ($min – $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'A privát kulcsnak pontosan $length hexadecimális karakterből kell állnia'; + } + + @override + String get contacts_advertFailed => 'Nem sikerült elküldeni a hirdetést'; + + @override + String get contacts_manageGroups => 'Csoportok kezelése'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Csatlakozva:'; + + @override + String get usbChooseSerialPort => 'Soros port kiválasztása'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds mp'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes p $seconds mp'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours ó $minutes p'; + } } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 877c0975..17b87f24 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -5792,4 +5792,402 @@ class AppLocalizationsIt extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Impossibile scaricare il modello di immagine: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Nascondi: resta nascosto finché non lasci la mappa.'; + + @override + String get map_markerRemoveHint => + 'Rimuovi: resta nascosto finché non lo ripristini dal menu dei filtri.'; + + @override + String get map_markerRemoved => 'Segnaposto rimosso'; + + @override + String get map_restoreRemovedMarkers => 'Ripristina segnaposti rimossi'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count rimossi'; + } + + @override + String map_markersRestored(int count) { + return '$count segnaposti ripristinati'; + } + + @override + String get map_setLocationConfirmTitle => 'Impostare come tua posizione?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Il tuo nodo annuncerà questa posizione:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Imposta posizione'; + + @override + String get map_locationSetSuccess => 'Posizione del nodo aggiornata'; + + @override + String get map_locationSetFailed => + 'Il dispositivo non ha confermato la nuova posizione. Riprova.'; + + @override + String map_poiClusterTitle(int count) { + return '$count segnaposti qui'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count segnaposti condivisi. Tocca per elencarli.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Tu e $count segnaposti'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Segnaposto condiviso: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Download annullato. $count tile salvate nella cache.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Area troppo grande'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Quest\'area richiede $count tile, più del limite di $max. Scegli un\'area più piccola o riduci lo zoom massimo.'; + } + + @override + String get chat_clearChatConfirm => + 'Questo cancella tutti i messaggi di questa conversazione da questo dispositivo. Non può essere annullato.'; + + @override + String get channels_clearChatConfirm => + 'Questo cancella tutti i messaggi di questo canale da questo dispositivo, comprese le immagini ricevute. Non può essere annullato.'; + + @override + String get channels_timeNow => 'ora'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes min'; + } + + @override + String channels_timeHours(int hours) { + return '$hours h'; + } + + @override + String channels_timeDays(int days) { + return '$days g'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Sconosciuto'; + + @override + String get pathMap_noSelfGpsFix => 'Il nodo locale non ha un fix GPS'; + + @override + String pathTrace_sendFailed(String error) { + return 'Impossibile inviare il tracciamento del percorso: $error'; + } + + @override + String get losErrorNoInternet => + 'I dati di altitudine richiedono una connessione a Internet'; + + @override + String get losResultStale => + 'Non aggiornato: l\'altezza dell\'antenna è cambiata'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Caricamento della telemetria…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Non connesso a una radio. Connettiti e riprova.'; + + @override + String get settings_requiresConnection => 'Connettiti a una radio per usarlo'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Potenza TX non valida ($min - $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => + 'Impostazioni del contatto salvate'; + + @override + String get settings_batteryToggleHint => + 'Tocca per passare tra percentuale e tensione'; + + @override + String get settings_publicKeyCopyHint => 'Copia chiave pubblica'; + + @override + String get settings_locationClearHelper => + 'Lascia vuoti entrambi i campi per rimuovere la tua posizione.'; + + @override + String get settings_locationCleared => 'Posizione rimossa'; + + @override + String get settings_regionFetchDiscovering => 'Ricerca di ripetitori vicini…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Interrogazione del ripetitore $current di $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Nessun ripetitore noto per ora. Aggiungi un ripetitore come contatto o attendi che ne annunci uno, poi riprova.'; + + @override + String get settings_regionFetchNoneResponded => + 'Nessun ripetitore vicino ha risposto. Avvicinati a un ripetitore e riprova.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Instradamento'; + + @override + String get appSettings_imageMessagesSection => 'Messaggi immagine'; + + @override + String get appSettings_showApiKey => 'Mostra chiave API'; + + @override + String get appSettings_hideApiKey => 'Nascondi chiave API'; + + @override + String get translation_defaultModelName => 'Modello'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio disconnessa'; + + @override + String get repeater_radioDisconnectedHint => + 'Riconnettiti alla radio per inviare comandi, aggiornare o salvare le modifiche.'; + + @override + String get repeater_cliSend => 'Invia comando'; + + @override + String get repeater_cliCopyTranscript => 'Copia trascrizione'; + + @override + String get repeater_cliShareTranscript => 'Condividi trascrizione'; + + @override + String get repeater_cliTranscriptCopied => 'Trascrizione copiata'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Cancellare la cronologia dei comandi? Non può essere annullato.'; + + @override + String get repeater_cliSearchCommands => 'Cerca comandi'; + + @override + String get repeater_cliNoMatchingCommands => 'Nessun comando corrispondente'; + + @override + String get debugLog_clearConfirm => + 'Cancellare tutte le voci del registro? Non può essere annullato.'; + + @override + String get repeater_unsavedChangesTitle => 'Modifiche non salvate'; + + @override + String get repeater_unsavedChangesMessage => + 'Hai modifiche non salvate sul ripetitore.'; + + @override + String get repeater_discardChanges => 'Scarta'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: comando inviato. Il ripetitore non risponde a questo comando.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value non è valido'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Potenza TX $value fuori intervallo ($min - $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'La chiave privata deve essere di esattamente $length caratteri esadecimali'; + } + + @override + String get contacts_advertFailed => 'Impossibile inviare l\'annuncio'; + + @override + String get contacts_manageGroups => 'Gestisci gruppi'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Connesso a'; + + @override + String get usbChooseSerialPort => 'Scegli porta seriale'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours h $minutes min'; + } } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 240eea50..7f59a6f5 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5507,4 +5507,389 @@ class AppLocalizationsJa extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return '画像モデルをダウンロードできませんでした:$error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => '非表示:マップを離れるまで非表示になります。'; + + @override + String get map_markerRemoveHint => '削除:フィルターメニューから復元するまで非表示のままです。'; + + @override + String get map_markerRemoved => 'マーカーを削除しました'; + + @override + String get map_restoreRemovedMarkers => '削除したマーカーを復元'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count件削除済み'; + } + + @override + String map_markersRestored(int count) { + return '$count件のマーカーを復元しました'; + } + + @override + String get map_setLocationConfirmTitle => 'この位置を自分の位置に設定しますか?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'ノードは次の位置をアドバートします:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => '位置を設定'; + + @override + String get map_locationSetSuccess => 'ノードの位置を更新しました'; + + @override + String get map_locationSetFailed => 'デバイスが新しい位置を確認しませんでした。もう一度お試しください。'; + + @override + String map_poiClusterTitle(int count) { + return 'ここに$count件のマーカー'; + } + + @override + String map_poiClusterSemantics(int count) { + return '共有マーカー$count件。タップして一覧を表示します。'; + } + + @override + String map_youWithMarkers(int count) { + return '自分と$count件のマーカー'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return '共有マーカー: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name、$type、$status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'ズーム $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'ダウンロードをキャンセルしました。$count枚のタイルをキャッシュしました。'; + } + + @override + String get mapCache_tooManyTilesTitle => 'エリアが大きすぎます'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'このエリアには$count枚のタイルが必要で、上限の$max枚を超えています。より小さいエリアを選ぶか、最大ズームを下げてください。'; + } + + @override + String get chat_clearChatConfirm => 'この会話のすべてのメッセージをこのデバイスから消去します。元に戻せません。'; + + @override + String get channels_clearChatConfirm => + 'このチャンネルのすべてのメッセージを、受信した画像も含めてこのデバイスから消去します。元に戻せません。'; + + @override + String get channels_timeNow => '今'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes分'; + } + + @override + String channels_timeHours(int hours) { + return '$hours時間'; + } + + @override + String channels_timeDays(int days) { + return '$days日'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => '不明'; + + @override + String get pathMap_noSelfGpsFix => 'ローカルノードにGPS測位がありません'; + + @override + String pathTrace_sendFailed(String error) { + return 'パストレースを送信できませんでした: $error'; + } + + @override + String get losErrorNoInternet => '標高データにはインターネット接続が必要です'; + + @override + String get losResultStale => '古い結果: アンテナ高が変更されました'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'テレメトリを読み込み中…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => '無線機に接続されていません。接続してからもう一度お試しください。'; + + @override + String get settings_requiresConnection => '使用するには無線機に接続してください'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'TX出力が無効です($min~$max dBm)'; + } + + @override + String get settings_contactSettingsSaved => '連絡先設定を保存しました'; + + @override + String get settings_batteryToggleHint => 'タップでパーセントと電圧を切り替え'; + + @override + String get settings_publicKeyCopyHint => '公開鍵をコピー'; + + @override + String get settings_locationClearHelper => '位置情報を削除するには、両方の欄を空にしてください。'; + + @override + String get settings_locationCleared => '位置情報を削除しました'; + + @override + String get settings_regionFetchDiscovering => '近くのリピータを検索中…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'リピータ $current/$total に問い合わせ中…'; + } + + @override + String get settings_regionFetchNoRepeaters => + '既知のリピータがまだありません。リピータを連絡先に追加するか、アドバートを待ってからもう一度お試しください。'; + + @override + String get settings_regionFetchNoneResponded => + '近くのリピータから応答がありませんでした。リピータに近づいてもう一度お試しください。'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'ルーティング'; + + @override + String get appSettings_imageMessagesSection => '画像メッセージ'; + + @override + String get appSettings_showApiKey => 'APIキーを表示'; + + @override + String get appSettings_hideApiKey => 'APIキーを非表示'; + + @override + String get translation_defaultModelName => 'モデル'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => '無線機が切断されました'; + + @override + String get repeater_radioDisconnectedHint => + 'コマンドの送信、更新、変更の保存を行うには、無線機に再接続してください。'; + + @override + String get repeater_cliSend => 'コマンドを送信'; + + @override + String get repeater_cliCopyTranscript => '履歴をコピー'; + + @override + String get repeater_cliShareTranscript => '履歴を共有'; + + @override + String get repeater_cliTranscriptCopied => '履歴をコピーしました'; + + @override + String get repeater_cliClearHistoryConfirm => 'コマンド履歴を消去しますか?元に戻せません。'; + + @override + String get repeater_cliSearchCommands => 'コマンドを検索'; + + @override + String get repeater_cliNoMatchingCommands => '一致するコマンドがありません'; + + @override + String get debugLog_clearConfirm => 'すべてのログを消去しますか?元に戻せません。'; + + @override + String get repeater_unsavedChangesTitle => '未保存の変更'; + + @override + String get repeater_unsavedChangesMessage => 'リピータに保存されていない変更があります。'; + + @override + String get repeater_discardChanges => '破棄'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: コマンドを送信しました。リピータはこのコマンドに応答しません。'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $valueは無効です'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX出力 $value は範囲外です($min~$max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return '秘密鍵は16進数でちょうど$length文字である必要があります'; + } + + @override + String get contacts_advertFailed => 'アドバートを送信できませんでした'; + + @override + String get contacts_manageGroups => 'グループを管理'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => '接続先'; + + @override + String get usbChooseSerialPort => 'シリアルポートを選択'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds秒'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes分$seconds秒'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours時間$minutes分'; + } } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index d4b9be2d..658abee7 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5517,4 +5517,389 @@ class AppLocalizationsKo extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return '이미지 모델을 다운로드하지 못했습니다: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => '숨기기: 지도를 벗어날 때까지 숨겨집니다.'; + + @override + String get map_markerRemoveHint => '삭제: 필터 메뉴에서 복원하기 전까지 숨겨진 상태로 유지됩니다.'; + + @override + String get map_markerRemoved => '마커를 삭제했습니다'; + + @override + String get map_restoreRemovedMarkers => '삭제한 마커 복원'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count개 삭제됨'; + } + + @override + String map_markersRestored(int count) { + return '마커 $count개를 복원했습니다'; + } + + @override + String get map_setLocationConfirmTitle => '내 위치로 설정할까요?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return '노드가 다음 위치를 어드버트합니다:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => '위치 설정'; + + @override + String get map_locationSetSuccess => '노드 위치를 업데이트했습니다'; + + @override + String get map_locationSetFailed => '장치가 새 위치를 확인하지 않았습니다. 다시 시도하세요.'; + + @override + String map_poiClusterTitle(int count) { + return '여기에 마커 $count개'; + } + + @override + String map_poiClusterSemantics(int count) { + return '공유 마커 $count개. 탭하여 목록을 확인하세요.'; + } + + @override + String map_youWithMarkers(int count) { + return '나와 마커 $count개'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return '공유 마커: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return '줌 $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return '다운로드가 취소되었습니다. 타일 $count개를 캐시했습니다.'; + } + + @override + String get mapCache_tooManyTilesTitle => '영역이 너무 큽니다'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return '이 영역에는 타일 $count개가 필요하며 제한인 $max개를 초과합니다. 더 작은 영역을 선택하거나 최대 줌을 낮추세요.'; + } + + @override + String get chat_clearChatConfirm => '이 대화의 모든 메시지를 이 기기에서 삭제합니다. 되돌릴 수 없습니다.'; + + @override + String get channels_clearChatConfirm => + '받은 이미지를 포함해 이 채널의 모든 메시지를 이 기기에서 삭제합니다. 되돌릴 수 없습니다.'; + + @override + String get channels_timeNow => '지금'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes분'; + } + + @override + String channels_timeHours(int hours) { + return '$hours시간'; + } + + @override + String channels_timeDays(int days) { + return '$days일'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => '알 수 없음'; + + @override + String get pathMap_noSelfGpsFix => '로컬 노드에 GPS 위치가 없습니다'; + + @override + String pathTrace_sendFailed(String error) { + return '경로 추적을 보낼 수 없습니다: $error'; + } + + @override + String get losErrorNoInternet => '고도 데이터에는 인터넷 연결이 필요합니다'; + + @override + String get losResultStale => '오래된 결과: 안테나 높이가 변경되었습니다'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => '텔레메트리 불러오는 중…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => '무전기에 연결되어 있지 않습니다. 연결한 후 다시 시도하세요.'; + + @override + String get settings_requiresConnection => '사용하려면 무전기에 연결하세요'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return '잘못된 TX 출력입니다($min~$max dBm)'; + } + + @override + String get settings_contactSettingsSaved => '연락처 설정을 저장했습니다'; + + @override + String get settings_batteryToggleHint => '탭하여 퍼센트와 전압 전환'; + + @override + String get settings_publicKeyCopyHint => '공개 키 복사'; + + @override + String get settings_locationClearHelper => '위치를 삭제하려면 두 입력란을 모두 비워 두세요.'; + + @override + String get settings_locationCleared => '위치를 삭제했습니다'; + + @override + String get settings_regionFetchDiscovering => '주변 리피터를 찾는 중…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return '리피터 $current/$total에 요청하는 중…'; + } + + @override + String get settings_regionFetchNoRepeaters => + '알려진 리피터가 아직 없습니다. 리피터를 연락처로 추가하거나 어드버트를 기다린 후 다시 시도하세요.'; + + @override + String get settings_regionFetchNoneResponded => + '응답한 주변 리피터가 없습니다. 리피터에 더 가까이 이동한 후 다시 시도하세요.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => '라우팅'; + + @override + String get appSettings_imageMessagesSection => '이미지 메시지'; + + @override + String get appSettings_showApiKey => 'API 키 표시'; + + @override + String get appSettings_hideApiKey => 'API 키 숨기기'; + + @override + String get translation_defaultModelName => '모델'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => '무전기 연결 끊김'; + + @override + String get repeater_radioDisconnectedHint => + '명령을 보내거나 새로고침 또는 변경 사항을 저장하려면 무전기에 다시 연결하세요.'; + + @override + String get repeater_cliSend => '명령 보내기'; + + @override + String get repeater_cliCopyTranscript => '기록 복사'; + + @override + String get repeater_cliShareTranscript => '기록 공유'; + + @override + String get repeater_cliTranscriptCopied => '기록을 복사했습니다'; + + @override + String get repeater_cliClearHistoryConfirm => '명령 기록을 지울까요? 되돌릴 수 없습니다.'; + + @override + String get repeater_cliSearchCommands => '명령 검색'; + + @override + String get repeater_cliNoMatchingCommands => '일치하는 명령이 없습니다'; + + @override + String get debugLog_clearConfirm => '모든 로그 항목을 지울까요? 되돌릴 수 없습니다.'; + + @override + String get repeater_unsavedChangesTitle => '저장하지 않은 변경 사항'; + + @override + String get repeater_unsavedChangesMessage => '리피터에 저장되지 않은 변경 사항이 있습니다.'; + + @override + String get repeater_discardChanges => '취소'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: 명령을 보냈습니다. 리피터는 이 명령에 응답하지 않습니다.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value은(는) 올바르지 않습니다'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX 출력 $value이(가) 범위를 벗어났습니다($min~$max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return '개인 키는 정확히 16진수 $length자여야 합니다'; + } + + @override + String get contacts_advertFailed => '어드버트를 보낼 수 없습니다'; + + @override + String get contacts_manageGroups => '그룹 관리'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => '연결 대상'; + + @override + String get usbChooseSerialPort => '시리얼 포트 선택'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds초'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes분 $seconds초'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours시간 $minutes분'; + } } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index db418ab4..47bf573c 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -5752,4 +5752,402 @@ class AppLocalizationsNl extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Het afbeeldingsmodel kon niet worden gedownload: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Verbergen: verborgen totdat je de kaart verlaat.'; + + @override + String get map_markerRemoveHint => + 'Verwijderen: blijft verborgen totdat je het herstelt via het filtermenu.'; + + @override + String get map_markerRemoved => 'Markering verwijderd'; + + @override + String get map_restoreRemovedMarkers => 'Verwijderde markeringen herstellen'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count verwijderd'; + } + + @override + String map_markersRestored(int count) { + return '$count markeringen hersteld'; + } + + @override + String get map_setLocationConfirmTitle => 'Instellen als jouw locatie?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Je node adverteert deze positie:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Locatie instellen'; + + @override + String get map_locationSetSuccess => 'Nodelocatie bijgewerkt'; + + @override + String get map_locationSetFailed => + 'Het apparaat heeft de nieuwe locatie niet bevestigd. Probeer het opnieuw.'; + + @override + String map_poiClusterTitle(int count) { + return '$count markeringen hier'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count gedeelde markeringen. Tik om ze weer te geven.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Jij en $count markeringen'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Gedeelde markering: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Download geannuleerd. $count tegels in cache opgeslagen.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Gebied te groot'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Dit gebied vereist $count tegels, meer dan de limiet van $max. Kies een kleiner gebied of verlaag de maximale zoom.'; + } + + @override + String get chat_clearChatConfirm => + 'Hiermee worden alle berichten in dit gesprek van dit apparaat gewist. Dit kan niet ongedaan worden gemaakt.'; + + @override + String get channels_clearChatConfirm => + 'Hiermee worden alle berichten in dit kanaal van dit apparaat gewist, inclusief ontvangen afbeeldingen. Dit kan niet ongedaan worden gemaakt.'; + + @override + String get channels_timeNow => 'nu'; + + @override + String channels_timeMinutes(int minutes) { + return '${minutes}m'; + } + + @override + String channels_timeHours(int hours) { + return '${hours}u'; + } + + @override + String channels_timeDays(int days) { + return '${days}d'; + } + + @override + String channels_indexChip(int index) { + return 'KN $index'; + } + + @override + String get reaction_unknownSender => 'Onbekend'; + + @override + String get pathMap_noSelfGpsFix => 'Lokale node heeft geen GPS-fix'; + + @override + String pathTrace_sendFailed(String error) { + return 'Padtracering kon niet worden verzonden: $error'; + } + + @override + String get losErrorNoInternet => + 'Hoogtegegevens vereisen een internetverbinding'; + + @override + String get losResultStale => 'Verouderd: antennehoogte is gewijzigd'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Telemetrie laden…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Niet verbonden met een radio. Maak verbinding en probeer het opnieuw.'; + + @override + String get settings_requiresConnection => + 'Maak verbinding met een radio om dit te gebruiken'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Ongeldig TX-vermogen ($min tot $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Contactinstellingen opgeslagen'; + + @override + String get settings_batteryToggleHint => + 'Tik om te wisselen tussen procent en spanning'; + + @override + String get settings_publicKeyCopyHint => 'Publieke sleutel kopiëren'; + + @override + String get settings_locationClearHelper => + 'Laat beide velden leeg om je locatie te verwijderen.'; + + @override + String get settings_locationCleared => 'Locatie verwijderd'; + + @override + String get settings_regionFetchDiscovering => 'Repeaters in de buurt zoeken…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Repeater $current van $total wordt gevraagd…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Er zijn nog geen repeaters bekend. Voeg een repeater toe als contact of wacht tot er een adverteert en probeer het dan opnieuw.'; + + @override + String get settings_regionFetchNoneResponded => + 'Geen repeaters in de buurt hebben geantwoord. Ga dichter bij een repeater staan en probeer het opnieuw.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Routering'; + + @override + String get appSettings_imageMessagesSection => 'Afbeeldingsberichten'; + + @override + String get appSettings_showApiKey => 'API-sleutel tonen'; + + @override + String get appSettings_hideApiKey => 'API-sleutel verbergen'; + + @override + String get translation_defaultModelName => 'Model'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio losgekoppeld'; + + @override + String get repeater_radioDisconnectedHint => + 'Maak opnieuw verbinding met je radio om commando\'s te verzenden, te vernieuwen of wijzigingen op te slaan.'; + + @override + String get repeater_cliSend => 'Commando verzenden'; + + @override + String get repeater_cliCopyTranscript => 'Transcript kopiëren'; + + @override + String get repeater_cliShareTranscript => 'Transcript delen'; + + @override + String get repeater_cliTranscriptCopied => 'Transcript gekopieerd'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Commandogeschiedenis wissen? Dit kan niet ongedaan worden gemaakt.'; + + @override + String get repeater_cliSearchCommands => 'Commando\'s zoeken'; + + @override + String get repeater_cliNoMatchingCommands => + 'Geen overeenkomende commando\'s'; + + @override + String get debugLog_clearConfirm => + 'Alle logboekvermeldingen wissen? Dit kan niet ongedaan worden gemaakt.'; + + @override + String get repeater_unsavedChangesTitle => 'Niet-opgeslagen wijzigingen'; + + @override + String get repeater_unsavedChangesMessage => + 'Je hebt wijzigingen die niet zijn opgeslagen op de repeater.'; + + @override + String get repeater_discardChanges => 'Verwerpen'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: commando verzonden. De repeater antwoordt niet op dit commando.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value is niet geldig'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX-vermogen $value valt buiten het bereik ($min tot $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'De privésleutel moet precies $length hexadecimale tekens bevatten'; + } + + @override + String get contacts_advertFailed => 'Advertentie kon niet worden verzonden'; + + @override + String get contacts_manageGroups => 'Groepen beheren'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Verbonden met'; + + @override + String get usbChooseSerialPort => 'Seriële poort kiezen'; + + @override + String neighbors_durationSeconds(String seconds) { + return '${seconds}s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '${minutes}m ${seconds}s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '${hours}u ${minutes}m'; + } } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index a1959873..452ea7d1 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -5817,4 +5817,401 @@ class AppLocalizationsPl extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Nie udało się pobrać modelu obrazów: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => 'Ukryj: ukryty do czasu opuszczenia mapy.'; + + @override + String get map_markerRemoveHint => + 'Usuń: pozostaje ukryty, dopóki nie przywrócisz go z menu filtrów.'; + + @override + String get map_markerRemoved => 'Znacznik usunięty'; + + @override + String get map_restoreRemovedMarkers => 'Przywróć usunięte znaczniki'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return 'Usunięto: $count'; + } + + @override + String map_markersRestored(int count) { + return 'Przywrócono znaczniki: $count'; + } + + @override + String get map_setLocationConfirmTitle => 'Ustawić jako Twoją lokalizację?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Twój węzeł będzie ogłaszał tę pozycję:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Ustaw lokalizację'; + + @override + String get map_locationSetSuccess => 'Zaktualizowano lokalizację węzła'; + + @override + String get map_locationSetFailed => + 'Urządzenie nie potwierdziło nowej lokalizacji. Spróbuj ponownie.'; + + @override + String map_poiClusterTitle(int count) { + return 'Znaczniki tutaj: $count'; + } + + @override + String map_poiClusterSemantics(int count) { + return 'Udostępnione znaczniki: $count. Dotknij, aby je wyświetlić.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Ty i znaczniki: $count'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Udostępniony znacznik: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Pobieranie anulowane. Zapisano w pamięci podręcznej kafelki: $count.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Obszar zbyt duży'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Ten obszar wymaga $count kafelków, co przekracza limit $max. Wybierz mniejszy obszar lub zmniejsz maksymalny zoom.'; + } + + @override + String get chat_clearChatConfirm => + 'Spowoduje to usunięcie z tego urządzenia wszystkich wiadomości w tej rozmowie. Tej operacji nie można cofnąć.'; + + @override + String get channels_clearChatConfirm => + 'Spowoduje to usunięcie z tego urządzenia wszystkich wiadomości w tym kanale, w tym odebranych obrazów. Tej operacji nie można cofnąć.'; + + @override + String get channels_timeNow => 'teraz'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes min'; + } + + @override + String channels_timeHours(int hours) { + return '$hours godz.'; + } + + @override + String channels_timeDays(int days) { + return '$days d'; + } + + @override + String channels_indexChip(int index) { + return 'KN $index'; + } + + @override + String get reaction_unknownSender => 'Nieznany'; + + @override + String get pathMap_noSelfGpsFix => 'Lokalny węzeł nie ma pozycji GPS'; + + @override + String pathTrace_sendFailed(String error) { + return 'Nie udało się wysłać śledzenia trasy: $error'; + } + + @override + String get losErrorNoInternet => + 'Dane wysokościowe wymagają połączenia z internetem'; + + @override + String get losResultStale => 'Nieaktualne: zmieniono wysokość anteny'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Wczytywanie telemetrii…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Brak połączenia z radiem. Połącz się i spróbuj ponownie.'; + + @override + String get settings_requiresConnection => + 'Połącz się z radiem, aby z tego korzystać'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Nieprawidłowa moc TX (od $min do $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Zapisano ustawienia kontaktu'; + + @override + String get settings_batteryToggleHint => + 'Dotknij, aby przełączyć między procentami a napięciem'; + + @override + String get settings_publicKeyCopyHint => 'Kopiuj klucz publiczny'; + + @override + String get settings_locationClearHelper => + 'Pozostaw oba pola puste, aby usunąć swoją lokalizację.'; + + @override + String get settings_locationCleared => 'Lokalizacja usunięta'; + + @override + String get settings_regionFetchDiscovering => + 'Wyszukiwanie pobliskich przekaźników…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Odpytywanie przekaźnika $current z $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Nie są jeszcze znane żadne przekaźniki. Dodaj przekaźnik jako kontakt lub poczekaj, aż któryś się ogłosi, a następnie spróbuj ponownie.'; + + @override + String get settings_regionFetchNoneResponded => + 'Żaden pobliski przekaźnik nie odpowiedział. Zbliż się do przekaźnika i spróbuj ponownie.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Routing'; + + @override + String get appSettings_imageMessagesSection => 'Wiadomości z obrazami'; + + @override + String get appSettings_showApiKey => 'Pokaż klucz API'; + + @override + String get appSettings_hideApiKey => 'Ukryj klucz API'; + + @override + String get translation_defaultModelName => 'Model'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio rozłączone'; + + @override + String get repeater_radioDisconnectedHint => + 'Połącz się ponownie z radiem, aby wysyłać polecenia, odświeżać lub zapisywać zmiany.'; + + @override + String get repeater_cliSend => 'Wyślij polecenie'; + + @override + String get repeater_cliCopyTranscript => 'Kopiuj zapis'; + + @override + String get repeater_cliShareTranscript => 'Udostępnij zapis'; + + @override + String get repeater_cliTranscriptCopied => 'Skopiowano zapis'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Wyczyścić historię poleceń? Tej operacji nie można cofnąć.'; + + @override + String get repeater_cliSearchCommands => 'Szukaj poleceń'; + + @override + String get repeater_cliNoMatchingCommands => 'Brak pasujących poleceń'; + + @override + String get debugLog_clearConfirm => + 'Wyczyścić wszystkie wpisy dziennika? Tej operacji nie można cofnąć.'; + + @override + String get repeater_unsavedChangesTitle => 'Niezapisane zmiany'; + + @override + String get repeater_unsavedChangesMessage => + 'Masz zmiany, które nie zostały zapisane w przekaźniku.'; + + @override + String get repeater_discardChanges => 'Odrzuć'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: polecenie wysłane. Przekaźnik nie odpowiada na to polecenie.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value jest nieprawidłowe'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Moc TX $value jest poza zakresem (od $min do $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Klucz prywatny musi mieć dokładnie $length znaków szesnastkowych'; + } + + @override + String get contacts_advertFailed => 'Nie udało się wysłać ogłoszenia'; + + @override + String get contacts_manageGroups => 'Zarządzaj grupami'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Połączono z'; + + @override + String get usbChooseSerialPort => 'Wybierz port szeregowy'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours godz. $minutes min'; + } } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index bab9270c..3f234aa4 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -5781,4 +5781,402 @@ class AppLocalizationsPt extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Não foi possível baixar o modelo de imagem: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Ocultar: fica oculto até você sair do mapa.'; + + @override + String get map_markerRemoveHint => + 'Remover: continua oculto até você restaurá-lo no menu de filtros.'; + + @override + String get map_markerRemoved => 'Marcador removido'; + + @override + String get map_restoreRemovedMarkers => 'Restaurar marcadores removidos'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count removidos'; + } + + @override + String map_markersRestored(int count) { + return '$count marcadores restaurados'; + } + + @override + String get map_setLocationConfirmTitle => 'Definir como sua localização?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Seu nó vai anunciar esta posição:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Definir localização'; + + @override + String get map_locationSetSuccess => 'Localização do nó atualizada'; + + @override + String get map_locationSetFailed => + 'O dispositivo não confirmou a nova localização. Tente novamente.'; + + @override + String map_poiClusterTitle(int count) { + return '$count marcadores aqui'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count marcadores compartilhados. Toque para listá-los.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Você e $count marcadores'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Marcador compartilhado: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Download cancelado. $count blocos em cache.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Área muito grande'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Esta área precisa de $count blocos, mais do que o limite de $max. Escolha uma área menor ou reduza o zoom máximo.'; + } + + @override + String get chat_clearChatConfirm => + 'Isto apaga todas as mensagens desta conversa deste dispositivo. Não é possível desfazer.'; + + @override + String get channels_clearChatConfirm => + 'Isto apaga todas as mensagens deste canal deste dispositivo, incluindo as imagens recebidas. Não é possível desfazer.'; + + @override + String get channels_timeNow => 'agora'; + + @override + String channels_timeMinutes(int minutes) { + return '${minutes}min'; + } + + @override + String channels_timeHours(int hours) { + return '${hours}h'; + } + + @override + String channels_timeDays(int days) { + return '${days}d'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => 'Desconhecido'; + + @override + String get pathMap_noSelfGpsFix => 'O nó local não tem sinal de GPS'; + + @override + String pathTrace_sendFailed(String error) { + return 'Não foi possível enviar o rastreamento de caminho: $error'; + } + + @override + String get losErrorNoInternet => + 'Os dados de elevação precisam de conexão com a internet'; + + @override + String get losResultStale => 'Desatualizado: a altura da antena mudou'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Carregando telemetria…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Sem conexão com um rádio. Conecte e tente novamente.'; + + @override + String get settings_requiresConnection => + 'Conecte-se a um rádio para usar isto'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Potência de TX inválida ($min a $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Configurações do contato salvas'; + + @override + String get settings_batteryToggleHint => + 'Toque para alternar entre porcentagem e tensão'; + + @override + String get settings_publicKeyCopyHint => 'Copiar chave pública'; + + @override + String get settings_locationClearHelper => + 'Deixe ambos os campos vazios para remover sua localização.'; + + @override + String get settings_locationCleared => 'Localização removida'; + + @override + String get settings_regionFetchDiscovering => + 'Procurando repetidores próximos…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Consultando o repetidor $current de $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Ainda não há repetidores conhecidos. Adicione um repetidor como contato ou aguarde um anunciar, e tente novamente.'; + + @override + String get settings_regionFetchNoneResponded => + 'Nenhum repetidor próximo respondeu. Aproxime-se de um repetidor e tente novamente.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Roteamento'; + + @override + String get appSettings_imageMessagesSection => 'Mensagens de imagem'; + + @override + String get appSettings_showApiKey => 'Mostrar chave de API'; + + @override + String get appSettings_hideApiKey => 'Ocultar chave de API'; + + @override + String get translation_defaultModelName => 'Modelo'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Rádio desconectado'; + + @override + String get repeater_radioDisconnectedHint => + 'Reconecte-se ao seu rádio para enviar comandos, atualizar ou salvar alterações.'; + + @override + String get repeater_cliSend => 'Enviar comando'; + + @override + String get repeater_cliCopyTranscript => 'Copiar transcrição'; + + @override + String get repeater_cliShareTranscript => 'Compartilhar transcrição'; + + @override + String get repeater_cliTranscriptCopied => 'Transcrição copiada'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Limpar o histórico de comandos? Não é possível desfazer.'; + + @override + String get repeater_cliSearchCommands => 'Pesquisar comandos'; + + @override + String get repeater_cliNoMatchingCommands => 'Nenhum comando correspondente'; + + @override + String get debugLog_clearConfirm => + 'Limpar todas as entradas do registro? Não é possível desfazer.'; + + @override + String get repeater_unsavedChangesTitle => 'Alterações não salvas'; + + @override + String get repeater_unsavedChangesMessage => + 'Você tem alterações que não foram salvas no repetidor.'; + + @override + String get repeater_discardChanges => 'Descartar'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: comando enviado. O repetidor não responde a este comando.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value não é válido'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Potência de TX $value fora do intervalo ($min a $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'A chave privada deve ter exatamente $length caracteres hexadecimais'; + } + + @override + String get contacts_advertFailed => 'Não foi possível enviar o anúncio'; + + @override + String get contacts_manageGroups => 'Gerenciar grupos'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Conectado a'; + + @override + String get usbChooseSerialPort => 'Escolher porta serial'; + + @override + String neighbors_durationSeconds(String seconds) { + return '${seconds}s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '${minutes}m ${seconds}s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '${hours}h ${minutes}m'; + } } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 4882c690..018549ec 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -5803,4 +5803,401 @@ class AppLocalizationsRu extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Не удалось загрузить модель изображений: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Скрыть: маркер скрыт, пока вы не покинете карту.'; + + @override + String get map_markerRemoveHint => + 'Удалить: маркер останется скрытым, пока вы не восстановите его в меню фильтра.'; + + @override + String get map_markerRemoved => 'Маркер удалён'; + + @override + String get map_restoreRemovedMarkers => 'Восстановить удалённые маркеры'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return 'Удалено: $count'; + } + + @override + String map_markersRestored(int count) { + return 'Восстановлено маркеров: $count'; + } + + @override + String get map_setLocationConfirmTitle => 'Установить как вашу позицию?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Ваш узел будет анонсировать эту позицию:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Установить позицию'; + + @override + String get map_locationSetSuccess => 'Позиция узла обновлена'; + + @override + String get map_locationSetFailed => + 'Устройство не подтвердило новую позицию. Попробуйте снова.'; + + @override + String map_poiClusterTitle(int count) { + return 'Маркеров здесь: $count'; + } + + @override + String map_poiClusterSemantics(int count) { + return 'Общих маркеров: $count. Нажмите, чтобы открыть список.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Вы и маркеров: $count'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Общий маркер: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Масштаб $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size Б'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size КБ'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size МБ'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size ГБ'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Загрузка отменена. Кэшировано тайлов: $count.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Область слишком большая'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Для этой области нужно тайлов: $count, что больше лимита $max. Выберите область меньше или уменьшите максимальный масштаб.'; + } + + @override + String get chat_clearChatConfirm => + 'Это удалит все сообщения этого чата с данного устройства. Действие нельзя отменить.'; + + @override + String get channels_clearChatConfirm => + 'Это удалит все сообщения этого канала с данного устройства, включая полученные изображения. Действие нельзя отменить.'; + + @override + String get channels_timeNow => 'сейчас'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutesм'; + } + + @override + String channels_timeHours(int hours) { + return '$hoursч'; + } + + @override + String channels_timeDays(int days) { + return '$daysд'; + } + + @override + String channels_indexChip(int index) { + return 'КАН $index'; + } + + @override + String get reaction_unknownSender => 'Неизвестно'; + + @override + String get pathMap_noSelfGpsFix => 'У локального узла нет GPS-фиксации'; + + @override + String pathTrace_sendFailed(String error) { + return 'Не удалось отправить трассировку пути: $error'; + } + + @override + String get losErrorNoInternet => + 'Для данных о высотах нужно подключение к интернету'; + + @override + String get losResultStale => 'Устарело: высота антенны изменилась'; + + @override + String losSnrValue(String snr) { + return '$snr дБ'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency МГц'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'км'; + + @override + String get units_mi => 'миль'; + + @override + String get units_m => 'м'; + + @override + String get units_ft => 'фт'; + + @override + String get telemetry_loading => 'Загрузка телеметрии…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet фт'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet фт'; + } + + @override + String get settings_notConnectedError => + 'Нет подключения к радио. Подключитесь и повторите попытку.'; + + @override + String get settings_requiresConnection => + 'Подключитесь к радио, чтобы использовать это'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Недопустимая мощность TX (от $min до $max дБм)'; + } + + @override + String get settings_contactSettingsSaved => 'Настройки контакта сохранены'; + + @override + String get settings_batteryToggleHint => + 'Нажмите, чтобы переключить между процентами и напряжением'; + + @override + String get settings_publicKeyCopyHint => 'Копировать публичный ключ'; + + @override + String get settings_locationClearHelper => + 'Оставьте оба поля пустыми, чтобы удалить вашу позицию.'; + + @override + String get settings_locationCleared => 'Позиция удалена'; + + @override + String get settings_regionFetchDiscovering => 'Поиск ближайших репитеров…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Опрос репитера $current из $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Репитеры пока не известны. Добавьте репитер в контакты или дождитесь его анонса, затем повторите попытку.'; + + @override + String get settings_regionFetchNoneResponded => + 'Ближайшие репитеры не ответили. Подойдите ближе к репитеру и повторите попытку.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Маршрутизация'; + + @override + String get appSettings_imageMessagesSection => 'Сообщения-изображения'; + + @override + String get appSettings_showApiKey => 'Показать API-ключ'; + + @override + String get appSettings_hideApiKey => 'Скрыть API-ключ'; + + @override + String get translation_defaultModelName => 'Модель'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current МБ'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total МБ ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size МБ • $source'; + } + + @override + String get repeater_radioDisconnected => 'Радио отключено'; + + @override + String get repeater_radioDisconnectedHint => + 'Переподключитесь к радио, чтобы отправлять команды, обновлять данные или сохранять изменения.'; + + @override + String get repeater_cliSend => 'Отправить команду'; + + @override + String get repeater_cliCopyTranscript => 'Копировать журнал'; + + @override + String get repeater_cliShareTranscript => 'Поделиться журналом'; + + @override + String get repeater_cliTranscriptCopied => 'Журнал скопирован'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Очистить историю команд? Действие нельзя отменить.'; + + @override + String get repeater_cliSearchCommands => 'Поиск команд'; + + @override + String get repeater_cliNoMatchingCommands => 'Нет подходящих команд'; + + @override + String get debugLog_clearConfirm => + 'Очистить все записи журнала? Действие нельзя отменить.'; + + @override + String get repeater_unsavedChangesTitle => 'Несохранённые изменения'; + + @override + String get repeater_unsavedChangesMessage => + 'У вас есть изменения, не сохранённые в репитере.'; + + @override + String get repeater_discardChanges => 'Отменить'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: команда отправлена. Репитер не отвечает на эту команду.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: значение $value недопустимо'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Мощность TX $value вне диапазона (от $min до $max дБм)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Приватный ключ должен содержать ровно $length шестнадцатеричных символов'; + } + + @override + String get contacts_advertFailed => 'Не удалось отправить анонс'; + + @override + String get contacts_manageGroups => 'Управление группами'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Подключено к'; + + @override + String get usbChooseSerialPort => 'Выберите последовательный порт'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$secondsс'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutesм $secondsс'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hoursч $minutesм'; + } } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 72213043..78a12f67 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -5765,4 +5765,401 @@ class AppLocalizationsSk extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Model obrázkov sa nepodarilo stiahnuť: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Skryť: značka zostane skrytá, kým neopustíte mapu.'; + + @override + String get map_markerRemoveHint => + 'Odstrániť: značka zostane skrytá, kým ju neobnovíte v ponuke filtra.'; + + @override + String get map_markerRemoved => 'Značka bola odstránená'; + + @override + String get map_restoreRemovedMarkers => 'Obnoviť odstránené značky'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return 'Odstránené: $count'; + } + + @override + String map_markersRestored(int count) { + return 'Obnovené značky: $count'; + } + + @override + String get map_setLocationConfirmTitle => 'Nastaviť ako vašu polohu?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Váš uzol bude oznamovať túto polohu:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Nastaviť polohu'; + + @override + String get map_locationSetSuccess => 'Poloha uzla bola aktualizovaná'; + + @override + String get map_locationSetFailed => + 'Zariadenie nepotvrdilo novú polohu. Skúste to znova.'; + + @override + String map_poiClusterTitle(int count) { + return 'Značiek tu: $count'; + } + + @override + String map_poiClusterSemantics(int count) { + return 'Zdieľané značky: $count. Klepnutím ich zobrazíte.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Vy a značky: $count'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Zdieľaná značka: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Priblíženie $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Sťahovanie bolo zrušené. Uložených dlaždíc: $count.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Oblasť je príliš veľká'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Táto oblasť vyžaduje $count dlaždíc, čo je viac ako limit $max. Vyberte menšiu oblasť alebo znížte maximálne priblíženie.'; + } + + @override + String get chat_clearChatConfirm => + 'Týmto sa z tohto zariadenia vymažú všetky správy v tejto konverzácii. Túto akciu nie je možné vrátiť späť.'; + + @override + String get channels_clearChatConfirm => + 'Týmto sa z tohto zariadenia vymažú všetky správy v tomto kanáli vrátane prijatých obrázkov. Túto akciu nie je možné vrátiť späť.'; + + @override + String get channels_timeNow => 'teraz'; + + @override + String channels_timeMinutes(int minutes) { + return '${minutes}m'; + } + + @override + String channels_timeHours(int hours) { + return '${hours}h'; + } + + @override + String channels_timeDays(int days) { + return '${days}d'; + } + + @override + String channels_indexChip(int index) { + return 'KAN $index'; + } + + @override + String get reaction_unknownSender => 'Neznámy'; + + @override + String get pathMap_noSelfGpsFix => 'Lokálny uzol nemá GPS fix'; + + @override + String pathTrace_sendFailed(String error) { + return 'Sledovanie cesty sa nepodarilo odoslať: $error'; + } + + @override + String get losErrorNoInternet => + 'Údaje o nadmorskej výške vyžadujú pripojenie k internetu'; + + @override + String get losResultStale => 'Zastarané: výška antény sa zmenila'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Načítavajú sa telemetrické údaje…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Nie ste pripojení k rádiu. Pripojte sa a skúste to znova.'; + + @override + String get settings_requiresConnection => 'Na použitie pripojte rádio'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Neplatný výkon TX ($min až $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => + 'Nastavenia kontaktu boli uložené'; + + @override + String get settings_batteryToggleHint => + 'Klepnutím prepnete medzi percentami a napätím'; + + @override + String get settings_publicKeyCopyHint => 'Kopírovať verejný kľúč'; + + @override + String get settings_locationClearHelper => + 'Ak chcete odstrániť svoju polohu, nechajte obe polia prázdne.'; + + @override + String get settings_locationCleared => 'Poloha bola odstránená'; + + @override + String get settings_regionFetchDiscovering => 'Hľadajú sa blízke opakovače…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Dopytuje sa opakovač $current z $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Zatiaľ nie sú známe žiadne opakovače. Pridajte opakovač medzi kontakty alebo počkajte na jeho oznam a skúste to znova.'; + + @override + String get settings_regionFetchNoneResponded => + 'Blízke opakovače neodpovedali. Priblížte sa k opakovaču a skúste to znova.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Smerovanie'; + + @override + String get appSettings_imageMessagesSection => 'Obrazové správy'; + + @override + String get appSettings_showApiKey => 'Zobraziť API kľúč'; + + @override + String get appSettings_hideApiKey => 'Skryť API kľúč'; + + @override + String get translation_defaultModelName => 'Model'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Rádio je odpojené'; + + @override + String get repeater_radioDisconnectedHint => + 'Znova sa pripojte k rádiu, aby ste mohli odosielať príkazy, obnovovať alebo ukladať zmeny.'; + + @override + String get repeater_cliSend => 'Odoslať príkaz'; + + @override + String get repeater_cliCopyTranscript => 'Kopírovať prepis'; + + @override + String get repeater_cliShareTranscript => 'Zdieľať prepis'; + + @override + String get repeater_cliTranscriptCopied => 'Prepis bol skopírovaný'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Vymazať históriu príkazov? Túto akciu nie je možné vrátiť späť.'; + + @override + String get repeater_cliSearchCommands => 'Hľadať príkazy'; + + @override + String get repeater_cliNoMatchingCommands => 'Žiadne zodpovedajúce príkazy'; + + @override + String get debugLog_clearConfirm => + 'Vymazať všetky záznamy denníka? Túto akciu nie je možné vrátiť späť.'; + + @override + String get repeater_unsavedChangesTitle => 'Neuložené zmeny'; + + @override + String get repeater_unsavedChangesMessage => + 'Máte zmeny, ktoré neboli uložené do opakovača.'; + + @override + String get repeater_discardChanges => 'Zahodiť'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: príkaz bol odoslaný. Opakovač na tento príkaz neodpovedá.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: hodnota $value nie je platná'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Výkon TX $value je mimo rozsah ($min až $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Súkromný kľúč musí mať presne $length hexadecimálnych znakov'; + } + + @override + String get contacts_advertFailed => 'Oznam sa nepodarilo odoslať'; + + @override + String get contacts_manageGroups => 'Spravovať skupiny'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Pripojené k'; + + @override + String get usbChooseSerialPort => 'Vyberte sériový port'; + + @override + String neighbors_durationSeconds(String seconds) { + return '${seconds}s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '${minutes}m ${seconds}s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '${hours}h ${minutes}m'; + } } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index d84d6857..88583058 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -5768,4 +5768,400 @@ class AppLocalizationsSl extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Slikovnega modela ni bilo mogoče prenesti: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Skrij: skrito, dokler ne zapustite zemljevida.'; + + @override + String get map_markerRemoveHint => + 'Odstrani: ostane skrito, dokler ga ne obnovite v meniju filtra.'; + + @override + String get map_markerRemoved => 'Oznaka odstranjena'; + + @override + String get map_restoreRemovedMarkers => 'Obnovi odstranjene oznake'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return 'Odstranjenih: $count'; + } + + @override + String map_markersRestored(int count) { + return 'Obnovljenih oznak: $count'; + } + + @override + String get map_setLocationConfirmTitle => 'Nastavim kot vašo lokacijo?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Vaše vozlišče bo oglaševalo ta položaj:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Nastavi lokacijo'; + + @override + String get map_locationSetSuccess => 'Lokacija vozlišča posodobljena'; + + @override + String get map_locationSetFailed => + 'Naprava ni potrdila nove lokacije. Poskusite znova.'; + + @override + String map_poiClusterTitle(int count) { + return 'Oznak tukaj: $count'; + } + + @override + String map_poiClusterSemantics(int count) { + return 'Deljenih oznak: $count. Tapnite za prikaz seznama.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Vi in oznak: $count'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Deljena oznaka: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Povečava $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Prenos preklican. V predpomnilniku je $count ploščic.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Območje je preveliko'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'To območje potrebuje $count ploščic, kar presega omejitev $max. Izberite manjše območje ali zmanjšajte največjo povečavo.'; + } + + @override + String get chat_clearChatConfirm => + 'S te naprave bodo izbrisana vsa sporočila v tem pogovoru. Dejanja ni mogoče razveljaviti.'; + + @override + String get channels_clearChatConfirm => + 'S te naprave bodo izbrisana vsa sporočila v tem kanalu, vključno s prejetimi slikami. Dejanja ni mogoče razveljaviti.'; + + @override + String get channels_timeNow => 'zdaj'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes min'; + } + + @override + String channels_timeHours(int hours) { + return '$hours h'; + } + + @override + String channels_timeDays(int days) { + return '$days d'; + } + + @override + String channels_indexChip(int index) { + return 'KAN $index'; + } + + @override + String get reaction_unknownSender => 'Neznano'; + + @override + String get pathMap_noSelfGpsFix => 'Lokalno vozlišče nima GPS-a'; + + @override + String pathTrace_sendFailed(String error) { + return 'Poti ni bilo mogoče poslati: $error'; + } + + @override + String get losErrorNoInternet => + 'Podatki o nadmorski višini zahtevajo internetno povezavo'; + + @override + String get losResultStale => 'Zastarelo: višina antene se je spremenila'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Nalaganje telemetrije…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Ni povezave z radiem. Povežite se in poskusite znova.'; + + @override + String get settings_requiresConnection => 'Za to se povežite z radiem'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Neveljavna moč TX ($min do $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Nastavitve stika shranjene'; + + @override + String get settings_batteryToggleHint => + 'Tapnite za preklop med odstotki in napetostjo'; + + @override + String get settings_publicKeyCopyHint => 'Kopiraj javni ključ'; + + @override + String get settings_locationClearHelper => + 'Obe polji pustite prazni, če želite odstraniti svojo lokacijo.'; + + @override + String get settings_locationCleared => 'Lokacija odstranjena'; + + @override + String get settings_regionFetchDiscovering => 'Iskanje bližnjih ponovitelj…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Spraševanje ponovitelja $current od $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Zaenkrat ni znanih ponovitelj. Dodajte ponovitelj kot stik ali počakajte, da se oglasi, nato poskusite znova.'; + + @override + String get settings_regionFetchNoneResponded => + 'Noben bližnji ponovitelj ni odgovoril. Približajte se ponovitelju in poskusite znova.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Usmerjanje'; + + @override + String get appSettings_imageMessagesSection => 'Sporočila s slikami'; + + @override + String get appSettings_showApiKey => 'Pokaži API ključ'; + + @override + String get appSettings_hideApiKey => 'Skrij API ključ'; + + @override + String get translation_defaultModelName => 'Model'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radio odklopljen'; + + @override + String get repeater_radioDisconnectedHint => + 'Znova se povežite z radiem, da pošljete ukaze, osvežite ali shranite spremembe.'; + + @override + String get repeater_cliSend => 'Pošlji ukaz'; + + @override + String get repeater_cliCopyTranscript => 'Kopiraj prepis'; + + @override + String get repeater_cliShareTranscript => 'Deli prepis'; + + @override + String get repeater_cliTranscriptCopied => 'Prepis kopiran'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Počistim zgodovino ukazov? Dejanja ni mogoče razveljaviti.'; + + @override + String get repeater_cliSearchCommands => 'Išči ukaze'; + + @override + String get repeater_cliNoMatchingCommands => 'Ni ustreznih ukazov'; + + @override + String get debugLog_clearConfirm => + 'Počistim vse vnose dnevnika? Dejanja ni mogoče razveljaviti.'; + + @override + String get repeater_unsavedChangesTitle => 'Neshranjene spremembe'; + + @override + String get repeater_unsavedChangesMessage => + 'Imate spremembe, ki niso shranjene v ponovitelju.'; + + @override + String get repeater_discardChanges => 'Zavrzi'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: ukaz poslan. Ponovitelj na ta ukaz ne odgovori.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value ni veljavno'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Moč TX $value je izven območja ($min do $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Zasebni ključ mora imeti točno $length šestnajstiških znakov'; + } + + @override + String get contacts_advertFailed => 'Oglasa ni bilo mogoče poslati'; + + @override + String get contacts_manageGroups => 'Upravljaj skupine'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Povezano z'; + + @override + String get usbChooseSerialPort => 'Izberite serijska vrata'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours h $minutes min'; + } } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index c760c91f..f6be1117 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -5734,4 +5734,400 @@ class AppLocalizationsSv extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Bildmodellen kunde inte laddas ned: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => 'Dölj: dold tills du lämnar kartan.'; + + @override + String get map_markerRemoveHint => + 'Ta bort: förblir dold tills du återställer den från filtermenyn.'; + + @override + String get map_markerRemoved => 'Markör borttagen'; + + @override + String get map_restoreRemovedMarkers => 'Återställ borttagna markörer'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '$count borttagna'; + } + + @override + String map_markersRestored(int count) { + return 'Återställde $count markörer'; + } + + @override + String get map_setLocationConfirmTitle => 'Ange som din plats?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Din nod kommer att annonsera denna position:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Ange plats'; + + @override + String get map_locationSetSuccess => 'Nodens plats uppdaterad'; + + @override + String get map_locationSetFailed => + 'Enheten bekräftade inte den nya platsen. Försök igen.'; + + @override + String map_poiClusterTitle(int count) { + return '$count markörer här'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count delade markörer. Tryck för att visa dem.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Du och $count markörer'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Delad markör: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Zoom $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Nedladdningen avbröts. $count brickor cachades.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Området är för stort'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Det här området kräver $count brickor, vilket överskrider gränsen på $max. Välj ett mindre område eller sänk maximal zoom.'; + } + + @override + String get chat_clearChatConfirm => + 'Detta raderar alla meddelanden i den här konversationen från den här enheten. Det går inte att ångra.'; + + @override + String get channels_clearChatConfirm => + 'Detta raderar alla meddelanden i den här kanalen från den här enheten, inklusive mottagna bilder. Det går inte att ångra.'; + + @override + String get channels_timeNow => 'nu'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes min'; + } + + @override + String channels_timeHours(int hours) { + return '$hours h'; + } + + @override + String channels_timeDays(int days) { + return '$days d'; + } + + @override + String channels_indexChip(int index) { + return 'KAN $index'; + } + + @override + String get reaction_unknownSender => 'Okänd'; + + @override + String get pathMap_noSelfGpsFix => 'Den lokala noden har ingen GPS-fix'; + + @override + String pathTrace_sendFailed(String error) { + return 'Kunde inte skicka sökvägsspårningen: $error'; + } + + @override + String get losErrorNoInternet => 'Höjddata kräver internetanslutning'; + + @override + String get losResultStale => 'Föråldrat: antennhöjden har ändrats'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => 'Läser in telemetri…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => + 'Inte ansluten till en radio. Anslut och försök igen.'; + + @override + String get settings_requiresConnection => + 'Anslut till en radio för att använda detta'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Ogiltig TX-effekt ($min till $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => 'Kontaktinställningar sparade'; + + @override + String get settings_batteryToggleHint => + 'Tryck för att växla mellan procent och spänning'; + + @override + String get settings_publicKeyCopyHint => 'Kopiera publik nyckel'; + + @override + String get settings_locationClearHelper => + 'Lämna båda fälten tomma för att ta bort din plats.'; + + @override + String get settings_locationCleared => 'Platsen borttagen'; + + @override + String get settings_regionFetchDiscovering => + 'Söker efter repeatrar i närheten…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Frågar repeater $current av $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Inga repeatrar är kända ännu. Lägg till en repeater som kontakt eller vänta tills en annonserar, och försök sedan igen.'; + + @override + String get settings_regionFetchNoneResponded => + 'Ingen repeater i närheten svarade. Flytta dig närmare en repeater och försök igen.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Routing'; + + @override + String get appSettings_imageMessagesSection => 'Bildmeddelanden'; + + @override + String get appSettings_showApiKey => 'Visa API-nyckel'; + + @override + String get appSettings_hideApiKey => 'Dölj API-nyckel'; + + @override + String get translation_defaultModelName => 'Modell'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total MB ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => 'Radion frånkopplad'; + + @override + String get repeater_radioDisconnectedHint => + 'Återanslut till din radio för att skicka kommandon, uppdatera eller spara ändringar.'; + + @override + String get repeater_cliSend => 'Skicka kommando'; + + @override + String get repeater_cliCopyTranscript => 'Kopiera utskrift'; + + @override + String get repeater_cliShareTranscript => 'Dela utskrift'; + + @override + String get repeater_cliTranscriptCopied => 'Utskrift kopierad'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Rensa kommandohistoriken? Det går inte att ångra.'; + + @override + String get repeater_cliSearchCommands => 'Sök kommandon'; + + @override + String get repeater_cliNoMatchingCommands => 'Inga matchande kommandon'; + + @override + String get debugLog_clearConfirm => + 'Rensa alla loggposter? Det går inte att ångra.'; + + @override + String get repeater_unsavedChangesTitle => 'Osparade ändringar'; + + @override + String get repeater_unsavedChangesMessage => + 'Du har ändringar som inte har sparats i repeatern.'; + + @override + String get repeater_discardChanges => 'Förkasta'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: kommando skickat. Repeatern svarar inte på detta kommando.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: $value är inte giltigt'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX-effekt $value ligger utanför intervallet ($min till $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Privat nyckel måste vara exakt $length hexadecimala tecken'; + } + + @override + String get contacts_advertFailed => 'Kunde inte skicka annonsen'; + + @override + String get contacts_manageGroups => 'Hantera grupper'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Ansluten till'; + + @override + String get usbChooseSerialPort => 'Välj serieport'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds s'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours h $minutes min'; + } } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 72ef4c94..4d57e40e 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -5805,4 +5805,401 @@ class AppLocalizationsUk extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return 'Не вдалося завантажити модель зображень: $error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => + 'Приховати: маркер буде прихований, доки ви не покинете карту.'; + + @override + String get map_markerRemoveHint => + 'Видалити: маркер залишатиметься прихованим, доки ви не відновите його в меню фільтра.'; + + @override + String get map_markerRemoved => 'Маркер видалено'; + + @override + String get map_restoreRemovedMarkers => 'Відновити видалені маркери'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return 'Видалено: $count'; + } + + @override + String map_markersRestored(int count) { + return 'Відновлено маркерів: $count'; + } + + @override + String get map_setLocationConfirmTitle => 'Встановити як вашу геопозицію?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return 'Ваш вузол оголошуватиме цю позицію:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => 'Встановити позицію'; + + @override + String get map_locationSetSuccess => 'Позицію вузла оновлено'; + + @override + String get map_locationSetFailed => + 'Пристрій не підтвердив нову позицію. Спробуйте ще раз.'; + + @override + String map_poiClusterTitle(int count) { + return 'Маркерів тут: $count'; + } + + @override + String map_poiClusterSemantics(int count) { + return 'Спільних маркерів: $count. Торкніться, щоб відкрити список.'; + } + + @override + String map_youWithMarkers(int count) { + return 'Ви та маркерів: $count'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return 'Спільний маркер: $label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name, $type, $status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return 'Масштаб $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size Б'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size КБ'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size МБ'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size ГБ'; + } + + @override + String mapCache_downloadCancelled(int count) { + return 'Завантаження скасовано. Кешовано тайлів: $count.'; + } + + @override + String get mapCache_tooManyTilesTitle => 'Область завелика'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return 'Для цієї області потрібно тайлів: $count, що перевищує ліміт $max. Виберіть меншу область або зменште максимальний масштаб.'; + } + + @override + String get chat_clearChatConfirm => + 'Це видалить усі повідомлення цього чату з цього пристрою. Дію не можна скасувати.'; + + @override + String get channels_clearChatConfirm => + 'Це видалить усі повідомлення цього каналу з цього пристрою, включно з отриманими зображеннями. Дію не можна скасувати.'; + + @override + String get channels_timeNow => 'зараз'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutesхв'; + } + + @override + String channels_timeHours(int hours) { + return '$hoursгод'; + } + + @override + String channels_timeDays(int days) { + return '$daysд'; + } + + @override + String channels_indexChip(int index) { + return 'КАН $index'; + } + + @override + String get reaction_unknownSender => 'Невідомо'; + + @override + String get pathMap_noSelfGpsFix => 'Локальний вузол не має GPS-фіксації'; + + @override + String pathTrace_sendFailed(String error) { + return 'Не вдалося надіслати трасування шляху: $error'; + } + + @override + String get losErrorNoInternet => + 'Для даних про висоти потрібне підключення до інтернету'; + + @override + String get losResultStale => 'Застаріло: висоту антени змінено'; + + @override + String losSnrValue(String snr) { + return '$snr дБ'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency МГц'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'км'; + + @override + String get units_mi => 'миль'; + + @override + String get units_m => 'м'; + + @override + String get units_ft => 'фт'; + + @override + String get telemetry_loading => 'Завантаження телеметрії…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet фт'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet фт'; + } + + @override + String get settings_notConnectedError => + 'Немає підключення до радіо. Підключіться й спробуйте ще раз.'; + + @override + String get settings_requiresConnection => + 'Підключіться до радіо, щоб скористатися цим'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'Недопустима потужність TX (від $min до $max дБм)'; + } + + @override + String get settings_contactSettingsSaved => 'Налаштування контакту збережено'; + + @override + String get settings_batteryToggleHint => + 'Торкніться, щоб перемкнути між відсотками та напругою'; + + @override + String get settings_publicKeyCopyHint => 'Копіювати публічний ключ'; + + @override + String get settings_locationClearHelper => + 'Залиште обидва поля порожніми, щоб видалити вашу геопозицію.'; + + @override + String get settings_locationCleared => 'Геопозицію видалено'; + + @override + String get settings_regionFetchDiscovering => 'Пошук ближніх ретрансляторів…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return 'Опитування ретранслятора $current з $total…'; + } + + @override + String get settings_regionFetchNoRepeaters => + 'Ретранслятори поки невідомі. Додайте ретранслятор до контактів або дочекайтеся його оголошення, а потім спробуйте ще раз.'; + + @override + String get settings_regionFetchNoneResponded => + 'Ближні ретранслятори не відповіли. Підійдіть ближче до ретранслятора й спробуйте ще раз.'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => 'Маршрутизація'; + + @override + String get appSettings_imageMessagesSection => 'Повідомлення із зображеннями'; + + @override + String get appSettings_showApiKey => 'Показати API-ключ'; + + @override + String get appSettings_hideApiKey => 'Приховати API-ключ'; + + @override + String get translation_defaultModelName => 'Модель'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName: $current МБ'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName: $current / $total МБ ($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size МБ • $source'; + } + + @override + String get repeater_radioDisconnected => 'Радіо відключено'; + + @override + String get repeater_radioDisconnectedHint => + 'Підключіться до радіо повторно, щоб надсилати команди, оновлювати дані або зберігати зміни.'; + + @override + String get repeater_cliSend => 'Надіслати команду'; + + @override + String get repeater_cliCopyTranscript => 'Копіювати журнал'; + + @override + String get repeater_cliShareTranscript => 'Поділитися журналом'; + + @override + String get repeater_cliTranscriptCopied => 'Журнал скопійовано'; + + @override + String get repeater_cliClearHistoryConfirm => + 'Очистити історію команд? Дію не можна скасувати.'; + + @override + String get repeater_cliSearchCommands => 'Пошук команд'; + + @override + String get repeater_cliNoMatchingCommands => 'Немає відповідних команд'; + + @override + String get debugLog_clearConfirm => + 'Очистити всі записи журналу? Дію не можна скасувати.'; + + @override + String get repeater_unsavedChangesTitle => 'Незбережені зміни'; + + @override + String get repeater_unsavedChangesMessage => + 'У вас є зміни, не збережені в ретрансляторі.'; + + @override + String get repeater_discardChanges => 'Відхилити'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action: команду надіслано. Ретранслятор не відповідає на цю команду.'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting: значення $value недопустиме'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'Потужність TX $value поза діапазоном (від $min до $max дБм)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return 'Приватний ключ має містити рівно $length шістнадцяткових символів'; + } + + @override + String get contacts_advertFailed => 'Не вдалося надіслати оголошення'; + + @override + String get contacts_manageGroups => 'Керування групами'; + + @override + String community_shortId(String id) { + return 'ID: $id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => 'Підключено до'; + + @override + String get usbChooseSerialPort => 'Виберіть послідовний порт'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$secondsс'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutesхв $secondsс'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hoursгод $minutesхв'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 88df6c9c..471da3d8 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5378,4 +5378,386 @@ class AppLocalizationsZh extends AppLocalizations { String imageMessages_downloadFailedWithError(String error) { return '无法下载图像模型:$error'; } + + @override + String get map_nodeId => 'ID'; + + @override + String get map_markerHideHint => '隐藏:离开地图前保持隐藏。'; + + @override + String get map_markerRemoveHint => '移除:在从筛选菜单中恢复之前保持隐藏。'; + + @override + String get map_markerRemoved => '标记已移除'; + + @override + String get map_restoreRemovedMarkers => '恢复已移除的标记'; + + @override + String map_restoreRemovedMarkersSubtitle(int count) { + return '已移除 $count 个'; + } + + @override + String map_markersRestored(int count) { + return '已恢复 $count 个标记'; + } + + @override + String get map_setLocationConfirmTitle => '设为你的位置?'; + + @override + String map_setLocationConfirmBody(String lat, String lon) { + return '你的节点将广播此位置:\n$lat, $lon'; + } + + @override + String get map_setLocationAction => '设置位置'; + + @override + String get map_locationSetSuccess => '节点位置已更新'; + + @override + String get map_locationSetFailed => '设备未确认新位置。请重试。'; + + @override + String map_poiClusterTitle(int count) { + return '此处有 $count 个标记'; + } + + @override + String map_poiClusterSemantics(int count) { + return '$count 个共享标记。点按以查看列表。'; + } + + @override + String map_youWithMarkers(int count) { + return '你和 $count 个标记'; + } + + @override + String map_sharedMarkerSemantics(String label) { + return '共享标记:$label'; + } + + @override + String map_nodeMarkerSemantics(String name, String type, String status) { + return '$name,$type,$status'; + } + + @override + String mapCache_zoomLevel(int zoom) { + return '缩放 $zoom'; + } + + @override + String mapCache_sizeBytes(String size) { + return '$size B'; + } + + @override + String mapCache_sizeKilobytes(String size) { + return '$size KB'; + } + + @override + String mapCache_sizeMegabytes(String size) { + return '$size MB'; + } + + @override + String mapCache_sizeGigabytes(String size) { + return '$size GB'; + } + + @override + String mapCache_downloadCancelled(int count) { + return '下载已取消。已缓存 $count 个图块。'; + } + + @override + String get mapCache_tooManyTilesTitle => '区域过大'; + + @override + String mapCache_tooManyTiles(int count, int max) { + return '此区域需要 $count 个图块,超过 $max 的上限。请选择更小的区域或降低最大缩放级别。'; + } + + @override + String get chat_clearChatConfirm => '这将从此设备上清除此对话中的所有消息,且无法撤销。'; + + @override + String get channels_clearChatConfirm => '这将从此设备上清除此频道中的所有消息(包括已接收的图片),且无法撤销。'; + + @override + String get channels_timeNow => '刚刚'; + + @override + String channels_timeMinutes(int minutes) { + return '$minutes分钟'; + } + + @override + String channels_timeHours(int hours) { + return '$hours小时'; + } + + @override + String channels_timeDays(int days) { + return '$days天'; + } + + @override + String channels_indexChip(int index) { + return 'CH $index'; + } + + @override + String get reaction_unknownSender => '未知'; + + @override + String get pathMap_noSelfGpsFix => '本地节点没有 GPS 定位'; + + @override + String pathTrace_sendFailed(String error) { + return '无法发送路径追踪:$error'; + } + + @override + String get losErrorNoInternet => '海拔数据需要网络连接'; + + @override + String get losResultStale => '结果已过期:天线高度已更改'; + + @override + String losSnrValue(String snr) { + return '$snr dB'; + } + + @override + String losFrequencyValue(String frequency) { + return '$frequency MHz'; + } + + @override + String losKFactorValue(String kFactor) { + return 'k=$kFactor'; + } + + @override + String get losEndpointA => 'A'; + + @override + String get losEndpointB => 'B'; + + @override + String get units_km => 'km'; + + @override + String get units_mi => 'mi'; + + @override + String get units_m => 'm'; + + @override + String get units_ft => 'ft'; + + @override + String get telemetry_loading => '正在加载遥测数据…'; + + @override + String telemetry_axisValue(String x, String y, String z) { + return 'X: $x, Y: $y, Z: $z'; + } + + @override + String telemetry_colourValue(String red, String green, String blue) { + return 'R: $red, G: $green, B: $blue'; + } + + @override + String telemetry_altitudeValueFeet(String feet) { + return '$feet ft'; + } + + @override + String telemetry_distanceValueFeet(String feet) { + return '$feet ft'; + } + + @override + String get settings_notConnectedError => '未连接到电台。请连接后重试。'; + + @override + String get settings_requiresConnection => '请连接电台后使用'; + + @override + String settings_txPowerInvalidRange(int min, int max) { + return 'TX 功率无效($min 至 $max dBm)'; + } + + @override + String get settings_contactSettingsSaved => '联系人设置已保存'; + + @override + String get settings_batteryToggleHint => '点按可在百分比和电压之间切换'; + + @override + String get settings_publicKeyCopyHint => '复制公钥'; + + @override + String get settings_locationClearHelper => '将两个字段都留空即可移除你的位置。'; + + @override + String get settings_locationCleared => '位置已移除'; + + @override + String get settings_regionFetchDiscovering => '正在查找附近的中继器…'; + + @override + String settings_regionFetchProgress(int current, int total) { + return '正在询问第 $current/$total 个中继器…'; + } + + @override + String get settings_regionFetchNoRepeaters => + '目前还没有已知的中继器。请将中继器添加为联系人,或等待其广播后重试。'; + + @override + String get settings_regionFetchNoneResponded => '附近没有中继器响应。请靠近中继器后重试。'; + + @override + String appSettings_sourceSummary(String label, String description) { + return '$label - $description'; + } + + @override + String get appSettings_routingSection => '路由'; + + @override + String get appSettings_imageMessagesSection => '图片消息'; + + @override + String get appSettings_showApiKey => '显示 API 密钥'; + + @override + String get appSettings_hideApiKey => '隐藏 API 密钥'; + + @override + String get translation_defaultModelName => '模型'; + + @override + String translation_downloadProgressBytes(String fileName, String current) { + return '$fileName:$current MB'; + } + + @override + String translation_downloadProgressTotal( + String fileName, + String current, + String total, + String percent, + ) { + return '$fileName:$current / $total MB($percent%)'; + } + + @override + String translation_downloadedModelDetails(String size, String source) { + return '$size MB • $source'; + } + + @override + String get repeater_radioDisconnected => '电台已断开连接'; + + @override + String get repeater_radioDisconnectedHint => '请重新连接电台以发送命令、刷新或保存更改。'; + + @override + String get repeater_cliSend => '发送命令'; + + @override + String get repeater_cliCopyTranscript => '复制记录'; + + @override + String get repeater_cliShareTranscript => '分享记录'; + + @override + String get repeater_cliTranscriptCopied => '记录已复制'; + + @override + String get repeater_cliClearHistoryConfirm => '清除命令历史?此操作无法撤销。'; + + @override + String get repeater_cliSearchCommands => '搜索命令'; + + @override + String get repeater_cliNoMatchingCommands => '没有匹配的命令'; + + @override + String get debugLog_clearConfirm => '清除所有日志条目?此操作无法撤销。'; + + @override + String get repeater_unsavedChangesTitle => '未保存的更改'; + + @override + String get repeater_unsavedChangesMessage => '你有尚未保存到中继器的更改。'; + + @override + String get repeater_discardChanges => '放弃'; + + @override + String repeater_actionSentNoReply(String action) { + return '$action:命令已发送。中继器不会回复此命令。'; + } + + @override + String repeater_invalidSettingValue(String setting, String value) { + return '$setting:$value 无效'; + } + + @override + String repeater_txPowerOutOfRange(String value, int min, int max) { + return 'TX 功率 $value 超出范围($min 至 $max dBm)'; + } + + @override + String repeater_prvKeyLengthError(int length) { + return '私钥必须恰好为 $length 个十六进制字符'; + } + + @override + String get contacts_advertFailed => '无法发送广播'; + + @override + String get contacts_manageGroups => '管理分组'; + + @override + String community_shortId(String id) { + return 'ID:$id…'; + } + + @override + String get tcpSectionTitle => 'TCP / IP'; + + @override + String get tcpConnectedToHeader => '已连接到'; + + @override + String get usbChooseSerialPort => '选择串口'; + + @override + String neighbors_durationSeconds(String seconds) { + return '$seconds秒'; + } + + @override + String neighbors_durationMinutes(int minutes, String seconds) { + return '$minutes分$seconds秒'; + } + + @override + String neighbors_durationHours(int hours, int minutes) { + return '$hours小时$minutes分'; + } } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 7a3e6c32..fcacaa94 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -3063,5 +3063,103 @@ "qr_cameraPermissionDenied": "Cameratoestemming geweigerd.\nSchakel cameratoegang in bij de instellingen.", "qr_cameraUnsupported": "Camera wordt niet ondersteund op dit apparaat.", "qr_cameraStartFailed": "Kan de camera niet starten.\n{details}", - "imageMessages_downloadFailedWithError": "Het afbeeldingsmodel kon niet worden gedownload: {error}" + "imageMessages_downloadFailedWithError": "Het afbeeldingsmodel kon niet worden gedownload: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Verbergen: verborgen totdat je de kaart verlaat.", + "map_markerRemoveHint": "Verwijderen: blijft verborgen totdat je het herstelt via het filtermenu.", + "map_markerRemoved": "Markering verwijderd", + "map_restoreRemovedMarkers": "Verwijderde markeringen herstellen", + "map_restoreRemovedMarkersSubtitle": "{count} verwijderd", + "map_markersRestored": "{count} markeringen hersteld", + "map_setLocationConfirmTitle": "Instellen als jouw locatie?", + "map_setLocationConfirmBody": "Je node adverteert deze positie:\n{lat}, {lon}", + "map_setLocationAction": "Locatie instellen", + "map_locationSetSuccess": "Nodelocatie bijgewerkt", + "map_locationSetFailed": "Het apparaat heeft de nieuwe locatie niet bevestigd. Probeer het opnieuw.", + "map_poiClusterTitle": "{count} markeringen hier", + "map_poiClusterSemantics": "{count} gedeelde markeringen. Tik om ze weer te geven.", + "map_youWithMarkers": "Jij en {count} markeringen", + "map_sharedMarkerSemantics": "Gedeelde markering: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Download geannuleerd. {count} tegels in cache opgeslagen.", + "mapCache_tooManyTilesTitle": "Gebied te groot", + "mapCache_tooManyTiles": "Dit gebied vereist {count} tegels, meer dan de limiet van {max}. Kies een kleiner gebied of verlaag de maximale zoom.", + "chat_clearChatConfirm": "Hiermee worden alle berichten in dit gesprek van dit apparaat gewist. Dit kan niet ongedaan worden gemaakt.", + "channels_clearChatConfirm": "Hiermee worden alle berichten in dit kanaal van dit apparaat gewist, inclusief ontvangen afbeeldingen. Dit kan niet ongedaan worden gemaakt.", + "channels_timeNow": "nu", + "channels_timeMinutes": "{minutes}m", + "channels_timeHours": "{hours}u", + "channels_timeDays": "{days}d", + "channels_indexChip": "KN {index}", + "reaction_unknownSender": "Onbekend", + "pathMap_noSelfGpsFix": "Lokale node heeft geen GPS-fix", + "pathTrace_sendFailed": "Padtracering kon niet worden verzonden: {error}", + "losErrorNoInternet": "Hoogtegegevens vereisen een internetverbinding", + "losResultStale": "Verouderd: antennehoogte is gewijzigd", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Telemetrie laden…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Niet verbonden met een radio. Maak verbinding en probeer het opnieuw.", + "settings_requiresConnection": "Maak verbinding met een radio om dit te gebruiken", + "settings_txPowerInvalidRange": "Ongeldig TX-vermogen ({min} tot {max} dBm)", + "settings_contactSettingsSaved": "Contactinstellingen opgeslagen", + "settings_batteryToggleHint": "Tik om te wisselen tussen procent en spanning", + "settings_publicKeyCopyHint": "Publieke sleutel kopiëren", + "settings_locationClearHelper": "Laat beide velden leeg om je locatie te verwijderen.", + "settings_locationCleared": "Locatie verwijderd", + "settings_regionFetchDiscovering": "Repeaters in de buurt zoeken…", + "settings_regionFetchProgress": "Repeater {current} van {total} wordt gevraagd…", + "settings_regionFetchNoRepeaters": "Er zijn nog geen repeaters bekend. Voeg een repeater toe als contact of wacht tot er een adverteert en probeer het dan opnieuw.", + "settings_regionFetchNoneResponded": "Geen repeaters in de buurt hebben geantwoord. Ga dichter bij een repeater staan en probeer het opnieuw.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Routering", + "appSettings_imageMessagesSection": "Afbeeldingsberichten", + "appSettings_showApiKey": "API-sleutel tonen", + "appSettings_hideApiKey": "API-sleutel verbergen", + "translation_defaultModelName": "Model", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Radio losgekoppeld", + "repeater_radioDisconnectedHint": "Maak opnieuw verbinding met je radio om commando's te verzenden, te vernieuwen of wijzigingen op te slaan.", + "repeater_cliSend": "Commando verzenden", + "repeater_cliCopyTranscript": "Transcript kopiëren", + "repeater_cliShareTranscript": "Transcript delen", + "repeater_cliTranscriptCopied": "Transcript gekopieerd", + "repeater_cliClearHistoryConfirm": "Commandogeschiedenis wissen? Dit kan niet ongedaan worden gemaakt.", + "repeater_cliSearchCommands": "Commando's zoeken", + "repeater_cliNoMatchingCommands": "Geen overeenkomende commando's", + "debugLog_clearConfirm": "Alle logboekvermeldingen wissen? Dit kan niet ongedaan worden gemaakt.", + "repeater_unsavedChangesTitle": "Niet-opgeslagen wijzigingen", + "repeater_unsavedChangesMessage": "Je hebt wijzigingen die niet zijn opgeslagen op de repeater.", + "repeater_discardChanges": "Verwerpen", + "repeater_actionSentNoReply": "{action}: commando verzonden. De repeater antwoordt niet op dit commando.", + "repeater_invalidSettingValue": "{setting}: {value} is niet geldig", + "repeater_txPowerOutOfRange": "TX-vermogen {value} valt buiten het bereik ({min} tot {max} dBm)", + "repeater_prvKeyLengthError": "De privésleutel moet precies {length} hexadecimale tekens bevatten", + "contacts_advertFailed": "Advertentie kon niet worden verzonden", + "contacts_manageGroups": "Groepen beheren", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Verbonden met", + "usbChooseSerialPort": "Seriële poort kiezen", + "neighbors_durationSeconds": "{seconds}s", + "neighbors_durationMinutes": "{minutes}m {seconds}s", + "neighbors_durationHours": "{hours}u {minutes}m" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index c6bdd2b0..f6b82399 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3195,5 +3195,103 @@ "qr_cameraPermissionDenied": "Odmowa dostępu do aparatu.\nWłącz dostęp do aparatu w ustawieniach.", "qr_cameraUnsupported": "Aparat nie jest obsługiwany na tym urządzeniu.", "qr_cameraStartFailed": "Nie udało się uruchomić aparatu.\n{details}", - "imageMessages_downloadFailedWithError": "Nie udało się pobrać modelu obrazów: {error}" + "imageMessages_downloadFailedWithError": "Nie udało się pobrać modelu obrazów: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Ukryj: ukryty do czasu opuszczenia mapy.", + "map_markerRemoveHint": "Usuń: pozostaje ukryty, dopóki nie przywrócisz go z menu filtrów.", + "map_markerRemoved": "Znacznik usunięty", + "map_restoreRemovedMarkers": "Przywróć usunięte znaczniki", + "map_restoreRemovedMarkersSubtitle": "Usunięto: {count}", + "map_markersRestored": "Przywrócono znaczniki: {count}", + "map_setLocationConfirmTitle": "Ustawić jako Twoją lokalizację?", + "map_setLocationConfirmBody": "Twój węzeł będzie ogłaszał tę pozycję:\n{lat}, {lon}", + "map_setLocationAction": "Ustaw lokalizację", + "map_locationSetSuccess": "Zaktualizowano lokalizację węzła", + "map_locationSetFailed": "Urządzenie nie potwierdziło nowej lokalizacji. Spróbuj ponownie.", + "map_poiClusterTitle": "Znaczniki tutaj: {count}", + "map_poiClusterSemantics": "Udostępnione znaczniki: {count}. Dotknij, aby je wyświetlić.", + "map_youWithMarkers": "Ty i znaczniki: {count}", + "map_sharedMarkerSemantics": "Udostępniony znacznik: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Pobieranie anulowane. Zapisano w pamięci podręcznej kafelki: {count}.", + "mapCache_tooManyTilesTitle": "Obszar zbyt duży", + "mapCache_tooManyTiles": "Ten obszar wymaga {count} kafelków, co przekracza limit {max}. Wybierz mniejszy obszar lub zmniejsz maksymalny zoom.", + "chat_clearChatConfirm": "Spowoduje to usunięcie z tego urządzenia wszystkich wiadomości w tej rozmowie. Tej operacji nie można cofnąć.", + "channels_clearChatConfirm": "Spowoduje to usunięcie z tego urządzenia wszystkich wiadomości w tym kanale, w tym odebranych obrazów. Tej operacji nie można cofnąć.", + "channels_timeNow": "teraz", + "channels_timeMinutes": "{minutes} min", + "channels_timeHours": "{hours} godz.", + "channels_timeDays": "{days} d", + "channels_indexChip": "KN {index}", + "reaction_unknownSender": "Nieznany", + "pathMap_noSelfGpsFix": "Lokalny węzeł nie ma pozycji GPS", + "pathTrace_sendFailed": "Nie udało się wysłać śledzenia trasy: {error}", + "losErrorNoInternet": "Dane wysokościowe wymagają połączenia z internetem", + "losResultStale": "Nieaktualne: zmieniono wysokość anteny", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Wczytywanie telemetrii…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Brak połączenia z radiem. Połącz się i spróbuj ponownie.", + "settings_requiresConnection": "Połącz się z radiem, aby z tego korzystać", + "settings_txPowerInvalidRange": "Nieprawidłowa moc TX (od {min} do {max} dBm)", + "settings_contactSettingsSaved": "Zapisano ustawienia kontaktu", + "settings_batteryToggleHint": "Dotknij, aby przełączyć między procentami a napięciem", + "settings_publicKeyCopyHint": "Kopiuj klucz publiczny", + "settings_locationClearHelper": "Pozostaw oba pola puste, aby usunąć swoją lokalizację.", + "settings_locationCleared": "Lokalizacja usunięta", + "settings_regionFetchDiscovering": "Wyszukiwanie pobliskich przekaźników…", + "settings_regionFetchProgress": "Odpytywanie przekaźnika {current} z {total}…", + "settings_regionFetchNoRepeaters": "Nie są jeszcze znane żadne przekaźniki. Dodaj przekaźnik jako kontakt lub poczekaj, aż któryś się ogłosi, a następnie spróbuj ponownie.", + "settings_regionFetchNoneResponded": "Żaden pobliski przekaźnik nie odpowiedział. Zbliż się do przekaźnika i spróbuj ponownie.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Routing", + "appSettings_imageMessagesSection": "Wiadomości z obrazami", + "appSettings_showApiKey": "Pokaż klucz API", + "appSettings_hideApiKey": "Ukryj klucz API", + "translation_defaultModelName": "Model", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Radio rozłączone", + "repeater_radioDisconnectedHint": "Połącz się ponownie z radiem, aby wysyłać polecenia, odświeżać lub zapisywać zmiany.", + "repeater_cliSend": "Wyślij polecenie", + "repeater_cliCopyTranscript": "Kopiuj zapis", + "repeater_cliShareTranscript": "Udostępnij zapis", + "repeater_cliTranscriptCopied": "Skopiowano zapis", + "repeater_cliClearHistoryConfirm": "Wyczyścić historię poleceń? Tej operacji nie można cofnąć.", + "repeater_cliSearchCommands": "Szukaj poleceń", + "repeater_cliNoMatchingCommands": "Brak pasujących poleceń", + "debugLog_clearConfirm": "Wyczyścić wszystkie wpisy dziennika? Tej operacji nie można cofnąć.", + "repeater_unsavedChangesTitle": "Niezapisane zmiany", + "repeater_unsavedChangesMessage": "Masz zmiany, które nie zostały zapisane w przekaźniku.", + "repeater_discardChanges": "Odrzuć", + "repeater_actionSentNoReply": "{action}: polecenie wysłane. Przekaźnik nie odpowiada na to polecenie.", + "repeater_invalidSettingValue": "{setting}: {value} jest nieprawidłowe", + "repeater_txPowerOutOfRange": "Moc TX {value} jest poza zakresem (od {min} do {max} dBm)", + "repeater_prvKeyLengthError": "Klucz prywatny musi mieć dokładnie {length} znaków szesnastkowych", + "contacts_advertFailed": "Nie udało się wysłać ogłoszenia", + "contacts_manageGroups": "Zarządzaj grupami", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Połączono z", + "usbChooseSerialPort": "Wybierz port szeregowy", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} min {seconds} s", + "neighbors_durationHours": "{hours} godz. {minutes} min" } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index e97f3421..960562d5 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3162,5 +3162,103 @@ "qr_cameraPermissionDenied": "Permissão da câmera negada.\nAtive o acesso à câmera nas configurações.", "qr_cameraUnsupported": "Câmera não compatível com este dispositivo.", "qr_cameraStartFailed": "Falha ao iniciar a câmera.\n{details}", - "imageMessages_downloadFailedWithError": "Não foi possível baixar o modelo de imagem: {error}" + "imageMessages_downloadFailedWithError": "Não foi possível baixar o modelo de imagem: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Ocultar: fica oculto até você sair do mapa.", + "map_markerRemoveHint": "Remover: continua oculto até você restaurá-lo no menu de filtros.", + "map_markerRemoved": "Marcador removido", + "map_restoreRemovedMarkers": "Restaurar marcadores removidos", + "map_restoreRemovedMarkersSubtitle": "{count} removidos", + "map_markersRestored": "{count} marcadores restaurados", + "map_setLocationConfirmTitle": "Definir como sua localização?", + "map_setLocationConfirmBody": "Seu nó vai anunciar esta posição:\n{lat}, {lon}", + "map_setLocationAction": "Definir localização", + "map_locationSetSuccess": "Localização do nó atualizada", + "map_locationSetFailed": "O dispositivo não confirmou a nova localização. Tente novamente.", + "map_poiClusterTitle": "{count} marcadores aqui", + "map_poiClusterSemantics": "{count} marcadores compartilhados. Toque para listá-los.", + "map_youWithMarkers": "Você e {count} marcadores", + "map_sharedMarkerSemantics": "Marcador compartilhado: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Download cancelado. {count} blocos em cache.", + "mapCache_tooManyTilesTitle": "Área muito grande", + "mapCache_tooManyTiles": "Esta área precisa de {count} blocos, mais do que o limite de {max}. Escolha uma área menor ou reduza o zoom máximo.", + "chat_clearChatConfirm": "Isto apaga todas as mensagens desta conversa deste dispositivo. Não é possível desfazer.", + "channels_clearChatConfirm": "Isto apaga todas as mensagens deste canal deste dispositivo, incluindo as imagens recebidas. Não é possível desfazer.", + "channels_timeNow": "agora", + "channels_timeMinutes": "{minutes}min", + "channels_timeHours": "{hours}h", + "channels_timeDays": "{days}d", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "Desconhecido", + "pathMap_noSelfGpsFix": "O nó local não tem sinal de GPS", + "pathTrace_sendFailed": "Não foi possível enviar o rastreamento de caminho: {error}", + "losErrorNoInternet": "Os dados de elevação precisam de conexão com a internet", + "losResultStale": "Desatualizado: a altura da antena mudou", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Carregando telemetria…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Sem conexão com um rádio. Conecte e tente novamente.", + "settings_requiresConnection": "Conecte-se a um rádio para usar isto", + "settings_txPowerInvalidRange": "Potência de TX inválida ({min} a {max} dBm)", + "settings_contactSettingsSaved": "Configurações do contato salvas", + "settings_batteryToggleHint": "Toque para alternar entre porcentagem e tensão", + "settings_publicKeyCopyHint": "Copiar chave pública", + "settings_locationClearHelper": "Deixe ambos os campos vazios para remover sua localização.", + "settings_locationCleared": "Localização removida", + "settings_regionFetchDiscovering": "Procurando repetidores próximos…", + "settings_regionFetchProgress": "Consultando o repetidor {current} de {total}…", + "settings_regionFetchNoRepeaters": "Ainda não há repetidores conhecidos. Adicione um repetidor como contato ou aguarde um anunciar, e tente novamente.", + "settings_regionFetchNoneResponded": "Nenhum repetidor próximo respondeu. Aproxime-se de um repetidor e tente novamente.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Roteamento", + "appSettings_imageMessagesSection": "Mensagens de imagem", + "appSettings_showApiKey": "Mostrar chave de API", + "appSettings_hideApiKey": "Ocultar chave de API", + "translation_defaultModelName": "Modelo", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Rádio desconectado", + "repeater_radioDisconnectedHint": "Reconecte-se ao seu rádio para enviar comandos, atualizar ou salvar alterações.", + "repeater_cliSend": "Enviar comando", + "repeater_cliCopyTranscript": "Copiar transcrição", + "repeater_cliShareTranscript": "Compartilhar transcrição", + "repeater_cliTranscriptCopied": "Transcrição copiada", + "repeater_cliClearHistoryConfirm": "Limpar o histórico de comandos? Não é possível desfazer.", + "repeater_cliSearchCommands": "Pesquisar comandos", + "repeater_cliNoMatchingCommands": "Nenhum comando correspondente", + "debugLog_clearConfirm": "Limpar todas as entradas do registro? Não é possível desfazer.", + "repeater_unsavedChangesTitle": "Alterações não salvas", + "repeater_unsavedChangesMessage": "Você tem alterações que não foram salvas no repetidor.", + "repeater_discardChanges": "Descartar", + "repeater_actionSentNoReply": "{action}: comando enviado. O repetidor não responde a este comando.", + "repeater_invalidSettingValue": "{setting}: {value} não é válido", + "repeater_txPowerOutOfRange": "Potência de TX {value} fora do intervalo ({min} a {max} dBm)", + "repeater_prvKeyLengthError": "A chave privada deve ter exatamente {length} caracteres hexadecimais", + "contacts_advertFailed": "Não foi possível enviar o anúncio", + "contacts_manageGroups": "Gerenciar grupos", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Conectado a", + "usbChooseSerialPort": "Escolher porta serial", + "neighbors_durationSeconds": "{seconds}s", + "neighbors_durationMinutes": "{minutes}m {seconds}s", + "neighbors_durationHours": "{hours}h {minutes}m" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 48e250a6..564d72f8 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -2459,5 +2459,103 @@ "qr_cameraPermissionDenied": "Доступ к камере запрещён.\nВключите доступ к камере в настройках.", "qr_cameraUnsupported": "Камера не поддерживается на этом устройстве.", "qr_cameraStartFailed": "Не удалось запустить камеру.\n{details}", - "imageMessages_downloadFailedWithError": "Не удалось загрузить модель изображений: {error}" + "imageMessages_downloadFailedWithError": "Не удалось загрузить модель изображений: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Скрыть: маркер скрыт, пока вы не покинете карту.", + "map_markerRemoveHint": "Удалить: маркер останется скрытым, пока вы не восстановите его в меню фильтра.", + "map_markerRemoved": "Маркер удалён", + "map_restoreRemovedMarkers": "Восстановить удалённые маркеры", + "map_restoreRemovedMarkersSubtitle": "Удалено: {count}", + "map_markersRestored": "Восстановлено маркеров: {count}", + "map_setLocationConfirmTitle": "Установить как вашу позицию?", + "map_setLocationConfirmBody": "Ваш узел будет анонсировать эту позицию:\n{lat}, {lon}", + "map_setLocationAction": "Установить позицию", + "map_locationSetSuccess": "Позиция узла обновлена", + "map_locationSetFailed": "Устройство не подтвердило новую позицию. Попробуйте снова.", + "map_poiClusterTitle": "Маркеров здесь: {count}", + "map_poiClusterSemantics": "Общих маркеров: {count}. Нажмите, чтобы открыть список.", + "map_youWithMarkers": "Вы и маркеров: {count}", + "map_sharedMarkerSemantics": "Общий маркер: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Масштаб {zoom}", + "mapCache_sizeBytes": "{size} Б", + "mapCache_sizeKilobytes": "{size} КБ", + "mapCache_sizeMegabytes": "{size} МБ", + "mapCache_sizeGigabytes": "{size} ГБ", + "mapCache_downloadCancelled": "Загрузка отменена. Кэшировано тайлов: {count}.", + "mapCache_tooManyTilesTitle": "Область слишком большая", + "mapCache_tooManyTiles": "Для этой области нужно тайлов: {count}, что больше лимита {max}. Выберите область меньше или уменьшите максимальный масштаб.", + "chat_clearChatConfirm": "Это удалит все сообщения этого чата с данного устройства. Действие нельзя отменить.", + "channels_clearChatConfirm": "Это удалит все сообщения этого канала с данного устройства, включая полученные изображения. Действие нельзя отменить.", + "channels_timeNow": "сейчас", + "channels_timeMinutes": "{minutes}м", + "channels_timeHours": "{hours}ч", + "channels_timeDays": "{days}д", + "channels_indexChip": "КАН {index}", + "reaction_unknownSender": "Неизвестно", + "pathMap_noSelfGpsFix": "У локального узла нет GPS-фиксации", + "pathTrace_sendFailed": "Не удалось отправить трассировку пути: {error}", + "losErrorNoInternet": "Для данных о высотах нужно подключение к интернету", + "losResultStale": "Устарело: высота антенны изменилась", + "losSnrValue": "{snr} дБ", + "losFrequencyValue": "{frequency} МГц", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "км", + "units_mi": "миль", + "units_m": "м", + "units_ft": "фт", + "telemetry_loading": "Загрузка телеметрии…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} фт", + "telemetry_distanceValueFeet": "{feet} фт", + "settings_notConnectedError": "Нет подключения к радио. Подключитесь и повторите попытку.", + "settings_requiresConnection": "Подключитесь к радио, чтобы использовать это", + "settings_txPowerInvalidRange": "Недопустимая мощность TX (от {min} до {max} дБм)", + "settings_contactSettingsSaved": "Настройки контакта сохранены", + "settings_batteryToggleHint": "Нажмите, чтобы переключить между процентами и напряжением", + "settings_publicKeyCopyHint": "Копировать публичный ключ", + "settings_locationClearHelper": "Оставьте оба поля пустыми, чтобы удалить вашу позицию.", + "settings_locationCleared": "Позиция удалена", + "settings_regionFetchDiscovering": "Поиск ближайших репитеров…", + "settings_regionFetchProgress": "Опрос репитера {current} из {total}…", + "settings_regionFetchNoRepeaters": "Репитеры пока не известны. Добавьте репитер в контакты или дождитесь его анонса, затем повторите попытку.", + "settings_regionFetchNoneResponded": "Ближайшие репитеры не ответили. Подойдите ближе к репитеру и повторите попытку.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Маршрутизация", + "appSettings_imageMessagesSection": "Сообщения-изображения", + "appSettings_showApiKey": "Показать API-ключ", + "appSettings_hideApiKey": "Скрыть API-ключ", + "translation_defaultModelName": "Модель", + "translation_downloadProgressBytes": "{fileName}: {current} МБ", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} МБ ({percent}%)", + "translation_downloadedModelDetails": "{size} МБ • {source}", + "repeater_radioDisconnected": "Радио отключено", + "repeater_radioDisconnectedHint": "Переподключитесь к радио, чтобы отправлять команды, обновлять данные или сохранять изменения.", + "repeater_cliSend": "Отправить команду", + "repeater_cliCopyTranscript": "Копировать журнал", + "repeater_cliShareTranscript": "Поделиться журналом", + "repeater_cliTranscriptCopied": "Журнал скопирован", + "repeater_cliClearHistoryConfirm": "Очистить историю команд? Действие нельзя отменить.", + "repeater_cliSearchCommands": "Поиск команд", + "repeater_cliNoMatchingCommands": "Нет подходящих команд", + "debugLog_clearConfirm": "Очистить все записи журнала? Действие нельзя отменить.", + "repeater_unsavedChangesTitle": "Несохранённые изменения", + "repeater_unsavedChangesMessage": "У вас есть изменения, не сохранённые в репитере.", + "repeater_discardChanges": "Отменить", + "repeater_actionSentNoReply": "{action}: команда отправлена. Репитер не отвечает на эту команду.", + "repeater_invalidSettingValue": "{setting}: значение {value} недопустимо", + "repeater_txPowerOutOfRange": "Мощность TX {value} вне диапазона (от {min} до {max} дБм)", + "repeater_prvKeyLengthError": "Приватный ключ должен содержать ровно {length} шестнадцатеричных символов", + "contacts_advertFailed": "Не удалось отправить анонс", + "contacts_manageGroups": "Управление группами", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Подключено к", + "usbChooseSerialPort": "Выберите последовательный порт", + "neighbors_durationSeconds": "{seconds}с", + "neighbors_durationMinutes": "{minutes}м {seconds}с", + "neighbors_durationHours": "{hours}ч {minutes}м" } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index 5593df60..e3de5e7e 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3163,5 +3163,103 @@ "qr_cameraPermissionDenied": "Povolenie kamery bolo zamietnuté.\nPovoľte prístup ku kamere v nastaveniach.", "qr_cameraUnsupported": "Kamera nie je na tomto zariadení podporovaná.", "qr_cameraStartFailed": "Kameru sa nepodarilo spustiť.\n{details}", - "imageMessages_downloadFailedWithError": "Model obrázkov sa nepodarilo stiahnuť: {error}" + "imageMessages_downloadFailedWithError": "Model obrázkov sa nepodarilo stiahnuť: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Skryť: značka zostane skrytá, kým neopustíte mapu.", + "map_markerRemoveHint": "Odstrániť: značka zostane skrytá, kým ju neobnovíte v ponuke filtra.", + "map_markerRemoved": "Značka bola odstránená", + "map_restoreRemovedMarkers": "Obnoviť odstránené značky", + "map_restoreRemovedMarkersSubtitle": "Odstránené: {count}", + "map_markersRestored": "Obnovené značky: {count}", + "map_setLocationConfirmTitle": "Nastaviť ako vašu polohu?", + "map_setLocationConfirmBody": "Váš uzol bude oznamovať túto polohu:\n{lat}, {lon}", + "map_setLocationAction": "Nastaviť polohu", + "map_locationSetSuccess": "Poloha uzla bola aktualizovaná", + "map_locationSetFailed": "Zariadenie nepotvrdilo novú polohu. Skúste to znova.", + "map_poiClusterTitle": "Značiek tu: {count}", + "map_poiClusterSemantics": "Zdieľané značky: {count}. Klepnutím ich zobrazíte.", + "map_youWithMarkers": "Vy a značky: {count}", + "map_sharedMarkerSemantics": "Zdieľaná značka: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Priblíženie {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Sťahovanie bolo zrušené. Uložených dlaždíc: {count}.", + "mapCache_tooManyTilesTitle": "Oblasť je príliš veľká", + "mapCache_tooManyTiles": "Táto oblasť vyžaduje {count} dlaždíc, čo je viac ako limit {max}. Vyberte menšiu oblasť alebo znížte maximálne priblíženie.", + "chat_clearChatConfirm": "Týmto sa z tohto zariadenia vymažú všetky správy v tejto konverzácii. Túto akciu nie je možné vrátiť späť.", + "channels_clearChatConfirm": "Týmto sa z tohto zariadenia vymažú všetky správy v tomto kanáli vrátane prijatých obrázkov. Túto akciu nie je možné vrátiť späť.", + "channels_timeNow": "teraz", + "channels_timeMinutes": "{minutes}m", + "channels_timeHours": "{hours}h", + "channels_timeDays": "{days}d", + "channels_indexChip": "KAN {index}", + "reaction_unknownSender": "Neznámy", + "pathMap_noSelfGpsFix": "Lokálny uzol nemá GPS fix", + "pathTrace_sendFailed": "Sledovanie cesty sa nepodarilo odoslať: {error}", + "losErrorNoInternet": "Údaje o nadmorskej výške vyžadujú pripojenie k internetu", + "losResultStale": "Zastarané: výška antény sa zmenila", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Načítavajú sa telemetrické údaje…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Nie ste pripojení k rádiu. Pripojte sa a skúste to znova.", + "settings_requiresConnection": "Na použitie pripojte rádio", + "settings_txPowerInvalidRange": "Neplatný výkon TX ({min} až {max} dBm)", + "settings_contactSettingsSaved": "Nastavenia kontaktu boli uložené", + "settings_batteryToggleHint": "Klepnutím prepnete medzi percentami a napätím", + "settings_publicKeyCopyHint": "Kopírovať verejný kľúč", + "settings_locationClearHelper": "Ak chcete odstrániť svoju polohu, nechajte obe polia prázdne.", + "settings_locationCleared": "Poloha bola odstránená", + "settings_regionFetchDiscovering": "Hľadajú sa blízke opakovače…", + "settings_regionFetchProgress": "Dopytuje sa opakovač {current} z {total}…", + "settings_regionFetchNoRepeaters": "Zatiaľ nie sú známe žiadne opakovače. Pridajte opakovač medzi kontakty alebo počkajte na jeho oznam a skúste to znova.", + "settings_regionFetchNoneResponded": "Blízke opakovače neodpovedali. Priblížte sa k opakovaču a skúste to znova.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Smerovanie", + "appSettings_imageMessagesSection": "Obrazové správy", + "appSettings_showApiKey": "Zobraziť API kľúč", + "appSettings_hideApiKey": "Skryť API kľúč", + "translation_defaultModelName": "Model", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Rádio je odpojené", + "repeater_radioDisconnectedHint": "Znova sa pripojte k rádiu, aby ste mohli odosielať príkazy, obnovovať alebo ukladať zmeny.", + "repeater_cliSend": "Odoslať príkaz", + "repeater_cliCopyTranscript": "Kopírovať prepis", + "repeater_cliShareTranscript": "Zdieľať prepis", + "repeater_cliTranscriptCopied": "Prepis bol skopírovaný", + "repeater_cliClearHistoryConfirm": "Vymazať históriu príkazov? Túto akciu nie je možné vrátiť späť.", + "repeater_cliSearchCommands": "Hľadať príkazy", + "repeater_cliNoMatchingCommands": "Žiadne zodpovedajúce príkazy", + "debugLog_clearConfirm": "Vymazať všetky záznamy denníka? Túto akciu nie je možné vrátiť späť.", + "repeater_unsavedChangesTitle": "Neuložené zmeny", + "repeater_unsavedChangesMessage": "Máte zmeny, ktoré neboli uložené do opakovača.", + "repeater_discardChanges": "Zahodiť", + "repeater_actionSentNoReply": "{action}: príkaz bol odoslaný. Opakovač na tento príkaz neodpovedá.", + "repeater_invalidSettingValue": "{setting}: hodnota {value} nie je platná", + "repeater_txPowerOutOfRange": "Výkon TX {value} je mimo rozsah ({min} až {max} dBm)", + "repeater_prvKeyLengthError": "Súkromný kľúč musí mať presne {length} hexadecimálnych znakov", + "contacts_advertFailed": "Oznam sa nepodarilo odoslať", + "contacts_manageGroups": "Spravovať skupiny", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Pripojené k", + "usbChooseSerialPort": "Vyberte sériový port", + "neighbors_durationSeconds": "{seconds}s", + "neighbors_durationMinutes": "{minutes}m {seconds}s", + "neighbors_durationHours": "{hours}h {minutes}m" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 9d2da421..97e5cc06 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3163,5 +3163,103 @@ "qr_cameraPermissionDenied": "Dovoljenje za kamero zavrnjeno.\nOmogočite dostop do kamere v nastavitvah.", "qr_cameraUnsupported": "Kamera na tej napravi ni podprta.", "qr_cameraStartFailed": "Kamere ni bilo mogoče zagnati.\n{details}", - "imageMessages_downloadFailedWithError": "Slikovnega modela ni bilo mogoče prenesti: {error}" + "imageMessages_downloadFailedWithError": "Slikovnega modela ni bilo mogoče prenesti: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Skrij: skrito, dokler ne zapustite zemljevida.", + "map_markerRemoveHint": "Odstrani: ostane skrito, dokler ga ne obnovite v meniju filtra.", + "map_markerRemoved": "Oznaka odstranjena", + "map_restoreRemovedMarkers": "Obnovi odstranjene oznake", + "map_restoreRemovedMarkersSubtitle": "Odstranjenih: {count}", + "map_markersRestored": "Obnovljenih oznak: {count}", + "map_setLocationConfirmTitle": "Nastavim kot vašo lokacijo?", + "map_setLocationConfirmBody": "Vaše vozlišče bo oglaševalo ta položaj:\n{lat}, {lon}", + "map_setLocationAction": "Nastavi lokacijo", + "map_locationSetSuccess": "Lokacija vozlišča posodobljena", + "map_locationSetFailed": "Naprava ni potrdila nove lokacije. Poskusite znova.", + "map_poiClusterTitle": "Oznak tukaj: {count}", + "map_poiClusterSemantics": "Deljenih oznak: {count}. Tapnite za prikaz seznama.", + "map_youWithMarkers": "Vi in oznak: {count}", + "map_sharedMarkerSemantics": "Deljena oznaka: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Povečava {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Prenos preklican. V predpomnilniku je {count} ploščic.", + "mapCache_tooManyTilesTitle": "Območje je preveliko", + "mapCache_tooManyTiles": "To območje potrebuje {count} ploščic, kar presega omejitev {max}. Izberite manjše območje ali zmanjšajte največjo povečavo.", + "chat_clearChatConfirm": "S te naprave bodo izbrisana vsa sporočila v tem pogovoru. Dejanja ni mogoče razveljaviti.", + "channels_clearChatConfirm": "S te naprave bodo izbrisana vsa sporočila v tem kanalu, vključno s prejetimi slikami. Dejanja ni mogoče razveljaviti.", + "channels_timeNow": "zdaj", + "channels_timeMinutes": "{minutes} min", + "channels_timeHours": "{hours} h", + "channels_timeDays": "{days} d", + "channels_indexChip": "KAN {index}", + "reaction_unknownSender": "Neznano", + "pathMap_noSelfGpsFix": "Lokalno vozlišče nima GPS-a", + "pathTrace_sendFailed": "Poti ni bilo mogoče poslati: {error}", + "losErrorNoInternet": "Podatki o nadmorski višini zahtevajo internetno povezavo", + "losResultStale": "Zastarelo: višina antene se je spremenila", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Nalaganje telemetrije…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Ni povezave z radiem. Povežite se in poskusite znova.", + "settings_requiresConnection": "Za to se povežite z radiem", + "settings_txPowerInvalidRange": "Neveljavna moč TX ({min} do {max} dBm)", + "settings_contactSettingsSaved": "Nastavitve stika shranjene", + "settings_batteryToggleHint": "Tapnite za preklop med odstotki in napetostjo", + "settings_publicKeyCopyHint": "Kopiraj javni ključ", + "settings_locationClearHelper": "Obe polji pustite prazni, če želite odstraniti svojo lokacijo.", + "settings_locationCleared": "Lokacija odstranjena", + "settings_regionFetchDiscovering": "Iskanje bližnjih ponovitelj…", + "settings_regionFetchProgress": "Spraševanje ponovitelja {current} od {total}…", + "settings_regionFetchNoRepeaters": "Zaenkrat ni znanih ponovitelj. Dodajte ponovitelj kot stik ali počakajte, da se oglasi, nato poskusite znova.", + "settings_regionFetchNoneResponded": "Noben bližnji ponovitelj ni odgovoril. Približajte se ponovitelju in poskusite znova.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Usmerjanje", + "appSettings_imageMessagesSection": "Sporočila s slikami", + "appSettings_showApiKey": "Pokaži API ključ", + "appSettings_hideApiKey": "Skrij API ključ", + "translation_defaultModelName": "Model", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Radio odklopljen", + "repeater_radioDisconnectedHint": "Znova se povežite z radiem, da pošljete ukaze, osvežite ali shranite spremembe.", + "repeater_cliSend": "Pošlji ukaz", + "repeater_cliCopyTranscript": "Kopiraj prepis", + "repeater_cliShareTranscript": "Deli prepis", + "repeater_cliTranscriptCopied": "Prepis kopiran", + "repeater_cliClearHistoryConfirm": "Počistim zgodovino ukazov? Dejanja ni mogoče razveljaviti.", + "repeater_cliSearchCommands": "Išči ukaze", + "repeater_cliNoMatchingCommands": "Ni ustreznih ukazov", + "debugLog_clearConfirm": "Počistim vse vnose dnevnika? Dejanja ni mogoče razveljaviti.", + "repeater_unsavedChangesTitle": "Neshranjene spremembe", + "repeater_unsavedChangesMessage": "Imate spremembe, ki niso shranjene v ponovitelju.", + "repeater_discardChanges": "Zavrzi", + "repeater_actionSentNoReply": "{action}: ukaz poslan. Ponovitelj na ta ukaz ne odgovori.", + "repeater_invalidSettingValue": "{setting}: {value} ni veljavno", + "repeater_txPowerOutOfRange": "Moč TX {value} je izven območja ({min} do {max} dBm)", + "repeater_prvKeyLengthError": "Zasebni ključ mora imeti točno {length} šestnajstiških znakov", + "contacts_advertFailed": "Oglasa ni bilo mogoče poslati", + "contacts_manageGroups": "Upravljaj skupine", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Povezano z", + "usbChooseSerialPort": "Izberite serijska vrata", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} min {seconds} s", + "neighbors_durationHours": "{hours} h {minutes} min" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index da417952..7b469c00 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3157,5 +3157,103 @@ "qr_cameraPermissionDenied": "Kamerabehörighet nekades.\nAktivera kameraåtkomst i inställningarna.", "qr_cameraUnsupported": "Kameran stöds inte på den här enheten.", "qr_cameraStartFailed": "Det gick inte att starta kameran.\n{details}", - "imageMessages_downloadFailedWithError": "Bildmodellen kunde inte laddas ned: {error}" + "imageMessages_downloadFailedWithError": "Bildmodellen kunde inte laddas ned: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Dölj: dold tills du lämnar kartan.", + "map_markerRemoveHint": "Ta bort: förblir dold tills du återställer den från filtermenyn.", + "map_markerRemoved": "Markör borttagen", + "map_restoreRemovedMarkers": "Återställ borttagna markörer", + "map_restoreRemovedMarkersSubtitle": "{count} borttagna", + "map_markersRestored": "Återställde {count} markörer", + "map_setLocationConfirmTitle": "Ange som din plats?", + "map_setLocationConfirmBody": "Din nod kommer att annonsera denna position:\n{lat}, {lon}", + "map_setLocationAction": "Ange plats", + "map_locationSetSuccess": "Nodens plats uppdaterad", + "map_locationSetFailed": "Enheten bekräftade inte den nya platsen. Försök igen.", + "map_poiClusterTitle": "{count} markörer här", + "map_poiClusterSemantics": "{count} delade markörer. Tryck för att visa dem.", + "map_youWithMarkers": "Du och {count} markörer", + "map_sharedMarkerSemantics": "Delad markör: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Zoom {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "Nedladdningen avbröts. {count} brickor cachades.", + "mapCache_tooManyTilesTitle": "Området är för stort", + "mapCache_tooManyTiles": "Det här området kräver {count} brickor, vilket överskrider gränsen på {max}. Välj ett mindre område eller sänk maximal zoom.", + "chat_clearChatConfirm": "Detta raderar alla meddelanden i den här konversationen från den här enheten. Det går inte att ångra.", + "channels_clearChatConfirm": "Detta raderar alla meddelanden i den här kanalen från den här enheten, inklusive mottagna bilder. Det går inte att ångra.", + "channels_timeNow": "nu", + "channels_timeMinutes": "{minutes} min", + "channels_timeHours": "{hours} h", + "channels_timeDays": "{days} d", + "channels_indexChip": "KAN {index}", + "reaction_unknownSender": "Okänd", + "pathMap_noSelfGpsFix": "Den lokala noden har ingen GPS-fix", + "pathTrace_sendFailed": "Kunde inte skicka sökvägsspårningen: {error}", + "losErrorNoInternet": "Höjddata kräver internetanslutning", + "losResultStale": "Föråldrat: antennhöjden har ändrats", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "Läser in telemetri…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "Inte ansluten till en radio. Anslut och försök igen.", + "settings_requiresConnection": "Anslut till en radio för att använda detta", + "settings_txPowerInvalidRange": "Ogiltig TX-effekt ({min} till {max} dBm)", + "settings_contactSettingsSaved": "Kontaktinställningar sparade", + "settings_batteryToggleHint": "Tryck för att växla mellan procent och spänning", + "settings_publicKeyCopyHint": "Kopiera publik nyckel", + "settings_locationClearHelper": "Lämna båda fälten tomma för att ta bort din plats.", + "settings_locationCleared": "Platsen borttagen", + "settings_regionFetchDiscovering": "Söker efter repeatrar i närheten…", + "settings_regionFetchProgress": "Frågar repeater {current} av {total}…", + "settings_regionFetchNoRepeaters": "Inga repeatrar är kända ännu. Lägg till en repeater som kontakt eller vänta tills en annonserar, och försök sedan igen.", + "settings_regionFetchNoneResponded": "Ingen repeater i närheten svarade. Flytta dig närmare en repeater och försök igen.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Routing", + "appSettings_imageMessagesSection": "Bildmeddelanden", + "appSettings_showApiKey": "Visa API-nyckel", + "appSettings_hideApiKey": "Dölj API-nyckel", + "translation_defaultModelName": "Modell", + "translation_downloadProgressBytes": "{fileName}: {current} MB", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} MB ({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "Radion frånkopplad", + "repeater_radioDisconnectedHint": "Återanslut till din radio för att skicka kommandon, uppdatera eller spara ändringar.", + "repeater_cliSend": "Skicka kommando", + "repeater_cliCopyTranscript": "Kopiera utskrift", + "repeater_cliShareTranscript": "Dela utskrift", + "repeater_cliTranscriptCopied": "Utskrift kopierad", + "repeater_cliClearHistoryConfirm": "Rensa kommandohistoriken? Det går inte att ångra.", + "repeater_cliSearchCommands": "Sök kommandon", + "repeater_cliNoMatchingCommands": "Inga matchande kommandon", + "debugLog_clearConfirm": "Rensa alla loggposter? Det går inte att ångra.", + "repeater_unsavedChangesTitle": "Osparade ändringar", + "repeater_unsavedChangesMessage": "Du har ändringar som inte har sparats i repeatern.", + "repeater_discardChanges": "Förkasta", + "repeater_actionSentNoReply": "{action}: kommando skickat. Repeatern svarar inte på detta kommando.", + "repeater_invalidSettingValue": "{setting}: {value} är inte giltigt", + "repeater_txPowerOutOfRange": "TX-effekt {value} ligger utanför intervallet ({min} till {max} dBm)", + "repeater_prvKeyLengthError": "Privat nyckel måste vara exakt {length} hexadecimala tecken", + "contacts_advertFailed": "Kunde inte skicka annonsen", + "contacts_manageGroups": "Hantera grupper", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Ansluten till", + "usbChooseSerialPort": "Välj serieport", + "neighbors_durationSeconds": "{seconds} s", + "neighbors_durationMinutes": "{minutes} min {seconds} s", + "neighbors_durationHours": "{hours} h {minutes} min" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 6fa4e7ad..7a8fe6f9 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3142,5 +3142,103 @@ "qr_cameraPermissionDenied": "Доступ до камери заборонено.\nУвімкніть доступ до камери в налаштуваннях.", "qr_cameraUnsupported": "Камера не підтримується на цьому пристрої.", "qr_cameraStartFailed": "Не вдалося запустити камеру.\n{details}", - "imageMessages_downloadFailedWithError": "Не вдалося завантажити модель зображень: {error}" + "imageMessages_downloadFailedWithError": "Не вдалося завантажити модель зображень: {error}", + "map_nodeId": "ID", + "map_markerHideHint": "Приховати: маркер буде прихований, доки ви не покинете карту.", + "map_markerRemoveHint": "Видалити: маркер залишатиметься прихованим, доки ви не відновите його в меню фільтра.", + "map_markerRemoved": "Маркер видалено", + "map_restoreRemovedMarkers": "Відновити видалені маркери", + "map_restoreRemovedMarkersSubtitle": "Видалено: {count}", + "map_markersRestored": "Відновлено маркерів: {count}", + "map_setLocationConfirmTitle": "Встановити як вашу геопозицію?", + "map_setLocationConfirmBody": "Ваш вузол оголошуватиме цю позицію:\n{lat}, {lon}", + "map_setLocationAction": "Встановити позицію", + "map_locationSetSuccess": "Позицію вузла оновлено", + "map_locationSetFailed": "Пристрій не підтвердив нову позицію. Спробуйте ще раз.", + "map_poiClusterTitle": "Маркерів тут: {count}", + "map_poiClusterSemantics": "Спільних маркерів: {count}. Торкніться, щоб відкрити список.", + "map_youWithMarkers": "Ви та маркерів: {count}", + "map_sharedMarkerSemantics": "Спільний маркер: {label}", + "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "mapCache_zoomLevel": "Масштаб {zoom}", + "mapCache_sizeBytes": "{size} Б", + "mapCache_sizeKilobytes": "{size} КБ", + "mapCache_sizeMegabytes": "{size} МБ", + "mapCache_sizeGigabytes": "{size} ГБ", + "mapCache_downloadCancelled": "Завантаження скасовано. Кешовано тайлів: {count}.", + "mapCache_tooManyTilesTitle": "Область завелика", + "mapCache_tooManyTiles": "Для цієї області потрібно тайлів: {count}, що перевищує ліміт {max}. Виберіть меншу область або зменште максимальний масштаб.", + "chat_clearChatConfirm": "Це видалить усі повідомлення цього чату з цього пристрою. Дію не можна скасувати.", + "channels_clearChatConfirm": "Це видалить усі повідомлення цього каналу з цього пристрою, включно з отриманими зображеннями. Дію не можна скасувати.", + "channels_timeNow": "зараз", + "channels_timeMinutes": "{minutes}хв", + "channels_timeHours": "{hours}год", + "channels_timeDays": "{days}д", + "channels_indexChip": "КАН {index}", + "reaction_unknownSender": "Невідомо", + "pathMap_noSelfGpsFix": "Локальний вузол не має GPS-фіксації", + "pathTrace_sendFailed": "Не вдалося надіслати трасування шляху: {error}", + "losErrorNoInternet": "Для даних про висоти потрібне підключення до інтернету", + "losResultStale": "Застаріло: висоту антени змінено", + "losSnrValue": "{snr} дБ", + "losFrequencyValue": "{frequency} МГц", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "км", + "units_mi": "миль", + "units_m": "м", + "units_ft": "фт", + "telemetry_loading": "Завантаження телеметрії…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} фт", + "telemetry_distanceValueFeet": "{feet} фт", + "settings_notConnectedError": "Немає підключення до радіо. Підключіться й спробуйте ще раз.", + "settings_requiresConnection": "Підключіться до радіо, щоб скористатися цим", + "settings_txPowerInvalidRange": "Недопустима потужність TX (від {min} до {max} дБм)", + "settings_contactSettingsSaved": "Налаштування контакту збережено", + "settings_batteryToggleHint": "Торкніться, щоб перемкнути між відсотками та напругою", + "settings_publicKeyCopyHint": "Копіювати публічний ключ", + "settings_locationClearHelper": "Залиште обидва поля порожніми, щоб видалити вашу геопозицію.", + "settings_locationCleared": "Геопозицію видалено", + "settings_regionFetchDiscovering": "Пошук ближніх ретрансляторів…", + "settings_regionFetchProgress": "Опитування ретранслятора {current} з {total}…", + "settings_regionFetchNoRepeaters": "Ретранслятори поки невідомі. Додайте ретранслятор до контактів або дочекайтеся його оголошення, а потім спробуйте ще раз.", + "settings_regionFetchNoneResponded": "Ближні ретранслятори не відповіли. Підійдіть ближче до ретранслятора й спробуйте ще раз.", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "Маршрутизація", + "appSettings_imageMessagesSection": "Повідомлення із зображеннями", + "appSettings_showApiKey": "Показати API-ключ", + "appSettings_hideApiKey": "Приховати API-ключ", + "translation_defaultModelName": "Модель", + "translation_downloadProgressBytes": "{fileName}: {current} МБ", + "translation_downloadProgressTotal": "{fileName}: {current} / {total} МБ ({percent}%)", + "translation_downloadedModelDetails": "{size} МБ • {source}", + "repeater_radioDisconnected": "Радіо відключено", + "repeater_radioDisconnectedHint": "Підключіться до радіо повторно, щоб надсилати команди, оновлювати дані або зберігати зміни.", + "repeater_cliSend": "Надіслати команду", + "repeater_cliCopyTranscript": "Копіювати журнал", + "repeater_cliShareTranscript": "Поділитися журналом", + "repeater_cliTranscriptCopied": "Журнал скопійовано", + "repeater_cliClearHistoryConfirm": "Очистити історію команд? Дію не можна скасувати.", + "repeater_cliSearchCommands": "Пошук команд", + "repeater_cliNoMatchingCommands": "Немає відповідних команд", + "debugLog_clearConfirm": "Очистити всі записи журналу? Дію не можна скасувати.", + "repeater_unsavedChangesTitle": "Незбережені зміни", + "repeater_unsavedChangesMessage": "У вас є зміни, не збережені в ретрансляторі.", + "repeater_discardChanges": "Відхилити", + "repeater_actionSentNoReply": "{action}: команду надіслано. Ретранслятор не відповідає на цю команду.", + "repeater_invalidSettingValue": "{setting}: значення {value} недопустиме", + "repeater_txPowerOutOfRange": "Потужність TX {value} поза діапазоном (від {min} до {max} дБм)", + "repeater_prvKeyLengthError": "Приватний ключ має містити рівно {length} шістнадцяткових символів", + "contacts_advertFailed": "Не вдалося надіслати оголошення", + "contacts_manageGroups": "Керування групами", + "community_shortId": "ID: {id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "Підключено до", + "usbChooseSerialPort": "Виберіть послідовний порт", + "neighbors_durationSeconds": "{seconds}с", + "neighbors_durationMinutes": "{minutes}хв {seconds}с", + "neighbors_durationHours": "{hours}год {minutes}хв" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index d0c7ca59..7fa7bbd0 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3167,5 +3167,103 @@ "qr_cameraPermissionDenied": "相机权限被拒绝。\n请在设置中启用相机访问。", "qr_cameraUnsupported": "此设备不支持相机。", "qr_cameraStartFailed": "无法启动相机。\n{details}", - "imageMessages_downloadFailedWithError": "无法下载图像模型:{error}" + "imageMessages_downloadFailedWithError": "无法下载图像模型:{error}", + "map_nodeId": "ID", + "map_markerHideHint": "隐藏:离开地图前保持隐藏。", + "map_markerRemoveHint": "移除:在从筛选菜单中恢复之前保持隐藏。", + "map_markerRemoved": "标记已移除", + "map_restoreRemovedMarkers": "恢复已移除的标记", + "map_restoreRemovedMarkersSubtitle": "已移除 {count} 个", + "map_markersRestored": "已恢复 {count} 个标记", + "map_setLocationConfirmTitle": "设为你的位置?", + "map_setLocationConfirmBody": "你的节点将广播此位置:\n{lat}, {lon}", + "map_setLocationAction": "设置位置", + "map_locationSetSuccess": "节点位置已更新", + "map_locationSetFailed": "设备未确认新位置。请重试。", + "map_poiClusterTitle": "此处有 {count} 个标记", + "map_poiClusterSemantics": "{count} 个共享标记。点按以查看列表。", + "map_youWithMarkers": "你和 {count} 个标记", + "map_sharedMarkerSemantics": "共享标记:{label}", + "map_nodeMarkerSemantics": "{name},{type},{status}", + "mapCache_zoomLevel": "缩放 {zoom}", + "mapCache_sizeBytes": "{size} B", + "mapCache_sizeKilobytes": "{size} KB", + "mapCache_sizeMegabytes": "{size} MB", + "mapCache_sizeGigabytes": "{size} GB", + "mapCache_downloadCancelled": "下载已取消。已缓存 {count} 个图块。", + "mapCache_tooManyTilesTitle": "区域过大", + "mapCache_tooManyTiles": "此区域需要 {count} 个图块,超过 {max} 的上限。请选择更小的区域或降低最大缩放级别。", + "chat_clearChatConfirm": "这将从此设备上清除此对话中的所有消息,且无法撤销。", + "channels_clearChatConfirm": "这将从此设备上清除此频道中的所有消息(包括已接收的图片),且无法撤销。", + "channels_timeNow": "刚刚", + "channels_timeMinutes": "{minutes}分钟", + "channels_timeHours": "{hours}小时", + "channels_timeDays": "{days}天", + "channels_indexChip": "CH {index}", + "reaction_unknownSender": "未知", + "pathMap_noSelfGpsFix": "本地节点没有 GPS 定位", + "pathTrace_sendFailed": "无法发送路径追踪:{error}", + "losErrorNoInternet": "海拔数据需要网络连接", + "losResultStale": "结果已过期:天线高度已更改", + "losSnrValue": "{snr} dB", + "losFrequencyValue": "{frequency} MHz", + "losKFactorValue": "k={kFactor}", + "losEndpointA": "A", + "losEndpointB": "B", + "units_km": "km", + "units_mi": "mi", + "units_m": "m", + "units_ft": "ft", + "telemetry_loading": "正在加载遥测数据…", + "telemetry_axisValue": "X: {x}, Y: {y}, Z: {z}", + "telemetry_colourValue": "R: {red}, G: {green}, B: {blue}", + "telemetry_altitudeValueFeet": "{feet} ft", + "telemetry_distanceValueFeet": "{feet} ft", + "settings_notConnectedError": "未连接到电台。请连接后重试。", + "settings_requiresConnection": "请连接电台后使用", + "settings_txPowerInvalidRange": "TX 功率无效({min} 至 {max} dBm)", + "settings_contactSettingsSaved": "联系人设置已保存", + "settings_batteryToggleHint": "点按可在百分比和电压之间切换", + "settings_publicKeyCopyHint": "复制公钥", + "settings_locationClearHelper": "将两个字段都留空即可移除你的位置。", + "settings_locationCleared": "位置已移除", + "settings_regionFetchDiscovering": "正在查找附近的中继器…", + "settings_regionFetchProgress": "正在询问第 {current}/{total} 个中继器…", + "settings_regionFetchNoRepeaters": "目前还没有已知的中继器。请将中继器添加为联系人,或等待其广播后重试。", + "settings_regionFetchNoneResponded": "附近没有中继器响应。请靠近中继器后重试。", + "appSettings_sourceSummary": "{label} - {description}", + "appSettings_routingSection": "路由", + "appSettings_imageMessagesSection": "图片消息", + "appSettings_showApiKey": "显示 API 密钥", + "appSettings_hideApiKey": "隐藏 API 密钥", + "translation_defaultModelName": "模型", + "translation_downloadProgressBytes": "{fileName}:{current} MB", + "translation_downloadProgressTotal": "{fileName}:{current} / {total} MB({percent}%)", + "translation_downloadedModelDetails": "{size} MB • {source}", + "repeater_radioDisconnected": "电台已断开连接", + "repeater_radioDisconnectedHint": "请重新连接电台以发送命令、刷新或保存更改。", + "repeater_cliSend": "发送命令", + "repeater_cliCopyTranscript": "复制记录", + "repeater_cliShareTranscript": "分享记录", + "repeater_cliTranscriptCopied": "记录已复制", + "repeater_cliClearHistoryConfirm": "清除命令历史?此操作无法撤销。", + "repeater_cliSearchCommands": "搜索命令", + "repeater_cliNoMatchingCommands": "没有匹配的命令", + "debugLog_clearConfirm": "清除所有日志条目?此操作无法撤销。", + "repeater_unsavedChangesTitle": "未保存的更改", + "repeater_unsavedChangesMessage": "你有尚未保存到中继器的更改。", + "repeater_discardChanges": "放弃", + "repeater_actionSentNoReply": "{action}:命令已发送。中继器不会回复此命令。", + "repeater_invalidSettingValue": "{setting}:{value} 无效", + "repeater_txPowerOutOfRange": "TX 功率 {value} 超出范围({min} 至 {max} dBm)", + "repeater_prvKeyLengthError": "私钥必须恰好为 {length} 个十六进制字符", + "contacts_advertFailed": "无法发送广播", + "contacts_manageGroups": "管理分组", + "community_shortId": "ID:{id}…", + "tcpSectionTitle": "TCP / IP", + "tcpConnectedToHeader": "已连接到", + "usbChooseSerialPort": "选择串口", + "neighbors_durationSeconds": "{seconds}秒", + "neighbors_durationMinutes": "{minutes}分{seconds}秒", + "neighbors_durationHours": "{hours}小时{minutes}分" } diff --git a/lib/screens/app_debug_log_screen.dart b/lib/screens/app_debug_log_screen.dart index 4b00c70c..02216029 100644 --- a/lib/screens/app_debug_log_screen.dart +++ b/lib/screens/app_debug_log_screen.dart @@ -6,6 +6,7 @@ import '../l10n/l10n.dart'; import '../services/app_debug_log_service.dart'; import '../theme/mesh_theme.dart'; import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/confirm_clear_dialog.dart'; import '../helpers/snack_bar_builder.dart'; class AppDebugLogScreen extends StatelessWidget { @@ -17,6 +18,8 @@ class AppDebugLogScreen extends StatelessWidget { builder: (context, logService, _) { final entries = logService.entries.reversed.toList(); final hasEntries = entries.isNotEmpty; + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; return Scaffold( appBar: AppBar( @@ -47,8 +50,13 @@ class AppDebugLogScreen extends StatelessWidget { tooltip: context.l10n.debugLog_clearLog, icon: const Icon(Icons.delete_outline), onPressed: hasEntries - ? () { - logService.clear(); + ? () async { + final confirmed = await showConfirmClearDialog( + context, + title: context.l10n.debugLog_clearLog, + message: context.l10n.debugLog_clearConfirm, + ); + if (confirmed) logService.clear(); } : null, ), @@ -60,11 +68,11 @@ class AppDebugLogScreen extends StatelessWidget { ? ListView.separated( itemCount: entries.length, separatorBuilder: (_, _) => - const Divider(height: 1, color: MeshPalette.line), + Divider(height: 1, color: scheme.outlineVariant), itemBuilder: (context, index) { final entry = entries[index]; return Container( - color: MeshPalette.bg, + color: scheme.surfaceContainerLowest, padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 8, @@ -84,15 +92,18 @@ class AppDebugLogScreen extends StatelessWidget { TextSpan( text: '[${entry.tag}] ', style: MeshTheme.mono( - fontSize: 11.5, - color: _levelColor(entry.level), + fontSize: 13, + color: _levelColor( + context, + entry.level, + ), ), ), TextSpan( text: entry.message, style: MeshTheme.mono( - fontSize: 11.5, - color: MeshPalette.ink2, + fontSize: 13, + color: scheme.onSurface, ), ), ], @@ -102,8 +113,8 @@ class AppDebugLogScreen extends StatelessWidget { Text( entry.formattedTime, style: MeshTheme.mono( - fontSize: 9.5, - color: MeshPalette.ink4, + fontSize: 12, + color: scheme.onSurfaceVariant, ), ), ], @@ -118,25 +129,25 @@ class AppDebugLogScreen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon( + Icon( Icons.bug_report_outlined, size: 64, - color: MeshPalette.ink3, + color: scheme.onSurfaceVariant, ), const SizedBox(height: 16), Text( context.l10n.debugLog_noEntries, - style: const TextStyle( - fontSize: 16, - color: MeshPalette.ink3, + textAlign: TextAlign.center, + style: textTheme.titleMedium?.copyWith( + color: scheme.onSurface, ), ), const SizedBox(height: 8), Text( context.l10n.debugLog_enableInSettings, - style: const TextStyle( - fontSize: 12, - color: MeshPalette.ink3, + textAlign: TextAlign.center, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, ), ), ], @@ -148,36 +159,38 @@ class AppDebugLogScreen extends StatelessWidget { ); } - Color _levelColor(AppDebugLogLevel level) { + Color _levelColor(BuildContext context, AppDebugLogLevel level) { + final scheme = Theme.of(context).colorScheme; + final isDark = Theme.of(context).brightness == Brightness.dark; switch (level) { case AppDebugLogLevel.info: - return MeshPalette.blue; + return scheme.primary; case AppDebugLogLevel.warning: - return MeshPalette.warn; + return isDark ? MeshPalette.warn : MeshPalette.warnDim; case AppDebugLogLevel.error: - return MeshPalette.alert; + return scheme.error; } } Widget _buildLevelIcon(BuildContext context, AppDebugLogLevel level) { switch (level) { case AppDebugLogLevel.info: - return const Icon( + return Icon( Icons.info_outline, - size: 18, - color: MeshPalette.blue, + size: 20, + color: _levelColor(context, level), ); case AppDebugLogLevel.warning: - return const Icon( + return Icon( Icons.warning_amber_outlined, - size: 18, - color: MeshPalette.warn, + size: 20, + color: _levelColor(context, level), ); case AppDebugLogLevel.error: - return const Icon( + return Icon( Icons.error_outline, - size: 18, - color: MeshPalette.alert, + size: 20, + color: _levelColor(context, level), ); } } diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index d32a443b..0570724a 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -1,4 +1,3 @@ -import 'dart:convert'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -7,18 +6,20 @@ import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../models/app_settings.dart'; import '../models/image_codec_support.dart'; -import '../models/translation_support.dart'; import '../services/app_settings_service.dart'; import '../services/background_service.dart'; import '../services/image_codec_service.dart'; import '../services/map_tile_cache_service.dart'; import '../services/notification_service.dart'; -import '../services/translation_service.dart'; import '../theme/mesh_theme.dart'; import '../utils/platform_info.dart'; import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/cyr2lat_profile_dialog.dart'; +import '../widgets/language_picker_sheet.dart'; +import '../widgets/mesh_nav_tile.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/sync_progress_overlay.dart'; +import '../widgets/translation_settings_section.dart'; import '../helpers/snack_bar_builder.dart'; import 'map_cache_screen.dart'; @@ -44,107 +45,99 @@ class AppSettingsScreen extends StatelessWidget { ), body: SafeArea( top: false, - child: - Consumer3< - AppSettingsService, - MeshCoreConnector, - TranslationService - >( - builder: - ( - context, - settingsService, - connector, - translationService, - child, - ) { - return ListView( - padding: const EdgeInsets.fromLTRB(0, 8, 0, 24), - children: [ - // APPEARANCE - SectionHeader(context.l10n.appSettings_appearance), - MeshCard( - padding: EdgeInsets.zero, - child: _buildAppearanceContent( - context, - settingsService, - ), - ), - - // NOTIFICATIONS - SectionHeader(context.l10n.appSettings_notifications), - MeshCard( - padding: EdgeInsets.zero, - child: _buildNotificationsContent( - context, - settingsService, - ), - ), - - // MESSAGING - SectionHeader(context.l10n.appSettings_messaging), - MeshCard( - padding: EdgeInsets.zero, - child: _buildMessagingContent( - context, - settingsService, - ), - ), - - // BATTERY - SectionHeader(context.l10n.appSettings_battery), - MeshCard( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), - child: _buildBatteryContent( - context, - settingsService, - connector, - ), - ), - - // MAP - SectionHeader(context.l10n.appSettings_mapDisplay), - MeshCard( - padding: EdgeInsets.zero, - child: _buildMapContent(context, settingsService), - ), - - // TRANSLATION (non-web only) - if (!kIsWeb) ...[ - SectionHeader(context.l10n.translation_title), - MeshCard( - padding: EdgeInsets.zero, - child: _buildTranslationContent( - context, - settingsService, - translationService, - ), - ), - ], - - // CYR2LAT - SectionHeader( - context.l10n.channels_cyr2latSettingsHeading, - ), - MeshCard( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), - child: _buildCyr2LatContent(context, settingsService), - ), - - // DEBUG - SectionHeader(context.l10n.appSettings_debugCard), - MeshCard( - padding: EdgeInsets.zero, - child: _buildDebugContent(context, settingsService), - ), - ], - ); - }, + // Each card subscribes to only what it shows, so connector traffic + // and translation download ticks do not rebuild the whole list. + child: ListView( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 24), + children: [ + // APPEARANCE + SectionHeader(context.l10n.appSettings_appearance), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildAppearanceContent), ), + + // NOTIFICATIONS + SectionHeader(context.l10n.appSettings_notifications), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildNotificationsContent), + ), + + // MESSAGING + SectionHeader(context.l10n.appSettings_messaging), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildMessagingContent), + ), + + // ROUTING + SectionHeader(context.l10n.appSettings_routingSection), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildRoutingContent), + ), + + // IMAGE MESSAGES + SectionHeader(context.l10n.appSettings_imageMessagesSection), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildImageMessagesContent), + ), + + // BATTERY + SectionHeader(context.l10n.appSettings_battery), + MeshCard( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: _settingsCard(_buildBatteryContent), + ), + + // MAP + SectionHeader(context.l10n.appSettings_mapDisplay), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildMapContent), + ), + + // TRANSLATION (non-web only) + if (!kIsWeb) ...[ + SectionHeader(context.l10n.translation_title), + const MeshCard( + padding: EdgeInsets.zero, + child: TranslationSettingsSection(), + ), + ], + + // CYR2LAT + SectionHeader(context.l10n.channels_cyr2latSettingsHeading), + MeshCard( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: _settingsCard(_buildCyr2LatContent), + ), + + // DEBUG + SectionHeader(context.l10n.appSettings_debugCard), + MeshCard( + padding: EdgeInsets.zero, + child: _settingsCard(_buildDebugContent), + ), + ], + ), ), ); } + /// A card that rebuilds only on [AppSettingsService] changes. + Widget _settingsCard( + Widget Function(BuildContext context, AppSettingsService settingsService) + builder, + ) { + return Consumer( + builder: (context, settingsService, _) => + builder(context, settingsService), + ); + } + Widget _buildAppearanceContent( BuildContext context, AppSettingsService settingsService, @@ -163,13 +156,13 @@ class AppSettingsScreen extends StatelessWidget { children: [ Icon( Icons.brightness_6_outlined, - size: 20, + size: 24, color: scheme.onSurfaceVariant, ), - const SizedBox(width: 12), + const SizedBox(width: 16), Text( context.l10n.appSettings_theme, - style: textTheme.bodyMedium?.copyWith( + style: textTheme.bodyLarge?.copyWith( fontWeight: FontWeight.w600, ), ), @@ -200,49 +193,14 @@ class AppSettingsScreen extends StatelessWidget { ), ), const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showLanguageSheet(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon( - Icons.language_outlined, - size: 20, - color: scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_language, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - _languageLabel( - context, - settingsService.settings.languageOverride, - ), - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), + MeshNavTile( + icon: Icons.language_outlined, + title: context.l10n.appSettings_language, + subtitle: appLanguageLabel( + context, + settingsService.settings.languageOverride, ), + onTap: () => showLanguagePickerSheet(context, settingsService), ), ], ); @@ -260,7 +218,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.notifications_outlined, size: 20), + secondary: const Icon(Icons.notifications_outlined, size: 24), title: Text(context.l10n.appSettings_enableNotifications), subtitle: Text(context.l10n.appSettings_enableNotificationsSubtitle), value: settingsService.settings.notificationsEnabled, @@ -302,7 +260,7 @@ class AppSettingsScreen extends StatelessWidget { ), secondary: Icon( Icons.message_outlined, - size: 20, + size: 24, color: notifEnabled ? null : Theme.of(context).disabledColor, ), title: Text( @@ -329,12 +287,12 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - leading: const Icon(Icons.battery_saver_outlined, size: 20), + leading: const Icon(Icons.battery_saver_outlined, size: 24), title: Text(context.l10n.appSettings_batteryOptimization), subtitle: Text( context.l10n.appSettings_batteryOptimizationSubtitle, ), - trailing: const Icon(Icons.open_in_new, size: 18), + trailing: const Icon(Icons.open_in_new, size: 24), onTap: BackgroundService.openBatteryOptimizationSettings, ), ], @@ -346,7 +304,7 @@ class AppSettingsScreen extends StatelessWidget { ), secondary: Icon( Icons.forum_outlined, - size: 20, + size: 24, color: notifEnabled ? null : Theme.of(context).disabledColor, ), title: Text( @@ -374,7 +332,7 @@ class AppSettingsScreen extends StatelessWidget { ), secondary: Icon( Icons.cell_tower, - size: 20, + size: 24, color: notifEnabled ? null : Theme.of(context).disabledColor, ), title: Text( @@ -402,7 +360,6 @@ class AppSettingsScreen extends StatelessWidget { BuildContext context, AppSettingsService settingsService, ) { - final autoRouteEnabled = settingsService.settings.autoRouteRotationEnabled; return Column( children: [ SwitchListTile( @@ -410,7 +367,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.refresh_outlined, size: 20), + secondary: const Icon(Icons.refresh_outlined, size: 24), title: Text(context.l10n.appSettings_clearPathOnMaxRetry), subtitle: Text(context.l10n.appSettings_clearPathOnMaxRetrySubtitle), value: settingsService.settings.clearPathOnMaxRetry, @@ -433,7 +390,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.vertical_align_top, size: 20), + secondary: const Icon(Icons.vertical_align_top, size: 24), title: Text(context.l10n.appSettings_jumpToOldestUnread), subtitle: Text(context.l10n.appSettings_jumpToOldestUnreadSubtitle), value: settingsService.settings.jumpToOldestUnread, @@ -445,7 +402,43 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.alt_route, size: 20), + secondary: const Icon(Icons.location_searching, size: 24), + title: Text(context.l10n.appSettings_enableMessageTracing), + subtitle: Text(context.l10n.appSettings_enableMessageTracingSubtitle), + value: settingsService.settings.enableMessageTracing, + onChanged: (value) { + settingsService.setEnableMessageTracing(value); + }, + ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.short_text, size: 24), + title: Text(context.l10n.appSettings_regionOnHopsLine), + subtitle: Text(context.l10n.appSettings_regionOnHopsLineSubtitle), + value: settingsService.settings.regionOnHopsLine, + onChanged: settingsService.setRegionOnHopsLine, + ), + ], + ); + } + + Widget _buildRoutingContent( + BuildContext context, + AppSettingsService settingsService, + ) { + final autoRouteEnabled = settingsService.settings.autoRouteRotationEnabled; + return Column( + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.alt_route, size: 24), title: Text(context.l10n.appSettings_autoRouteRotation), subtitle: Text(context.l10n.appSettings_autoRouteRotationSubtitle), value: autoRouteEnabled, @@ -619,33 +612,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.location_searching, size: 20), - title: Text(context.l10n.appSettings_enableMessageTracing), - subtitle: Text(context.l10n.appSettings_enableMessageTracingSubtitle), - value: settingsService.settings.enableMessageTracing, - onChanged: (value) { - settingsService.setEnableMessageTracing(value); - }, - ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: const Icon(Icons.short_text, size: 20), - title: Text(context.l10n.appSettings_regionOnHopsLine), - subtitle: Text(context.l10n.appSettings_regionOnHopsLineSubtitle), - value: settingsService.settings.regionOnHopsLine, - onChanged: settingsService.setRegionOnHopsLine, - ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: const Icon(Icons.cell_tower, size: 20), + secondary: const Icon(Icons.cell_tower, size: 24), title: Text(context.l10n.appSettings_channelMinHops), subtitle: Text(context.l10n.appSettings_channelMinHopsSubtitle), value: settingsService.settings.channelMinHopsEnabled, @@ -689,7 +656,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.hub_outlined, size: 20), + secondary: const Icon(Icons.hub_outlined, size: 24), title: Text(context.l10n.appSettings_channelMinHopsCountRepeaters), subtitle: Text( context.l10n.appSettings_channelMinHopsCountRepeatersSubtitle( @@ -700,7 +667,16 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setChannelMinHopsCountRepeaters, ), ], - const Divider(height: 1, indent: 16), + ], + ); + } + + Widget _buildImageMessagesContent( + BuildContext context, + AppSettingsService settingsService, + ) { + return Column( + children: [ _ScrollIntoViewOnce( enabled: focusImageMessages, child: SwitchListTile( @@ -708,7 +684,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.image_outlined, size: 20), + secondary: const Icon(Icons.image_outlined, size: 24), title: Text(context.l10n.imageMessages_enableTitle), subtitle: Text(context.l10n.imageMessages_enableSubtitle), value: settingsService.settings.imageMessagesEnabled, @@ -729,7 +705,7 @@ class AppSettingsScreen extends StatelessWidget { horizontal: 16, vertical: 4, ), - secondary: const Icon(Icons.auto_awesome_outlined, size: 20), + secondary: const Icon(Icons.auto_awesome_outlined, size: 24), title: Text(context.l10n.imageMessages_autoProcessTitle), subtitle: Text(context.l10n.imageMessages_autoProcessSubtitle), value: settingsService.settings.imageProcessAutomatically, @@ -784,7 +760,7 @@ class AppSettingsScreen extends StatelessWidget { ), child: Text( reason, - style: textTheme.bodySmall?.copyWith( + style: textTheme.bodyMedium?.copyWith( color: scheme.onSurfaceVariant, ), ), @@ -795,11 +771,11 @@ class AppSettingsScreen extends StatelessWidget { ListTile( contentPadding: EdgeInsets.zero, dense: true, - leading: const Icon(Icons.check_circle_outline, size: 20), + leading: const Icon(Icons.check_circle_outline, size: 24), title: Text(model.name.isEmpty ? model.id : model.name), - subtitle: Text(_formatModelBytes(model.fileSizeBytes)), + subtitle: Text(_formatModelBytes(context, model.fileSizeBytes)), trailing: IconButton( - icon: const Icon(Icons.delete_outline, size: 20), + icon: const Icon(Icons.delete_outline, size: 24), tooltip: context.l10n.imageMessages_removeModel, onPressed: codec.isBusy || codec.isDownloading ? null @@ -810,7 +786,7 @@ class AppSettingsScreen extends StatelessWidget { const SizedBox(height: 6), Text( codec.lastError!, - style: textTheme.bodySmall?.copyWith(color: scheme.error), + style: textTheme.bodyMedium?.copyWith(color: scheme.error), ), ], ], @@ -839,12 +815,12 @@ class AppSettingsScreen extends StatelessWidget { ListTile( contentPadding: EdgeInsets.zero, dense: true, - leading: const Icon(Icons.download_outlined, size: 20), + leading: const Icon(Icons.download_outlined, size: 24), title: Text(spec.label), subtitle: Text( blocked ? context.l10n.imageMessages_modelNotPublished - : _formatModelBytes(spec.totalSizeBytes), + : _formatModelBytes(context, spec.totalSizeBytes), ), trailing: alreadyHave ? Text( @@ -893,24 +869,34 @@ class AppSettingsScreen extends StatelessWidget { } } - String _formatModelBytes(int bytes) { + String _formatModelBytes(BuildContext context, int bytes) { + final l10n = context.l10n; if (bytes >= 1024 * 1024 * 1024) { - return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB'; + return l10n.mapCache_sizeGigabytes( + (bytes / (1024 * 1024 * 1024)).toStringAsFixed(2), + ); } if (bytes >= 1024 * 1024) { - return '${(bytes / (1024 * 1024)).toStringAsFixed(0)} MB'; + return l10n.mapCache_sizeMegabytes( + (bytes / (1024 * 1024)).toStringAsFixed(0), + ); } - if (bytes >= 1024) return '${(bytes / 1024).toStringAsFixed(0)} kB'; - return '$bytes B'; + if (bytes >= 1024) { + return l10n.mapCache_sizeKilobytes((bytes / 1024).toStringAsFixed(0)); + } + return l10n.mapCache_sizeBytes('$bytes'); } Widget _buildBatteryContent( BuildContext context, AppSettingsService settingsService, - MeshCoreConnector connector, ) { - final deviceId = connector.batteryDeviceKey; - final isConnected = connector.isConnected && deviceId != null; + // Only the three connector fields this card shows trigger a rebuild. + final (deviceId, connected, deviceName) = context + .select( + (c) => (c.batteryDeviceKey, c.isConnected, c.deviceDisplayName), + ); + final isConnected = connected && deviceId != null; final selection = isConnected ? settingsService.batteryChemistryForDevice(deviceId) : 'nmc'; @@ -926,7 +912,7 @@ class AppSettingsScreen extends StatelessWidget { children: [ Icon( Icons.battery_full, - size: 20, + size: 24, color: scheme.onSurfaceVariant, ), const SizedBox(width: 12), @@ -936,7 +922,7 @@ class AppSettingsScreen extends StatelessWidget { children: [ Text( context.l10n.appSettings_batteryChemistry, - style: textTheme.bodyMedium?.copyWith( + style: textTheme.bodyLarge?.copyWith( fontWeight: FontWeight.w600, ), ), @@ -944,12 +930,12 @@ class AppSettingsScreen extends StatelessWidget { Text( isConnected ? context.l10n.appSettings_batteryChemistryPerDevice( - connector.deviceDisplayName, + deviceName, ) : context .l10n .appSettings_batteryChemistryConnectFirst, - style: textTheme.bodySmall?.copyWith( + style: textTheme.bodyMedium?.copyWith( color: scheme.onSurfaceVariant, ), ), @@ -1004,324 +990,117 @@ class AppSettingsScreen extends StatelessWidget { BuildContext context, AppSettingsService settingsService, ) { - final scheme = Theme.of(context).colorScheme; - final textTheme = Theme.of(context).textTheme; - final children = [ - SwitchListTile( - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - secondary: const Icon(Icons.router_outlined, size: 20), - title: Text(context.l10n.appSettings_showRepeaters), - subtitle: Text(context.l10n.appSettings_showRepeatersSubtitle), - value: settingsService.settings.mapShowRepeaters, - onChanged: (value) => settingsService.setMapShowRepeaters(value), - ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - secondary: const Icon(Icons.chat_outlined, size: 20), - title: Text(context.l10n.appSettings_showChatNodes), - subtitle: Text(context.l10n.appSettings_showChatNodesSubtitle), - value: settingsService.settings.mapShowChatNodes, - onChanged: (value) => settingsService.setMapShowChatNodes(value), - ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - secondary: const Icon(Icons.people_outline, size: 20), - title: Text(context.l10n.appSettings_showOtherNodes), - subtitle: Text(context.l10n.appSettings_showOtherNodesSubtitle), - value: settingsService.settings.mapShowOtherNodes, - onChanged: (value) => settingsService.setMapShowOtherNodes(value), - ), - const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showTimeFilterSheet(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon( - Icons.timer_outlined, - size: 20, - color: scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_timeFilter, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - settingsService.settings.mapTimeFilterHours == 0 - ? context.l10n.appSettings_timeFilterShowAll - : context.l10n.appSettings_timeFilterShowLast( - settingsService.settings.mapTimeFilterHours - .toInt(), - ), - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), + final settings = settingsService.settings; + const tilePadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4); + return Column( + children: [ + SwitchListTile( + contentPadding: tilePadding, + secondary: const Icon(Icons.router_outlined, size: 24), + title: Text(context.l10n.appSettings_showRepeaters), + subtitle: Text(context.l10n.appSettings_showRepeatersSubtitle), + value: settings.mapShowRepeaters, + onChanged: (value) => settingsService.setMapShowRepeaters(value), ), - ), - const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showUnitsSheet(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon(Icons.straighten, size: 20, color: scheme.onSurfaceVariant), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_unitsTitle, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - settingsService.settings.unitSystem == UnitSystem.imperial - ? context.l10n.appSettings_unitsImperial - : context.l10n.appSettings_unitsMetric, - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: tilePadding, + secondary: const Icon(Icons.chat_outlined, size: 24), + title: Text(context.l10n.appSettings_showChatNodes), + subtitle: Text(context.l10n.appSettings_showChatNodesSubtitle), + value: settings.mapShowChatNodes, + onChanged: (value) => settingsService.setMapShowChatNodes(value), ), - ), - const Divider(height: 1, indent: 16), - InkWell( - onTap: () { - Navigator.push( + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: tilePadding, + secondary: const Icon(Icons.people_outline, size: 24), + title: Text(context.l10n.appSettings_showOtherNodes), + subtitle: Text(context.l10n.appSettings_showOtherNodesSubtitle), + value: settings.mapShowOtherNodes, + onChanged: (value) => settingsService.setMapShowOtherNodes(value), + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.timer_outlined, + title: context.l10n.appSettings_timeFilter, + subtitle: settings.mapTimeFilterHours == 0 + ? context.l10n.appSettings_timeFilterShowAll + : context.l10n.appSettings_timeFilterShowLast( + settings.mapTimeFilterHours.toInt(), + ), + onTap: () => _showTimeFilterSheet(context, settingsService), + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.straighten, + title: context.l10n.appSettings_unitsTitle, + subtitle: settings.unitSystem == UnitSystem.imperial + ? context.l10n.appSettings_unitsImperial + : context.l10n.appSettings_unitsMetric, + onTap: () => _showUnitsSheet(context, settingsService), + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.download_outlined, + title: context.l10n.appSettings_offlineMapCache, + subtitle: settings.mapCacheBounds == null + ? context.l10n.appSettings_noAreaSelected + : context.l10n.appSettings_areaSelectedZoom( + settings.mapCacheMinZoom, + settings.mapCacheMaxZoom, + ), + onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => const MapCacheScreen()), - ); - }, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon( - Icons.download_outlined, - size: 20, - color: scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_offlineMapCache, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - settingsService.settings.mapCacheBounds == null - ? context.l10n.appSettings_noAreaSelected - : context.l10n.appSettings_areaSelectedZoom( - settingsService.settings.mapCacheMinZoom, - settingsService.settings.mapCacheMaxZoom, - ), - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), - ), - ), - const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showMapRasterSourceDialog(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon( - Icons.layers_outlined, - size: 20, - color: scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_rasterTileSource, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - _mapRasterSourceSummary(settingsService.settings), - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), - ), - ), - ]; - - if (_isStadiaSource(settingsService.settings)) { - children.addAll([ - const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showMapRasterEndpointDialog(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon( - Icons.public_outlined, - size: 20, - color: scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_stadiaEndpoint, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - _mapRasterEndpointSummary(settingsService.settings), - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), ), ), const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showMapApiKeyDialog(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon( - Icons.key_outlined, - size: 20, - color: scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.appSettings_stadiaApiKey, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - _mapApiKeySummary(context, settingsService.settings), - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), - ), + MeshNavTile( + icon: Icons.layers_outlined, + title: context.l10n.appSettings_rasterTileSource, + subtitle: _mapRasterSourceSummary(context, settings), + subtitleMaxLines: 2, + onTap: () => _showMapRasterSourceDialog(context, settingsService), ), - ]); - } - - return Column(children: children); + if (_isStadiaSource(settings)) ...[ + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.public_outlined, + title: context.l10n.appSettings_stadiaEndpoint, + subtitle: _mapRasterEndpointSummary(context, settings), + onTap: () => _showMapRasterEndpointDialog(context, settingsService), + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.key_outlined, + title: context.l10n.appSettings_stadiaApiKey, + subtitle: _mapApiKeySummary(context, settings), + onTap: () => _showMapApiKeyDialog(context, settingsService), + ), + ], + ], + ); } - String _mapRasterSourceSummary(AppSettings settings) { + String _mapRasterSourceSummary(BuildContext context, AppSettings settings) { final source = MapRasterSourceCatalog.fromSettings(settings); - return '${source.label} - ${source.description}'; + return context.l10n.appSettings_sourceSummary( + source.label, + source.description, + ); } bool _isStadiaSource(AppSettings settings) { return MapRasterSourceCatalog.fromSettings(settings).isStadia; } - String _mapRasterEndpointSummary(AppSettings settings) { + String _mapRasterEndpointSummary(BuildContext context, AppSettings settings) { final endpoint = MapRasterEndpointCatalog.fromSettings(settings); - return '${endpoint.label} - ${endpoint.description}'; + return context.l10n.appSettings_sourceSummary( + endpoint.label, + endpoint.description, + ); } String _mapApiKeySummary(BuildContext context, AppSettings settings) { @@ -1458,381 +1237,18 @@ class AppSettingsScreen extends StatelessWidget { AppSettingsService settingsService, ) { final currentApiKey = settingsService.settings.mapTileApiKey?.trim() ?? ''; - final maskedApiKey = _maskApiKey( - currentApiKey.isEmpty ? AppSettings.stadiaDemo : currentApiKey, - ); - final controller = TextEditingController(text: maskedApiKey); - showDialog( + showDialog( context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.appSettings_stadiaApiKey), - content: SizedBox( - width: 420, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(context.l10n.appSettings_stadiaApiKeyDialogDescription), - const SizedBox(height: 12), - TextField( - controller: controller, - autofocus: true, - autocorrect: false, - enableSuggestions: false, - autofillHints: const [AutofillHints.password], - decoration: const InputDecoration( - border: OutlineInputBorder(), - hintText: '4e1bf343-3d91-4d9c-a8e1-1234567890ab', - ), - ), - ], - ), + builder: (_) => _MapApiKeyDialog( + settingsService: settingsService, + currentApiKey: currentApiKey, + maskedApiKey: _maskApiKey( + currentApiKey.isEmpty ? AppSettings.stadiaDemo : currentApiKey, ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () async { - final apiKey = controller.text.trim(); - await settingsService.setMapTileApiKey( - apiKey == maskedApiKey ? currentApiKey : apiKey, - ); - if (!dialogContext.mounted) return; - Navigator.pop(dialogContext); - }, - child: Text(context.l10n.common_save), - ), - ], ), ); } - Widget _buildTranslationContent( - BuildContext context, - AppSettingsService settingsService, - TranslationService translationService, - ) { - final settings = settingsService.settings; - final translationEnabled = settings.translationEnabled; - final scheme = Theme.of(context).colorScheme; - final textTheme = Theme.of(context).textTheme; - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: const Icon(Icons.translate, size: 20), - title: Text(context.l10n.translation_enableTitle), - subtitle: Text(context.l10n.translation_enableSubtitle), - value: settings.translationEnabled, - onChanged: settingsService.setTranslationEnabled, - ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: Icon( - Icons.auto_awesome_outlined, - size: 20, - color: translationEnabled ? null : Theme.of(context).disabledColor, - ), - title: Text( - context.l10n.translation_autoIncomingTitle, - style: TextStyle( - color: translationEnabled - ? null - : Theme.of(context).disabledColor, - ), - ), - subtitle: Text( - context.l10n.translation_autoIncomingSubtitle, - style: TextStyle( - color: translationEnabled - ? null - : Theme.of(context).disabledColor, - ), - ), - value: settings.autoTranslateIncomingMessages, - onChanged: translationEnabled - ? settingsService.setAutoTranslateIncomingMessages - : null, - ), - const Divider(height: 1, indent: 16), - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, - ), - secondary: Icon( - Icons.outgoing_mail, - size: 20, - color: translationEnabled ? null : Theme.of(context).disabledColor, - ), - title: Text( - context.l10n.translation_composerTitle, - style: TextStyle( - color: translationEnabled - ? null - : Theme.of(context).disabledColor, - ), - ), - subtitle: Text( - context.l10n.translation_composerSubtitle, - style: TextStyle( - color: translationEnabled - ? null - : Theme.of(context).disabledColor, - ), - ), - value: settings.composerTranslationEnabled, - onChanged: translationEnabled - ? settingsService.setComposerTranslationEnabled - : null, - ), - const Divider(height: 1, indent: 16), - InkWell( - onTap: () => _showTranslationLanguageDialog(context, settingsService), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon(Icons.language, size: 20, color: scheme.onSurfaceVariant), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.translation_targetLanguage, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - _translationLanguageLabel( - context, - settings.translationTargetLanguageCode, - ), - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon( - Icons.chevron_right, - color: scheme.onSurfaceVariant, - size: 16, - ), - ], - ), - ), - ), - const Divider(height: 1, indent: 16), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: DropdownButtonFormField( - initialValue: settings.translationSelectedModelId, - isExpanded: true, - decoration: InputDecoration( - labelText: context.l10n.translation_downloadedModelLabel, - border: const OutlineInputBorder(), - ), - items: [ - for (final model in settings.translationDownloadedModels) - DropdownMenuItem( - value: model.id, - child: Text( - translationModelFriendlyName(model), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: settings.translationDownloadedModels.isEmpty - ? null - : (value) { - settingsService.setTranslationSelectedModelId(value); - }, - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), - child: DropdownButtonFormField( - initialValue: null, - isExpanded: true, - decoration: InputDecoration( - labelText: context.l10n.translation_presetModelLabel, - border: const OutlineInputBorder(), - ), - items: [ - for (final preset in translationPresetModels) - DropdownMenuItem( - value: preset.sourceUrl, - child: Text( - translationModelFriendlyName(preset), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: translationService.isBusy - ? null - : (value) async { - if (value == null) return; - final preset = translationPresetModels.firstWhere( - (entry) => entry.sourceUrl == value, - ); - await _downloadTranslationModel( - context, - translationService, - settingsService, - sourceUrl: preset.sourceUrl, - fileName: preset.name, - id: preset.id, - ); - }, - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _TranslationUrlField( - initialValue: settings.translationModelSourceUrl ?? '', - onChanged: settingsService.setTranslationModelSourceUrl, - onDownload: translationService.isBusy - ? null - : (url) => _downloadTranslationModel( - context, - translationService, - settingsService, - sourceUrl: url, - ), - downloadLabel: translationService.isDownloading - ? context.l10n.translation_downloading - : translationService.isBusy - ? context.l10n.translation_working - : context.l10n.translation_downloadModel, - isDownloading: translationService.isDownloading, - onCancel: translationService.cancelDownload, - labelText: context.l10n.translation_manualUrlLabel, - stopLabel: context.l10n.translation_stop, - ), - if (translationService.isDownloading) ...[ - const SizedBox(height: 12), - ClipRRect( - borderRadius: BorderRadius.circular(2), - child: LinearProgressIndicator( - value: - translationService.downloadFileName == - 'Merging chunks...' - ? null - : translationService.downloadProgress, - ), - ), - const SizedBox(height: 8), - Align( - alignment: Alignment.centerLeft, - child: Text( - _downloadProgressLabel(context, translationService), - style: MeshTheme.mono( - fontSize: 12, - color: scheme.onSurfaceVariant, - ), - ), - ), - ], - if (settings.translationDownloadedModels.isNotEmpty) ...[ - const SizedBox(height: 16), - Align( - alignment: Alignment.centerLeft, - child: Text( - context.l10n.translation_downloadedModels, - style: Theme.of(context).textTheme.titleSmall, - ), - ), - const SizedBox(height: 8), - for (final model in settings.translationDownloadedModels) - Padding( - padding: const EdgeInsets.only(bottom: 8), - child: Row( - children: [ - Icon( - model.id == settings.translationSelectedModelId - ? Icons.check_circle - : Icons.memory_outlined, - size: 20, - color: model.id == settings.translationSelectedModelId - ? scheme.primary - : scheme.onSurfaceVariant, - ), - const SizedBox(width: 12), - Expanded( - child: InkWell( - borderRadius: BorderRadius.circular(MeshRadii.xs), - onTap: () => settingsService - .setTranslationSelectedModelId(model.id), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - translationModelFriendlyName(model), - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - Text( - _downloadedModelLabel(model), - style: MeshTheme.mono( - fontSize: 11, - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - ), - IconButton( - tooltip: context.l10n.translation_deleteModel, - onPressed: translationService.isBusy - ? null - : () => _deleteTranslationModel( - context, - translationService, - model, - ), - icon: const Icon(Icons.delete_outline), - ), - ], - ), - ), - ], - if (translationService.lastError != null) ...[ - const SizedBox(height: 8), - Text( - translationService.lastError!, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - ], - ], - ), - ), - ], - ); - } - Widget _buildCyr2LatContent( BuildContext context, AppSettingsService settingsService, @@ -1870,8 +1286,11 @@ class AppSettingsScreen extends StatelessWidget { children: [ Expanded( child: OutlinedButton.icon( - onPressed: () => - _showAddCyr2LatProfileDialog(context, settingsService), + onPressed: () => showDialog( + context: context, + builder: (_) => + Cyr2LatProfileDialog(settingsService: settingsService), + ), icon: const Icon(Icons.add), label: Text(context.l10n.common_add), ), @@ -1879,10 +1298,12 @@ class AppSettingsScreen extends StatelessWidget { const SizedBox(width: 8), Expanded( child: OutlinedButton.icon( - onPressed: () => _showEditCyr2LatProfileDialog( - context, - settingsService, - selectedProfile, + onPressed: () => showDialog( + context: context, + builder: (_) => Cyr2LatProfileDialog( + settingsService: settingsService, + profile: selectedProfile, + ), ), icon: const Icon(Icons.edit), label: Text(context.l10n.common_edit), @@ -1914,7 +1335,7 @@ class AppSettingsScreen extends StatelessWidget { ) { return SwitchListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - secondary: const Icon(Icons.bug_report_outlined, size: 20), + secondary: const Icon(Icons.bug_report_outlined, size: 24), title: Text(context.l10n.appSettings_appDebugLogging), subtitle: Text(context.l10n.appSettings_appDebugLoggingSubtitle), value: settingsService.settings.appDebugLogEnabled, @@ -1934,262 +1355,6 @@ class AppSettingsScreen extends StatelessWidget { ); } - String _languageLabel(BuildContext context, String? languageCode) { - switch (languageCode) { - case 'en': - return context.l10n.appSettings_languageEn; - case 'fr': - return context.l10n.appSettings_languageFr; - case 'es': - return context.l10n.appSettings_languageEs; - case 'de': - return context.l10n.appSettings_languageDe; - case 'pl': - return context.l10n.appSettings_languagePl; - case 'sl': - return context.l10n.appSettings_languageSl; - case 'pt': - return context.l10n.appSettings_languagePt; - case 'it': - return context.l10n.appSettings_languageIt; - case 'zh': - return context.l10n.appSettings_languageZh; - case 'sv': - return context.l10n.appSettings_languageSv; - case 'nl': - return context.l10n.appSettings_languageNl; - case 'sk': - return context.l10n.appSettings_languageSk; - case 'bg': - return context.l10n.appSettings_languageBg; - case 'ru': - return context.l10n.appSettings_languageRu; - case 'uk': - return context.l10n.appSettings_languageUk; - case 'hu': - return context.l10n.appSettings_languageHu; - case 'ja': - return context.l10n.appSettings_languageJa; - case 'ko': - return context.l10n.appSettings_languageKo; - default: - return context.l10n.appSettings_languageSystem; - } - } - - void _showLanguageSheet( - BuildContext context, - AppSettingsService settingsService, - ) { - showMeshSheet( - context, - builder: (ctx) => Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader(title: context.l10n.appSettings_language), - SizedBox( - height: 400, - child: ListView( - children: [ - _sheetOption( - ctx, - label: context.l10n.appSettings_languageSystem, - value: null, - selected: settingsService.settings.languageOverride == null, - onTap: () { - settingsService.setLanguageOverride(null); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageEn, - value: 'en', - selected: settingsService.settings.languageOverride == 'en', - onTap: () { - settingsService.setLanguageOverride('en'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageFr, - value: 'fr', - selected: settingsService.settings.languageOverride == 'fr', - onTap: () { - settingsService.setLanguageOverride('fr'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageEs, - value: 'es', - selected: settingsService.settings.languageOverride == 'es', - onTap: () { - settingsService.setLanguageOverride('es'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageDe, - value: 'de', - selected: settingsService.settings.languageOverride == 'de', - onTap: () { - settingsService.setLanguageOverride('de'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languagePl, - value: 'pl', - selected: settingsService.settings.languageOverride == 'pl', - onTap: () { - settingsService.setLanguageOverride('pl'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageSl, - value: 'sl', - selected: settingsService.settings.languageOverride == 'sl', - onTap: () { - settingsService.setLanguageOverride('sl'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languagePt, - value: 'pt', - selected: settingsService.settings.languageOverride == 'pt', - onTap: () { - settingsService.setLanguageOverride('pt'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageIt, - value: 'it', - selected: settingsService.settings.languageOverride == 'it', - onTap: () { - settingsService.setLanguageOverride('it'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageZh, - value: 'zh', - selected: settingsService.settings.languageOverride == 'zh', - onTap: () { - settingsService.setLanguageOverride('zh'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageSv, - value: 'sv', - selected: settingsService.settings.languageOverride == 'sv', - onTap: () { - settingsService.setLanguageOverride('sv'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageNl, - value: 'nl', - selected: settingsService.settings.languageOverride == 'nl', - onTap: () { - settingsService.setLanguageOverride('nl'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageSk, - value: 'sk', - selected: settingsService.settings.languageOverride == 'sk', - onTap: () { - settingsService.setLanguageOverride('sk'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageBg, - value: 'bg', - selected: settingsService.settings.languageOverride == 'bg', - onTap: () { - settingsService.setLanguageOverride('bg'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageRu, - value: 'ru', - selected: settingsService.settings.languageOverride == 'ru', - onTap: () { - settingsService.setLanguageOverride('ru'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageUk, - value: 'uk', - selected: settingsService.settings.languageOverride == 'uk', - onTap: () { - settingsService.setLanguageOverride('uk'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageHu, - value: 'hu', - selected: settingsService.settings.languageOverride == 'hu', - onTap: () { - settingsService.setLanguageOverride('hu'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageJa, - value: 'ja', - selected: settingsService.settings.languageOverride == 'ja', - onTap: () { - settingsService.setLanguageOverride('ja'); - Navigator.pop(ctx); - }, - ), - _sheetOption( - ctx, - label: context.l10n.appSettings_languageKo, - value: 'ko', - selected: settingsService.settings.languageOverride == 'ko', - onTap: () { - settingsService.setLanguageOverride('ko'); - Navigator.pop(ctx); - }, - ), - SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8), - ], - ), - ), - ], - ), - ); - } - void _showTimeFilterSheet( BuildContext context, AppSettingsService settingsService, @@ -2204,50 +1369,40 @@ class AppSettingsScreen extends StatelessWidget { padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), child: Text(context.l10n.appSettings_showNodesDiscoveredWithin), ), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_allTime, - value: 0, selected: settingsService.settings.mapTimeFilterHours == 0, onTap: () { settingsService.setMapTimeFilterHours(0); Navigator.pop(ctx); }, ), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_lastHour, - value: 1, selected: settingsService.settings.mapTimeFilterHours == 1, onTap: () { settingsService.setMapTimeFilterHours(1); Navigator.pop(ctx); }, ), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_last6Hours, - value: 6, selected: settingsService.settings.mapTimeFilterHours == 6, onTap: () { settingsService.setMapTimeFilterHours(6); Navigator.pop(ctx); }, ), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_last24Hours, - value: 24, selected: settingsService.settings.mapTimeFilterHours == 24, onTap: () { settingsService.setMapTimeFilterHours(24); Navigator.pop(ctx); }, ), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_lastWeek, - value: 168, selected: settingsService.settings.mapTimeFilterHours == 168, onTap: () { settingsService.setMapTimeFilterHours(168); @@ -2270,20 +1425,16 @@ class AppSettingsScreen extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ BottomSheetHeader(title: context.l10n.appSettings_unitsTitle), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_unitsMetric, - value: UnitSystem.metric, selected: settingsService.settings.unitSystem == UnitSystem.metric, onTap: () { settingsService.setUnitSystem(UnitSystem.metric); Navigator.pop(ctx); }, ), - _sheetOption( - ctx, + MeshSheetOption( label: context.l10n.appSettings_unitsImperial, - value: UnitSystem.imperial, selected: settingsService.settings.unitSystem == UnitSystem.imperial, onTap: () { @@ -2297,323 +1448,6 @@ class AppSettingsScreen extends StatelessWidget { ); } - Widget _sheetOption( - BuildContext context, { - required String label, - required T value, - required bool selected, - required VoidCallback onTap, - }) { - final scheme = Theme.of(context).colorScheme; - return ListTile( - leading: Icon( - selected ? Icons.radio_button_checked : Icons.radio_button_unchecked, - color: selected ? scheme.primary : scheme.onSurfaceVariant, - ), - title: Text(label), - onTap: onTap, - ); - } - - void _showTranslationLanguageDialog( - BuildContext context, - AppSettingsService settingsService, - ) { - showDialog( - context: context, - builder: (context) => _TranslationLanguageDialogContent( - currentLanguageCode: - settingsService.settings.translationTargetLanguageCode, - onLanguageSelected: (value) { - settingsService.setTranslationTargetLanguageCode(value); - Navigator.pop(context); - }, - ), - ); - } - - Future _downloadTranslationModel( - BuildContext context, - TranslationService translationService, - AppSettingsService settingsService, { - required String sourceUrl, - String? fileName, - String? id, - }) async { - if (sourceUrl.isEmpty) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.translation_enterUrlFirst), - ); - return; - } - try { - await translationService.downloadModel( - sourceUrl: sourceUrl, - fileName: fileName, - id: id, - ); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(context.l10n.translation_modelDownloaded), - ); - await settingsService.setTranslationEnabled(true); - } on TranslationDownloadCancelled { - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(context.l10n.translation_downloadStopped), - ); - } catch (error) { - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text( - context.l10n.translation_downloadFailed(error.toString()), - ), - ); - } - } - - String _translationLanguageLabel(BuildContext context, String? languageCode) { - if (languageCode == null || languageCode.isEmpty) { - return context.l10n.translation_useAppLanguage; - } - for (final option in supportedTranslationLanguages) { - if (option.code == languageCode) { - return option.label; - } - } - return languageCode.toUpperCase(); - } - - String _downloadProgressLabel( - BuildContext context, - TranslationService translationService, - ) { - final fileName = translationService.downloadFileName ?? 'Model'; - if (fileName == 'Merging chunks...') { - return context.l10n.translation_mergingChunks; - } - final currentMb = translationService.downloadedBytes / (1024 * 1024); - final totalBytes = translationService.downloadTotalBytes; - if (totalBytes == null || totalBytes <= 0) { - return '$fileName: ${currentMb.toStringAsFixed(1)} MB'; - } - final totalMb = totalBytes / (1024 * 1024); - final percent = ((translationService.downloadProgress ?? 0) * 100) - .toStringAsFixed(0); - return '$fileName: ${currentMb.toStringAsFixed(1)} / ${totalMb.toStringAsFixed(1)} MB ($percent%)'; - } - - Future _deleteTranslationModel( - BuildContext context, - TranslationService translationService, - TranslationModelRecord model, - ) async { - try { - await translationService.removeModel(model); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text( - context.l10n.appSettings_translationModelDeleted( - translationModelFriendlyName(model), - ), - ), - ); - } catch (error) { - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text( - context.l10n.appSettings_translationModelDeleteFailed('$error'), - ), - ); - } - } - - String _downloadedModelLabel(TranslationModelRecord model) { - final sizeMb = model.fileSizeBytes / (1024 * 1024); - final source = model.sourceUrl.isEmpty ? model.name : model.sourceUrl; - return '${sizeMb.toStringAsFixed(1)} MB • $source'; - } - - void _showAddCyr2LatProfileDialog( - BuildContext context, - AppSettingsService settingsService, - ) { - final nameController = TextEditingController(); - final jsonController = TextEditingController( - text: const JsonEncoder.withIndent(' ').convert(defaultCyr2LatCharMap), - ); - - showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text(context.l10n.settings_cyr2latProfileAdd), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: nameController, - decoration: InputDecoration( - labelText: context.l10n.settings_cyr2latProfileName, - border: const OutlineInputBorder(), - ), - ), - const SizedBox(height: 16), - TextField( - controller: jsonController, - maxLines: 15, - decoration: InputDecoration( - labelText: context.l10n.channels_cyr2latSettingsDialogHint, - border: const OutlineInputBorder(), - hintText: context.l10n.channels_cyr2latSettingsDscr, - ), - ), - ], - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () async { - if (nameController.text.isEmpty) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.settings_cyr2latProfileNameEmpty), - ); - return; - } - try { - final json = - jsonDecode(jsonController.text) as Map; - final map = json.map( - (key, value) => MapEntry(key, value.toString()), - ); - final profile = Cyr2LatProfile( - id: DateTime.now().millisecondsSinceEpoch.toString(), - name: nameController.text, - charMap: map, - ); - await settingsService.addCyr2LatProfile(profile); - if (!context.mounted) return; - Navigator.pop(context); - showDismissibleSnackBar( - context, - content: Text(context.l10n.settings_cyr2latProfileAdded), - ); - } catch (e) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_cyr2latSettingsDialogWrongJSON( - e.toString(), - ), - ), - ); - } - }, - child: Text(context.l10n.common_save), - ), - ], - ), - ); - } - - void _showEditCyr2LatProfileDialog( - BuildContext context, - AppSettingsService settingsService, - Cyr2LatProfile profile, - ) { - final nameController = TextEditingController(text: profile.name); - final jsonController = TextEditingController( - text: const JsonEncoder.withIndent(' ').convert(profile.charMap), - ); - - showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text(context.l10n.settings_cyr2latProfileEdit), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: nameController, - decoration: InputDecoration( - labelText: context.l10n.settings_cyr2latProfileName, - border: const OutlineInputBorder(), - ), - ), - const SizedBox(height: 16), - TextField( - controller: jsonController, - maxLines: 15, - decoration: InputDecoration( - labelText: context.l10n.channels_cyr2latSettingsDialogHint, - border: const OutlineInputBorder(), - hintText: context.l10n.channels_cyr2latSettingsDscr, - ), - ), - ], - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () async { - if (nameController.text.isEmpty) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.settings_cyr2latProfileNameEmpty), - ); - return; - } - try { - final json = - jsonDecode(jsonController.text) as Map; - final map = json.map( - (key, value) => MapEntry(key, value.toString()), - ); - final updatedProfile = profile.copyWith( - name: nameController.text, - charMap: map, - ); - await settingsService.updateCyr2LatProfile(updatedProfile); - if (!context.mounted) return; - Navigator.pop(context); - showDismissibleSnackBar( - context, - content: Text(context.l10n.settings_cyr2latProfileUpdated), - ); - } catch (e) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_cyr2latSettingsDialogWrongJSON( - e.toString(), - ), - ), - ); - } - }, - child: Text(context.l10n.common_save), - ), - ], - ), - ); - } - void _showDeleteCyr2LatProfileDialog( BuildContext context, AppSettingsService settingsService, @@ -2649,41 +1483,29 @@ class AppSettingsScreen extends StatelessWidget { } } -/// Owns the [TextEditingController] for the manual model URL field so it -/// survives rebuilds of the parent [Consumer3]. -class _TranslationUrlField extends StatefulWidget { - const _TranslationUrlField({ - required this.initialValue, - required this.onChanged, - required this.onDownload, - required this.downloadLabel, - required this.isDownloading, - required this.onCancel, - required this.labelText, - required this.stopLabel, +/// Stadia API key editor. Owns (and disposes) its controller; the key is +/// obscured by default with a visibility toggle. The field starts with the +/// masked current key, and saving it unchanged keeps the current key. +class _MapApiKeyDialog extends StatefulWidget { + final AppSettingsService settingsService; + final String currentApiKey; + final String maskedApiKey; + + const _MapApiKeyDialog({ + required this.settingsService, + required this.currentApiKey, + required this.maskedApiKey, }); - final String initialValue; - final ValueChanged onChanged; - final void Function(String url)? onDownload; - final String downloadLabel; - final bool isDownloading; - final VoidCallback onCancel; - final String labelText; - final String stopLabel; - @override - State<_TranslationUrlField> createState() => _TranslationUrlFieldState(); + State<_MapApiKeyDialog> createState() => _MapApiKeyDialogState(); } -class _TranslationUrlFieldState extends State<_TranslationUrlField> { - late final TextEditingController _controller; - - @override - void initState() { - super.initState(); - _controller = TextEditingController(text: widget.initialValue); - } +class _MapApiKeyDialogState extends State<_MapApiKeyDialog> { + late final TextEditingController _controller = TextEditingController( + text: widget.maskedApiKey, + ); + bool _obscured = true; @override void dispose() { @@ -2691,124 +1513,48 @@ class _TranslationUrlFieldState extends State<_TranslationUrlField> { super.dispose(); } - @override - Widget build(BuildContext context) { - return Column( - children: [ - TextField( - controller: _controller, - decoration: InputDecoration( - labelText: widget.labelText, - border: const OutlineInputBorder(), - ), - onChanged: widget.onChanged, - ), - const SizedBox(height: 8), - Row( - children: [ - Expanded( - child: FilledButton.icon( - onPressed: widget.onDownload == null - ? null - : () => widget.onDownload!(_controller.text.trim()), - icon: const Icon(Icons.download), - label: Text(widget.downloadLabel), - ), - ), - if (widget.isDownloading) ...[ - const SizedBox(width: 8), - OutlinedButton.icon( - onPressed: widget.onCancel, - icon: const Icon(Icons.stop_circle_outlined), - label: Text(widget.stopLabel), - ), - ], - ], - ), - ], + Future _save() async { + final apiKey = _controller.text.trim(); + await widget.settingsService.setMapTileApiKey( + apiKey == widget.maskedApiKey ? widget.currentApiKey : apiKey, ); - } -} - -/// Dialog content for choosing the translation target language. -/// Owns the search [TextEditingController] so it is properly disposed. -class _TranslationLanguageDialogContent extends StatefulWidget { - const _TranslationLanguageDialogContent({ - required this.currentLanguageCode, - required this.onLanguageSelected, - }); - - final String? currentLanguageCode; - final ValueChanged onLanguageSelected; - - @override - State<_TranslationLanguageDialogContent> createState() => - _TranslationLanguageDialogContentState(); -} - -class _TranslationLanguageDialogContentState - extends State<_TranslationLanguageDialogContent> { - late final TextEditingController _searchController; - List _filtered = supportedTranslationLanguages; - - @override - void initState() { - super.initState(); - _searchController = TextEditingController(); - } - - @override - void dispose() { - _searchController.dispose(); - super.dispose(); + if (!mounted) return; + Navigator.pop(context); } @override Widget build(BuildContext context) { + final l10n = context.l10n; return AlertDialog( - title: Text(context.l10n.translation_targetLanguage), + title: Text(l10n.appSettings_stadiaApiKey), content: SizedBox( - width: 360, + width: 420, child: Column( mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - TextField( - controller: _searchController, - decoration: const InputDecoration( - prefixIcon: Icon(Icons.search), - border: OutlineInputBorder(), - ), - onChanged: (value) { - final normalized = value.trim().toLowerCase(); - setState(() { - _filtered = supportedTranslationLanguages.where((option) { - return option.label.toLowerCase().contains(normalized) || - option.code.toLowerCase().contains(normalized); - }).toList(); - }); - }, - ), + Text(l10n.appSettings_stadiaApiKeyDialogDescription), const SizedBox(height: 12), - Flexible( - child: RadioGroup( - groupValue: widget.currentLanguageCode, - onChanged: (value) { - widget.onLanguageSelected(value); - }, - child: ListView( - shrinkWrap: true, - children: [ - RadioListTile( - value: null, - title: Text(context.l10n.translation_useAppLanguage), - ), - for (final option in _filtered) - RadioListTile( - value: option.code, - title: Text(option.label), - subtitle: Text(option.code.toUpperCase()), - ), - ], + TextField( + controller: _controller, + autofocus: true, + autocorrect: false, + enableSuggestions: false, + obscureText: _obscured, + autofillHints: const [AutofillHints.password], + decoration: InputDecoration( + border: const OutlineInputBorder(), + hintText: '4e1bf343-3d91-4d9c-a8e1-1234567890ab', + suffixIcon: IconButton( + tooltip: _obscured + ? l10n.appSettings_showApiKey + : l10n.appSettings_hideApiKey, + icon: Icon( + _obscured + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + ), + onPressed: () => setState(() => _obscured = !_obscured), ), ), ), @@ -2818,8 +1564,9 @@ class _TranslationLanguageDialogContentState actions: [ TextButton( onPressed: () => Navigator.pop(context), - child: Text(context.l10n.common_close), + child: Text(l10n.common_cancel), ), + TextButton(onPressed: _save, child: Text(l10n.common_save)), ], ); } diff --git a/lib/screens/ble_debug_log_screen.dart b/lib/screens/ble_debug_log_screen.dart index 7eb4aa5f..5a88e9ec 100644 --- a/lib/screens/ble_debug_log_screen.dart +++ b/lib/screens/ble_debug_log_screen.dart @@ -6,6 +6,7 @@ import '../services/ble_debug_log_service.dart'; import '../connector/meshcore_protocol.dart'; import '../theme/mesh_theme.dart'; import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/confirm_clear_dialog.dart'; import '../helpers/snack_bar_builder.dart'; enum _BleLogView { frames, rawLogRx } @@ -37,6 +38,9 @@ class _BleDebugLogScreenState extends State { final hasEntries = showingFrames ? entries.isNotEmpty : rawEntries.isNotEmpty; + final scheme = Theme.of(context).colorScheme; + final isDark = Theme.of(context).brightness == Brightness.dark; + final rxColor = isDark ? MeshPalette.signal : MeshPalette.signalDim; return Scaffold( appBar: AppBar( title: AdaptiveAppBarTitle(context.l10n.debugLog_bleTitle), @@ -73,8 +77,13 @@ class _BleDebugLogScreenState extends State { tooltip: context.l10n.debugLog_clearLog, icon: const Icon(Icons.delete_outline), onPressed: hasEntries - ? () { - logService.clear(); + ? () async { + final confirmed = await showConfirmClearDialog( + context, + title: context.l10n.debugLog_clearLog, + message: context.l10n.debugLog_clearConfirm, + ); + if (confirmed) logService.clear(); } : null, ), @@ -111,7 +120,7 @@ class _BleDebugLogScreenState extends State { ? entries.length : rawEntries.length, separatorBuilder: (_, _) => - const Divider(height: 1, color: MeshPalette.line), + Divider(height: 1, color: scheme.outlineVariant), itemBuilder: (context, index) { if (showingFrames) { final entry = entries[index]; @@ -144,7 +153,7 @@ class _BleDebugLogScreenState extends State { onLongPress: copyHex, onSecondaryTap: copyHex, child: Container( - color: MeshPalette.bg, + color: scheme.surfaceContainerLowest, padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 8, @@ -157,10 +166,10 @@ class _BleDebugLogScreenState extends State { entry.outgoing ? Icons.upload : Icons.download, - size: 18, + size: 20, color: entry.outgoing - ? MeshPalette.blue - : MeshPalette.signal, + ? scheme.primary + : rxColor, ), const SizedBox(width: 10), Expanded( @@ -171,24 +180,24 @@ class _BleDebugLogScreenState extends State { Text( entry.description, style: MeshTheme.mono( - fontSize: 11.5, - color: MeshPalette.ink, + fontSize: 13, + color: scheme.onSurface, ), ), const SizedBox(height: 2), Text( entry.hexPreview, style: MeshTheme.mono( - fontSize: 10, - color: MeshPalette.ink3, + fontSize: 13, + color: scheme.onSurfaceVariant, ), ), const SizedBox(height: 2), Text( time, style: MeshTheme.mono( - fontSize: 9.5, - color: MeshPalette.ink4, + fontSize: 12, + color: scheme.onSurfaceVariant, ), ), ], @@ -207,7 +216,7 @@ class _BleDebugLogScreenState extends State { return GestureDetector( onTap: () => _showRawDialog(context, info), child: Container( - color: MeshPalette.bg, + color: scheme.surfaceContainerLowest, padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 8, @@ -215,10 +224,10 @@ class _BleDebugLogScreenState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Icon( + Icon( Icons.download, - size: 18, - color: MeshPalette.signal, + size: 20, + color: rxColor, ), const SizedBox(width: 10), Expanded( @@ -229,24 +238,24 @@ class _BleDebugLogScreenState extends State { Text( info.title, style: MeshTheme.mono( - fontSize: 11.5, - color: MeshPalette.ink, + fontSize: 13, + color: scheme.onSurface, ), ), const SizedBox(height: 2), Text( info.summary, style: MeshTheme.mono( - fontSize: 10, - color: MeshPalette.ink3, + fontSize: 13, + color: scheme.onSurfaceVariant, ), ), const SizedBox(height: 2), Text( time, style: MeshTheme.mono( - fontSize: 9.5, - color: MeshPalette.ink4, + fontSize: 12, + color: scheme.onSurfaceVariant, ), ), ], @@ -259,9 +268,14 @@ class _BleDebugLogScreenState extends State { }, ) : Center( - child: Text( - context.l10n.debugLog_noBleActivity, - style: const TextStyle(color: MeshPalette.ink3), + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + context.l10n.debugLog_noBleActivity, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge + ?.copyWith(color: scheme.onSurfaceVariant), + ), ), ), ), diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 7f592dd5..5ab34313 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:math' as math; import 'dart:ui' as ui; +import 'package:flutter/foundation.dart' show mergeSort; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; @@ -12,7 +13,6 @@ import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../models/community.dart'; import '../storage/community_store.dart'; -import '../utils/app_logger.dart'; import '../utils/platform_info.dart'; import '../helpers/chat_scroll_controller.dart'; import '../connector/meshcore_protocol.dart'; @@ -26,7 +26,6 @@ import '../l10n/l10n.dart'; import '../models/channel.dart'; import '../models/channel_message.dart'; import '../models/image_codec_support.dart' show aeicRatePointForUi; -import '../models/translation_support.dart'; import '../services/app_settings_service.dart'; import '../services/chat_text_scale_service.dart'; import '../services/image_chunk_transport.dart'; @@ -37,18 +36,19 @@ import '../utils/image_save.dart'; import '../utils/lora_airtime.dart'; import '../widgets/marker_label_dialog.dart'; 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_composer.dart'; +import '../widgets/chat_send_pipeline.dart'; import '../widgets/chat_zoom_wrapper.dart'; +import '../widgets/message_bubble_frame.dart'; +import '../widgets/reaction_chips.dart'; import '../widgets/emoji_picker.dart'; import '../widgets/gif_message.dart'; import '../widgets/jump_to_bottom_button.dart'; -import '../widgets/gif_picker.dart'; import '../widgets/image_send_codec_binding.dart'; import '../widgets/image_send_preview_sheet.dart'; -import '../widgets/message_translation_button.dart'; import '../widgets/message_status_icon.dart'; import '../widgets/radio_stats_entry.dart'; import '../widgets/sync_progress_overlay.dart'; @@ -101,12 +101,13 @@ class _ChannelChatScreenState extends State { int _imageSendTotal = 0; MeshCoreConnector? _connector; - DateTime? _lastChannelSendAt; - // True while a send is awaiting outgoing translation, so a second tap - // can't send the same text again. - bool _isSendingText = false; + final ChatSendGuard _sendGuard = ChatSendGuard(); bool _channelSkipNextBottomSnap = false; String? _unreadDividerMessageId; + _TranscriptLayout? _transcriptLayout; + ReceivedImageStore? _watchedImageStore; + int _imageStoreVersion = 0; + ModalRoute? _route; @override void initState() { @@ -148,7 +149,8 @@ class _ChannelChatScreenState extends State { }); } - // TODO: Reload communities when returning from another screen + /// Loads the community list; also re-run whenever a covering route pops + /// (see [_onCoveringRouteStatus]). Future _loadCommunities() async { final connector = context.read(); _communityStore.setPublicKeyHex = connector.selfPublicKeyHex; @@ -202,8 +204,29 @@ class _ChannelChatScreenState extends State { } } + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (!identical(route, _route)) { + _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); + _route = route; + route?.secondaryAnimation?.addStatusListener(_onCoveringRouteStatus); + } + } + + /// Reloads communities when a route pushed on top of this one is popped, + /// so a community joined or created elsewhere gets its badge and type here. + void _onCoveringRouteStatus(AnimationStatus status) { + if (status == AnimationStatus.dismissed && mounted) { + _loadCommunities(); + } + } + @override void dispose() { + _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); + _watchedImageStore?.removeListener(_onImageStoreChanged); _connector?.setActiveChannel(null); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); @@ -218,6 +241,8 @@ class _ChannelChatScreenState extends State { _replyingToMessage = message; _useReplyRegion = message.region?.isNotEmpty ?? false; }); + // Replying means typing next: open the keyboard on the composer. + _textFieldFocusNode.requestFocus(); } void _cancelReply() { @@ -288,14 +313,14 @@ class _ChannelChatScreenState extends State { width: 12, height: 12, decoration: BoxDecoration( - color: Colors.purple, + color: MeshPalette.magenta, shape: BoxShape.circle, border: Border.all( color: Theme.of(context).cardColor, width: 2, ), ), - child: const Icon(Icons.people, size: 8, color: Colors.white), + child: const Icon(Icons.people, size: 8, color: MeshPalette.ink), ), ), ], @@ -439,9 +464,9 @@ class _ChannelChatScreenState extends State { child: Consumer( builder: (context, connector, child) { final messages = connector.getChannelMessages(widget.channel); - final imageRows = _receivedImageRows(context); + final layout = _transcriptLayoutFor(context, messages); - if (messages.isEmpty && imageRows.isEmpty) { + if (layout.length == 0) { return EmptyState( icon: widget.channel.isPublicChannel ? Icons.public @@ -460,40 +485,12 @@ class _ChannelChatScreenState extends State { final urlImagesEnabled = connector.isChannelUrlImagesEnabled( widget.channel.index, ); - // Images are not ChannelMessages: they arrive as GRP_DATA - // chunks and are owned by ReceivedImageStore, so the two - // sources are merged here in arrival (receivedAt) order and the list - // below indexes rows, not messages. - final rows = <_ChannelChatRow>[ - for (final message in messages) - _ChannelChatRow(message: message), - ...imageRows, - ]..sort((a, b) => a.receivedAt.compareTo(b.receivedAt)); - - // Reverse rows so newest appear at bottom with reverse: true - final reversedRows = rows.reversed.toList(); - final itemCount = - reversedRows.length + (_isLoadingOlder ? 1 : 0); - - // Prune stale keys (deleted/cleared messages) to avoid - // unbounded growth. - final liveIds = reversedRows.map((r) => r.id).toSet(); - _messageKeys.removeWhere((id, _) => !liveIds.contains(id)); - - // Two messages can collide on messageId (same ms + name/text - // hash). Only the first occurrence owns the shared GlobalKey - // used for scroll-to-message; duplicates get a local key so - // no two widgets share one GlobalKey. - final seenIds = {}; - final keyedIndices = {}; - for (var i = 0; i < reversedRows.length; i++) { - if (seenIds.add(reversedRows[i].id)) { - keyedIndices.add(i); - } - } + final rowCount = layout.length; + final itemCount = rowCount + (_isLoadingOlder ? 1 : 0); // Auto-scroll to bottom if user is already at bottom WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; if (_channelSkipNextBottomSnap) { _channelSkipNextBottomSnap = false; return; @@ -525,9 +522,9 @@ class _ChannelChatScreenState extends State { ), ); } - final row = reversedRows[index]; + final row = layout.rowAt(index, messages); final GlobalKey messageKey; - if (keyedIndices.contains(index)) { + if (layout.keyedIndices.contains(index)) { messageKey = _messageKeys.putIfAbsent( row.id, GlobalKey.new, @@ -558,9 +555,11 @@ class _ChannelChatScreenState extends State { textScale, ); final startsDay = - index == reversedRows.length - 1 || + index == rowCount - 1 || !isSameChatDay( - reversedRows[index + 1].receivedAt, + layout + .rowAt(index + 1, messages) + .receivedAt, row.receivedAt, ); if (isUnreadAnchor || startsDay) { @@ -641,15 +640,9 @@ class _ChannelChatScreenState extends State { message.pathLength, ); - // Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk. - final bubbleColor = isOutgoing - ? MeshPalette.me - : scheme.surfaceContainerLow; - final bubbleBorder = isOutgoing - ? MeshPalette.meBorder - : scheme.outlineVariant; - final textColor = isOutgoing ? MeshPalette.meInk : scheme.onSurface; - final metaColor = textColor.withValues(alpha: 0.65); + final colors = MessageBubbleColors.of(scheme, isOutgoing: isOutgoing); + final textColor = colors.text; + final metaColor = colors.meta; const bodyFontSize = 14.0; Widget buildTextContent() { @@ -679,21 +672,6 @@ class _ChannelChatScreenState extends State { ); } - // Asymmetric radius matching chat_screen bubbles. - final borderRadius = isOutgoing - ? const BorderRadius.only( - topLeft: Radius.circular(MeshRadii.lg), - topRight: Radius.circular(MeshRadii.lg), - bottomLeft: Radius.circular(MeshRadii.lg), - bottomRight: Radius.circular(MeshRadii.xs), - ) - : const BorderRadius.only( - topLeft: Radius.circular(MeshRadii.xs), - topRight: Radius.circular(MeshRadii.lg), - bottomLeft: Radius.circular(MeshRadii.lg), - bottomRight: Radius.circular(MeshRadii.lg), - ); - const maxSwipeOffset = 64.0; const replySwipeThreshold = 64.0; final messageBody = LayoutBuilder( @@ -718,21 +696,10 @@ class _ChannelChatScreenState extends State { onSecondaryTapUp: PlatformInfo.isDesktop ? (_) => _showMessageActions(message) : null, - child: Container( - padding: gifId != null - ? const EdgeInsets.all(4) - : const EdgeInsets.symmetric( - horizontal: 12, - vertical: 8, - ), - constraints: BoxConstraints( - maxWidth: constraints.maxWidth * 0.72, - ), - decoration: BoxDecoration( - color: bubbleColor, - borderRadius: borderRadius, - border: Border.all(color: bubbleBorder, width: 1), - ), + child: MessageBubbleFrame( + isOutgoing: isOutgoing, + compact: gifId != null, + maxWidth: constraints.maxWidth, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -849,7 +816,7 @@ class _ChannelChatScreenState extends State { context.l10n.urlImage_possible, style: TextStyle( color: metaColor, - fontSize: 11 * textScale, + fontSize: 12 * textScale, ), ), ), @@ -895,7 +862,7 @@ class _ChannelChatScreenState extends State { child: Text( _displayRegion(message.region!), style: MeshTheme.mono( - fontSize: 8.5 * textScale, + fontSize: 12 * textScale, color: metaColor, ), ), @@ -916,7 +883,7 @@ class _ChannelChatScreenState extends State { maxLines: 2, overflow: TextOverflow.ellipsis, style: MeshTheme.mono( - fontSize: 9.5 * textScale, + fontSize: 12 * textScale, color: metaColor, ), ), @@ -955,7 +922,7 @@ class _ChannelChatScreenState extends State { const SizedBox(width: 6), Icon( Icons.repeat, - size: 11 * textScale, + size: 14 * textScale, color: metaColor, ), const SizedBox(width: 2), @@ -1003,7 +970,10 @@ class _ChannelChatScreenState extends State { const SizedBox(height: 4), Padding( padding: EdgeInsets.only(left: isOutgoing ? 0 : 42), - child: _buildReactionsDisplay(message), + child: ReactionChips( + reactions: message.reactions, + onTap: (_) => _showReactionsReport(message), + ), ), ], ], @@ -1067,50 +1037,67 @@ class _ChannelChatScreenState extends State { ); } - Widget _buildReplyPreview(ChannelMessage message, double textScale) { - final connector = context.read(); - final isOwnNode = message.replyToSenderName == connector.selfName; - final replyText = message.replyToText ?? ''; + /// Decoded preview of quoted text: a GIF thumbnail, a location label, or + /// the text itself — never the raw `g:`/marker payload. Shared by the reply + /// quote inside bubbles and the "Replying to" banner above the composer. + Widget _buildReplyContent( + String replyText, + double textScale, { + required Color color, + int maxLines = 2, + double gifSize = 80, + }) { final colorScheme = Theme.of(context).colorScheme; - final previewTextColor = colorScheme.onSurface.withValues(alpha: 0.7); - final gifId = GifHelper.parseGif(replyText); final poi = parseMarkerText(replyText); - - Widget contentPreview; if (gifId != null) { - contentPreview = ClipRRect( + return ClipRRect( borderRadius: BorderRadius.circular(4), child: GifMessage( url: 'https://media.giphy.com/media/$gifId/giphy.gif', backgroundColor: colorScheme.surfaceContainerHighest, - fallbackTextColor: previewTextColor, - maxSize: 80, - ), - ); - } else if (poi != null) { - contentPreview = Row( - children: [ - Icon(Icons.location_on_outlined, size: 14, color: previewTextColor), - const SizedBox(width: 4), - Text( - context.l10n.chat_location, - style: TextStyle(fontSize: 12 * textScale, color: previewTextColor), - ), - ], - ); - } else { - contentPreview = Text( - replyText, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12 * textScale, - color: previewTextColor, - fontStyle: FontStyle.italic, + fallbackTextColor: color, + maxSize: gifSize, ), ); } + if (poi != null) { + return Row( + children: [ + Icon(Icons.location_on_outlined, size: 16, color: color), + const SizedBox(width: 4), + Flexible( + child: Text( + context.l10n.chat_location, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12 * textScale, color: color), + ), + ), + ], + ); + } + return Text( + replyText, + maxLines: maxLines, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12 * textScale, + color: color, + fontStyle: FontStyle.italic, + ), + ); + } + + Widget _buildReplyPreview(ChannelMessage message, double textScale) { + final connector = context.read(); + final isOwnNode = message.replyToSenderName == connector.selfName; + final colorScheme = Theme.of(context).colorScheme; + final contentPreview = _buildReplyContent( + message.replyToText ?? '', + textScale, + color: colorScheme.onSurface.withValues(alpha: 0.7), + ); return GestureDetector( onTap: () => _scrollToMessage(message.replyToMessageId!), @@ -1129,7 +1116,7 @@ class _ChannelChatScreenState extends State { Text( context.l10n.chat_replyTo(message.replyToSenderName ?? ''), style: TextStyle( - fontSize: 11 * textScale, + fontSize: 12 * textScale, fontWeight: FontWeight.bold, color: isOwnNode ? colorScheme.primary : colorScheme.onSurface, ), @@ -1142,54 +1129,6 @@ class _ChannelChatScreenState extends State { ); } - Widget _buildReactionsDisplay(ChannelMessage message) { - final scheme = Theme.of(context).colorScheme; - return Wrap( - spacing: 6, - runSpacing: 6, - children: message.reactions.entries.map((entry) { - final emoji = entry.key; - final int count = entry.value.length; - - return Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: scheme.surfaceContainerHigh, - borderRadius: BorderRadius.circular(MeshRadii.pill), - border: Border.all(color: scheme.outlineVariant, width: 1), - ), - child: InkWell( - onTap: () => _showReactionsReport(message), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - emoji, - style: MeshTheme.emoji(fontSize: 16), - textHeightBehavior: const TextHeightBehavior( - applyHeightToFirstAscent: false, - applyHeightToLastDescent: false, - ), - ), - if (count > 1) ...[ - const SizedBox(width: 4), - Text( - '$count', - style: MeshTheme.mono( - fontSize: 11, - fontWeight: FontWeight.w700, - color: scheme.onSurface, - ), - ), - ], - ], - ), - ), - ); - }).toList(), - ); - } - void _showReactionsReport(ChannelMessage message) { final scheme = Theme.of(context).colorScheme; showDialog( @@ -1235,7 +1174,12 @@ class _ChannelChatScreenState extends State { ), ), const SizedBox(width: 12), - Expanded(child: Text(reaction.senderName ?? '???')), + Expanded( + child: Text( + reaction.senderName ?? + context.l10n.reaction_unknownSender, + ), + ), ], ), ), @@ -1388,8 +1332,9 @@ class _ChannelChatScreenState extends State { } on Exception catch (e) { debugPrint('image pick failed: $e'); if (!mounted) return; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(context.l10n.chat_imagePickFailed)), + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_imagePickFailed), ); return; } @@ -1405,8 +1350,9 @@ class _ChannelChatScreenState extends State { } on Exception catch (e) { debugPrint('image read failed: $e'); if (!mounted) return; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(context.l10n.chat_imagePickFailed)), + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_imagePickFailed), ); return; } @@ -1437,19 +1383,20 @@ class _ChannelChatScreenState extends State { ImageSendPreviewResult result, { required Uint8List sourceBytes, }) async { - final messenger = ScaffoldMessenger.of(context); final l10n = context.l10n; if (!connector.supportsChannelData) { - messenger.showSnackBar( - SnackBar(content: Text(l10n.imageSend_deviceUnsupported)), + showDismissibleSnackBar( + context, + content: Text(l10n.imageSend_deviceUnsupported), ); return; } final senderPrefix = connector.imageSenderPrefix; if (senderPrefix == null) { - messenger.showSnackBar( - SnackBar(content: Text(l10n.imageSend_deviceUnsupported)), + showDismissibleSnackBar( + context, + content: Text(l10n.imageSend_deviceUnsupported), ); return; } @@ -1472,9 +1419,11 @@ class _ChannelChatScreenState extends State { parity: result.includeParity, ); } on ArgumentError { - messenger.showSnackBar(SnackBar(content: Text(l10n.imageSend_tooLarge))); + if (!mounted) return; + showDismissibleSnackBar(context, content: Text(l10n.imageSend_tooLarge)); return; } + if (!mounted) return; // Pace on the measured per-packet airtime when the radio parameters are // known; fall back to the base gap when they are not, rather than @@ -1513,19 +1462,19 @@ class _ChannelChatScreenState extends State { ); } if (!mounted) return; - messenger.showSnackBar( - SnackBar( - content: Text( - sent - ? l10n.imageSend_sentConfirmation(chunkSet.blobs.length) - : l10n.imageSend_deviceUnsupported, - ), + showDismissibleSnackBar( + context, + content: Text( + sent + ? l10n.imageSend_sentConfirmation(chunkSet.blobs.length) + : l10n.imageSend_deviceUnsupported, ), ); } on Exception catch (error) { if (!mounted) return; - messenger.showSnackBar( - SnackBar(content: Text(l10n.imageSend_sendFailed('$error'))), + showDismissibleSnackBar( + context, + content: Text(l10n.imageSend_sendFailed('$error')), ); } finally { if (mounted) { @@ -1645,26 +1594,60 @@ class _ChannelChatScreenState extends State { } } - /// Received/sent AEIC images for this channel, as transcript rows. + /// The merged, ordered transcript (messages + AEIC images), memoised. /// - /// Returns nothing when [ReceivedImageStore] is not registered, so a screen - /// test without the provider still renders. - /// [context] must be the context of the element currently building (the - /// `Consumer` builder's, not the `State`'s) — `watch` asserts on that. - List<_ChannelChatRow> _receivedImageRows(BuildContext context) { - final ReceivedImageStore store; + /// Sorting the whole transcript and rebuilding the key bookkeeping on every + /// connector notification is wasted work when this channel did not change + /// (most notifications are about other chats, contacts or radio state), so + /// the layout is only recomputed when the message list's identity, length or + /// ends change, or the image store notified. + /// + /// Returns no images when [ReceivedImageStore] is not registered, so a screen + /// test without the provider still renders. [context] must be the context + /// of the element currently building (the `Consumer` builder's, not the + /// `State`'s) — `watch` asserts on that. + _TranscriptLayout _transcriptLayoutFor( + BuildContext context, + List messages, + ) { + ReceivedImageStore? store; try { store = context.watch(); } on ProviderNotFoundException { - return const <_ChannelChatRow>[]; + store = null; } - return <_ChannelChatRow>[ - for (final entry in store.entries) - if (entry.channelIndex == widget.channel.index) - _ChannelChatRow(image: entry), - ]; + if (!identical(store, _watchedImageStore)) { + _watchedImageStore?.removeListener(_onImageStoreChanged); + _watchedImageStore = store; + store?.addListener(_onImageStoreChanged); + _imageStoreVersion++; + } + final cached = _transcriptLayout; + if (cached != null && + cached.matches(messages, _imageStoreVersion, widget.channel.index)) { + return cached; + } + final images = store == null + ? const [] + : [ + for (final entry in store.entries) + if (entry.channelIndex == widget.channel.index) entry, + ]; + final layout = _TranscriptLayout.build( + messages: messages, + images: images, + imageVersion: _imageStoreVersion, + channelIndex: widget.channel.index, + ); + // Prune stale keys (deleted/cleared messages) to avoid unbounded growth. + final liveIds = layout.ids.toSet(); + _messageKeys.removeWhere((id, _) => !liveIds.contains(id)); + _transcriptLayout = layout; + return layout; } + void _onImageStoreChanged() => _imageStoreVersion++; + /// Bubble for one AEIC image, following the GIF-message precedent: minimal /// chrome, the renderer owns every state (receiving / decoding / failed) and /// the mandatory AI-reconstruction label. @@ -1901,18 +1884,6 @@ class _ChannelChatScreenState extends State { return context.l10n.receivedImage_senderPrefix(hex); } - void _showGifPicker(BuildContext context) { - showModalBottomSheet( - context: context, - isScrollControlled: true, - builder: (context) => GifPicker( - onGifSelected: (gifId) { - _textController.text = GifHelper.encodeGif(gifId); - }, - ), - ); - } - Widget _buildAvatar(String senderName, double textScale) { return AvatarCircle( name: senderName, @@ -1944,19 +1915,17 @@ class _ChannelChatScreenState extends State { Text( context.l10n.chat_replyingTo(message.senderName), style: MeshTheme.mono( - fontSize: 11 * textScale, + fontSize: 12 * textScale, fontWeight: FontWeight.w700, color: scheme.primary, ), ), - Text( + _buildReplyContent( message.text, + textScale, + color: scheme.onSurfaceVariant, maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 11 * textScale, - color: scheme.onSurfaceVariant, - ), + gifSize: 48, ), ], ), @@ -1982,7 +1951,7 @@ class _ChannelChatScreenState extends State { context.l10n.channels_regionSetTo(replyRegion!), style: MeshTheme.mono( - fontSize: 10 * textScale, + fontSize: 12 * textScale, color: _useReplyRegion ? scheme.onPrimaryContainer : scheme.onSurfaceVariant, @@ -2038,351 +2007,112 @@ class _ChannelChatScreenState extends State { ); } + /// The `@[name] ` prefix a reply prepends to the outgoing text. + static String _replyPrefix(ChannelMessage replyTo) => + '@[${replyTo.senderName}] '; + Widget _buildInputBar() { - final connector = context.watch(); - final maxBytes = maxChannelMessageBytes(connector.selfName); - final settings = context.watch().settings; - final showImageAction = settings.imageMessagesEnabled; - final scheme = Theme.of(context).colorScheme; - return Container( - decoration: BoxDecoration( - color: scheme.surface, - border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), - ), - child: SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_replyingToMessage != null) - Builder( - builder: (context) { - final textScale = context - .select( - (service) => service.scale, - ); - return _buildReplyBanner(textScale); - }, - ), - if (_imageSendTotal > 0) _buildImageSendProgress(scheme), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - 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), - ], - ), - ), - ); - } - final selfConnector = context - .read(); - if (hasShareableLocation( - selfConnector.selfLatitude, - selfConnector.selfLongitude, - )) { - items.add( - PopupMenuItem( - value: 'send-my-location', - child: Row( - children: [ - const Icon(Icons.my_location), - const SizedBox(width: 12), - Text(context.l10n.chat_shareMyLocation), - ], - ), - ), - ); - } - - final menuHeight = - items.length * 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: 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': - await _shareMyLocation( - context.read(), - ); - break; - } - }, - ); - }, - ), - if (settings.translationEnabled) - MessageTranslationButton( - enabled: settings.composerTranslationEnabled, - languageCode: settings.translationTargetLanguageCode, - onPressed: _showTranslationOptions, - ), - Expanded( - child: ValueListenableBuilder( - valueListenable: _textController, - builder: (context, value, child) { - final gifId = GifHelper.parseGif(value.text); - if (gifId != null) { - return Focus( - autofocus: true, - onKeyEvent: (node, event) { - if (event is KeyDownEvent && - (event.logicalKey == - LogicalKeyboardKey.enter || - event.logicalKey == - LogicalKeyboardKey.numpadEnter)) { - _sendMessage(); - return KeyEventResult.handled; - } - return KeyEventResult.ignored; - }, - child: Row( - children: [ - Expanded( - child: ClipRRect( - borderRadius: BorderRadius.circular(12), - child: GifMessage( - url: - 'https://media.giphy.com/media/$gifId/giphy.gif', - backgroundColor: - scheme.surfaceContainerHighest, - fallbackTextColor: scheme.onSurface - .withValues(alpha: 0.6), - maxSize: 160, - ), - ), - ), - const SizedBox(width: 8), - IconButton( - icon: const Icon(Icons.close), - tooltip: context.l10n.chat_removeGif, - onPressed: () { - _textController.clear(); - _textFieldFocusNode.requestFocus(); - }, - ), - ], - ), - ); - } - return ByteCountedTextField( - maxBytes: maxBytes, - controller: _textController, - focusNode: _textFieldFocusNode, - hintText: context.l10n.chat_typeMessage, - onSubmitted: (_) => _sendMessage(), - encoder: - (connector.isChannelSmazEnabled( - widget.channel.index, - ) || - connector.isChannelCyr2LatEnabled( - widget.channel.index, - )) - ? (text) => connector.prepareChannelOutboundText( - widget.channel.index, - text, - ) - : null, - decoration: InputDecoration( - hintText: context.l10n.chat_typeMessage, - 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, - ), - ), - ); - }, - ), - ), - const SizedBox(width: 6), - ValueListenableBuilder( - valueListenable: _textController, - builder: (context, value, _) { - final hasText = value.text.trim().isNotEmpty; - return AnimatedContainer( - duration: const Duration(milliseconds: 180), - curve: Curves.easeInOut, - child: IconButton.filled( - icon: const Icon(Icons.send, size: 20), - tooltip: context.l10n.chat_sendMessage, - style: IconButton.styleFrom( - backgroundColor: hasText - ? scheme.primary - : scheme.surfaceContainerHighest, - foregroundColor: hasText - ? scheme.onPrimary - : scheme.onSurfaceVariant, - minimumSize: const Size(40, 40), - shape: const CircleBorder(), - ), - onPressed: hasText - ? () { - HapticFeedback.lightImpact(); - _sendMessage(); - } - : null, - ), - ); - }, - ), - ], - ), - ), - ], - ), - ), + // Only the fields the composer depends on, so unrelated connector + // notifications (adverts, other chats, radio stats) don't rebuild it. + final (selfName, useEncoder) = context + .select( + (c) => ( + c.selfName, + c.isChannelSmazEnabled(widget.channel.index) || + c.isChannelCyr2LatEnabled(widget.channel.index), + ), + ); + final showImageAction = context.select( + (s) => s.settings.imageMessagesEnabled, ); - } - - Future _showTranslationOptions() async { - final settingsService = context.read(); - final settings = settingsService.settings; - await showMessageTranslationSheet( - context: context, - enabled: settings.composerTranslationEnabled, - selectedLanguageCode: settings.translationTargetLanguageCode, - onEnabledChanged: settingsService.setComposerTranslationEnabled, - onLanguageSelected: settingsService.setTranslationTargetLanguageCode, + final replyTo = _replyingToMessage; + // A reply's prefix is sent too, so it counts against the limit. + final replyPrefixBytes = replyTo == null + ? 0 + : utf8.encode(_replyPrefix(replyTo)).length; + final maxBytes = math.max( + 0, + maxChannelMessageBytes(selfName) - replyPrefixBytes, + ); + final scheme = Theme.of(context).colorScheme; + return ChatComposer( + controller: _textController, + focusNode: _textFieldFocusNode, + maxBytes: maxBytes, + encoder: useEncoder + ? (text) => context + .read() + .prepareChannelOutboundText(widget.channel.index, text) + : null, + onSend: _sendMessage, + sendTooltip: context.l10n.chat_sendMessage, + header: [ + if (replyTo != null) + Builder( + builder: (context) { + final textScale = context.select( + (service) => service.scale, + ); + return _buildReplyBanner(textScale); + }, + ), + if (_imageSendTotal > 0) _buildImageSendProgress(scheme), + ], + actionsBuilder: () { + final connector = context.read(); + return [ + ChatComposerAction( + id: 'gif', + icon: Icons.gif_box, + label: context.l10n.chat_sendGif, + ), + if (showImageAction) + ChatComposerAction( + id: 'meshcore-image', + icon: Icons.image_outlined, + label: context.l10n.chat_sendImageLora, + ), + if (hasShareableLocation( + connector.selfLatitude, + connector.selfLongitude, + )) + ChatComposerAction( + id: 'send-my-location', + icon: Icons.my_location, + label: context.l10n.chat_shareMyLocation, + ), + ]; + }, + onAction: (action) { + if (!mounted) return; + switch (action) { + case 'gif': + showChatGifPicker(context, _textController); + case 'meshcore-image': + _showImageSendPreview(); + case 'send-my-location': + _shareMyLocation(context.read()); + } + }, ); } /// Shares the radio's own position as a map marker on this channel. It is /// not a reply, so any reply in progress stays open for the next message; /// it shares the text send guard and cooldown. - Future _shareMyLocation(MeshCoreConnector connector) async { - final lat = connector.selfLatitude; - final lon = connector.selfLongitude; - if (!hasShareableLocation(lat, lon)) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_noRadioLocation), - ); - return; - } - final selfName = connector.selfName; - final label = await showMarkerLabelDialog( - context, - lat: lat!, - lon: lon!, - defaultLabel: selfName != null && selfName.isNotEmpty - ? selfName - : context.l10n.map_sharedPin, - flags: 'poi', - confirmText: context.l10n.common_share, + Future _shareMyLocation(MeshCoreConnector connector) { + return shareMyLocationMarker( + context: context, + connector: connector, + guard: _sendGuard, + logTag: 'ChannelChat', + send: (markerText) => + connector.sendChannelMessage(widget.channel, markerText), ); - if (label == null || label.isEmpty || !mounted || _isSendingText) return; - final now = DateTime.now(); - if (_lastChannelSendAt != null && - now.difference(_lastChannelSendAt!) < const Duration(seconds: 1)) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_sendCooldown), - ); - return; - } - _lastChannelSendAt = now; - _isSendingText = true; - try { - await connector.sendChannelMessage( - widget.channel, - formatMarkerText(lat, lon, label, 'poi'), - ); - } catch (e) { - // A failed send (e.g. region scope rejected) is already marked failed - // on the message itself. - appLogger.warn('Sharing location failed: $e', tag: 'ChannelChat'); - } finally { - _isSendingText = false; - } } - Future _sendMessage() async { - if (_isSendingText) return; - _isSendingText = true; - try { - await _sendMessageInner(); - } finally { - _isSendingText = false; - } + Future _sendMessage() { + return _sendGuard.runExclusive(_sendMessageInner); } Future _sendMessageInner() async { @@ -2393,50 +2123,15 @@ class _ChannelChatScreenState extends State { final replyTo = _replyingToMessage; final replyRegion = _useReplyRegion ? replyTo?.region : null; - final now = DateTime.now(); - if (_lastChannelSendAt != null && - now.difference(_lastChannelSendAt!) < const Duration(seconds: 1)) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_sendCooldown), - ); - return; - } - _lastChannelSendAt = now; + if (!_sendGuard.checkCooldown(context)) return; final connector = context.read(); - final settings = context.read().settings; - final translationService = context.read(); + final translation = await translateOutgoingText(context, text); + if (translation == null || !mounted) return; - String messageText = text; - String? originalText; - String? translatedLanguageCode; - String? translationModelId; - if (settings.translationEnabled) { - final targetLanguageCode = translationService.resolvedTargetLanguageCode( - Localizations.localeOf(context).languageCode, - ); - if (translationService.shouldTranslateOutgoing( - text: text, - targetLanguageCode: targetLanguageCode, - )) { - final result = await translationService.translateOutgoingText( - text: text, - targetLanguageCode: targetLanguageCode, - ); - if (!mounted) return; - if (result != null && - result.status == MessageTranslationStatus.completed && - result.translatedText.isNotEmpty) { - messageText = result.translatedText; - originalText = text; - translatedLanguageCode = result.targetLanguageCode; - translationModelId = result.modelId; - } - } - } + String messageText = translation.text; if (replyTo != null) { - messageText = '@[${replyTo.senderName}] $messageText'; + messageText = '${_replyPrefix(replyTo)}$messageText'; } final maxBytes = maxChannelMessageBytes(connector.selfName); @@ -2472,12 +2167,14 @@ class _ChannelChatScreenState extends State { connector.sendChannelMessage( widget.channel, messageText, - originalText: originalText, - translatedLanguageCode: translatedLanguageCode, - translationModelId: translationModelId, + originalText: translation.originalText, + translatedLanguageCode: translation.languageCode, + translationModelId: translation.modelId, region: replyRegion, replyTo: replyTo, ); + // Only a dispatched send starts the cooldown. + _sendGuard.markDispatched(); } void _showMessagePathInfo(ChannelMessage message) { @@ -2562,7 +2259,7 @@ class _ChannelChatScreenState extends State { title: Text(context.l10n.common_copy), onTap: () { Navigator.pop(sheetContext); - _copyMessageText(message.text); + copyChatMessageText(context, message.text); }, ), if (canTranslateMessage) @@ -2632,38 +2329,12 @@ class _ChannelChatScreenState extends State { connector.sendChannelMessage(widget.channel, reactionText); } - 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), - ); - } - Future _confirmClearChat() async { - final confirmed = await showDialog( - context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.contact_clearChat), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext, false), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () => Navigator.pop(dialogContext, true), - style: TextButton.styleFrom( - foregroundColor: Theme.of(context).colorScheme.error, - ), - child: Text(context.l10n.common_delete), - ), - ], - ), + final confirmed = await confirmClearChat( + context, + message: context.l10n.channels_clearChatConfirm, ); - if (confirmed == true) { + if (confirmed) { if (!mounted) return; context.read().clearMessagesForChannel( widget.channel.index, @@ -3080,6 +2751,108 @@ class _ChannelChatRow { String get id => message?.messageId ?? 'aeic:${image!.streamId}'; } +/// Memoised ordering of a channel transcript, newest first. +/// +/// Rows hold positions, not message objects: the connector replaces messages +/// in place (status, repeats, reactions) without changing their order or id, +/// so [rowAt] always reads the current object from the live list. +class _TranscriptLayout { + final List _source; + final int _sourceLength; + final String? _firstId; + final String? _lastId; + final int _imageVersion; + final int _channelIndex; + + /// Newest first. `>= 0` is a message index; `< 0` is image `-(i + 1)`. + final List _order; + final List _images; + + /// Row ids, aligned with [_order]. + final List ids; + + /// Two messages can collide on messageId (same ms + name/text hash). Only + /// the first occurrence owns the shared GlobalKey used for + /// scroll-to-message; duplicates get a local key so no two widgets share + /// one GlobalKey. + final Set keyedIndices; + + _TranscriptLayout._( + this._source, + this._sourceLength, + this._firstId, + this._lastId, + this._imageVersion, + this._channelIndex, + this._order, + this._images, + this.ids, + this.keyedIndices, + ); + + factory _TranscriptLayout.build({ + required List messages, + required List images, + required int imageVersion, + required int channelIndex, + }) { + DateTime timeOf(int code) => + code >= 0 ? messages[code].receivedAt : images[-code - 1].firstSeen; + // Images are not ChannelMessages: they arrive as GRP_DATA chunks and are + // owned by ReceivedImageStore, so the two sources are merged here in + // arrival (receivedAt) order and the list indexes rows, not messages. + final order = [ + for (var i = 0; i < messages.length; i++) i, + for (var i = 0; i < images.length; i++) -(i + 1), + ]; + // Stable ascending sort, then reversed so newest appear at the bottom of + // the reversed ListView. + mergeSort(order, compare: (a, b) => timeOf(a).compareTo(timeOf(b))); + final reversed = order.reversed.toList(growable: false); + final ids = [ + for (final code in reversed) + code >= 0 + ? messages[code].messageId + : 'aeic:${images[-code - 1].streamId}', + ]; + final seen = {}; + final keyed = {}; + for (var i = 0; i < ids.length; i++) { + if (seen.add(ids[i])) keyed.add(i); + } + return _TranscriptLayout._( + messages, + messages.length, + messages.isEmpty ? null : messages.first.messageId, + messages.isEmpty ? null : messages.last.messageId, + imageVersion, + channelIndex, + reversed, + images, + ids, + keyed, + ); + } + + int get length => _order.length; + + bool matches(List messages, int imageVersion, int channel) { + return identical(messages, _source) && + messages.length == _sourceLength && + imageVersion == _imageVersion && + channel == _channelIndex && + (messages.isEmpty ? null : messages.first.messageId) == _firstId && + (messages.isEmpty ? null : messages.last.messageId) == _lastId; + } + + _ChannelChatRow rowAt(int index, List messages) { + final code = _order[index]; + return code >= 0 + ? _ChannelChatRow(message: messages[code]) + : _ChannelChatRow(image: _images[-code - 1]); + } +} + /// [ReceivedImageStrings] built from the app's localizations. /// /// The R6 badge and caption are deliberately absent from this class — they are diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index 44242745..092e296a 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -22,6 +22,7 @@ import '../models/path_playback.dart'; import '../theme/mesh_theme.dart'; import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/path_map_scaffold.dart'; import '../widgets/path_map_ui.dart'; class ChannelMessagePathScreen extends StatelessWidget { @@ -54,7 +55,8 @@ class ChannelMessagePathScreen extends StatelessWidget { ); final hops = _buildPathHops( primaryPath, - connector, + connector.allContacts, + plausibleSelfPoint(connector), l10n, hashByteWidth, resolveFromEnd: !message.isOutgoing, @@ -188,7 +190,7 @@ class ChannelMessagePathScreen extends StatelessWidget { _buildDetailRow( context, l10n.channelPath_timeLabel, - _formatTime(message.timestamp, l10n), + _formatTime(context, message.timestamp), scheme: scheme, ), if (message.repeatCount > 0) @@ -264,7 +266,7 @@ class ChannelMessagePathScreen extends StatelessWidget { Text( _formatPathPrefixes(variants[i], hashByteWidth), style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), @@ -358,8 +360,8 @@ class ChannelMessagePathScreen extends StatelessWidget { right: -4, top: -4, child: Container( - width: 18, - height: 18, + width: 22, + height: 22, decoration: BoxDecoration( color: MeshPalette.blueDim, shape: BoxShape.circle, @@ -369,12 +371,15 @@ class ChannelMessagePathScreen extends StatelessWidget { ), ), alignment: Alignment.center, - child: Text( - hop.index.toString(), - style: const TextStyle( - color: Colors.white, - fontSize: 9, - fontWeight: FontWeight.w700, + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + hop.index.toString(), + style: const TextStyle( + color: MeshPalette.ink, + fontSize: 12, + fontWeight: FontWeight.w700, + ), ), ), ), @@ -411,7 +416,7 @@ class ChannelMessagePathScreen extends StatelessWidget { Text( hexPrefix, style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: scheme.onSurfaceVariant, ), ), @@ -419,7 +424,7 @@ class ChannelMessagePathScreen extends StatelessWidget { Text( locationText, style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: scheme.onSurfaceVariant, ), ), @@ -432,18 +437,16 @@ class ChannelMessagePathScreen extends StatelessWidget { ); } - String _formatTime(DateTime time, AppLocalizations l10n) { - final now = DateTime.now(); - final diff = now.difference(time); - - if (diff.inDays > 0) { - final timeLabel = - '${time.hour}:${time.minute.toString().padLeft(2, '0')}'; - return l10n.channelPath_timeWithDate(time.day, time.month, timeLabel); - } - return l10n.channelPath_timeOnly( - '${time.hour}:${time.minute.toString().padLeft(2, '0')}', + String _formatTime(BuildContext context, DateTime time) { + final localizations = MaterialLocalizations.of(context); + final timeLabel = localizations.formatTimeOfDay( + TimeOfDay.fromDateTime(time), + alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), ); + if (DateTime.now().difference(time).inDays > 0) { + return '${localizations.formatShortMonthDay(time)} $timeLabel'; + } + return context.l10n.channelPath_timeOnly(timeLabel); } String _formatPathLabel(int? hopCount, AppLocalizations l10n) { @@ -536,13 +539,10 @@ class ChannelMessagePathMapScreen extends StatefulWidget { class _ChannelMessagePathMapScreenState extends State with SingleTickerProviderStateMixin { - static const double _labelZoomThreshold = 8.5; - static const double _mapMinZoom = 2.0; - static const double _mapMaxZoom = 18.0; + static const double _labelZoomThreshold = kPathMapLabelZoomThreshold; final MapController _mapController = MapController(); Uint8List? _selectedPath; - double _pathDistance = 0.0; bool _showNodeLabels = true; bool _didReceivePositionUpdate = false; int? _focusedHopIndex; @@ -555,6 +555,13 @@ class _ChannelMessagePathMapScreenState bool _animationEnabled = true; bool _followPacket = false; + // Resolved paths, reused across connector notifications until the inputs + // they depend on (selection, contacts, self position) change. + _PathMapModel? _model; + Object? _modelKey; + DisplayPath? _syncedDisplay; + bool _playbackSyncPending = false; + @override void initState() { super.initState(); @@ -565,14 +572,12 @@ class _ChannelMessagePathMapScreenState /// Keeps the camera centered on the packet while the follow lock is on. void _followPacketCamera() { - if (!_followPacket || - !_animationEnabled || - !_playback.started || - !_playback.hasPath || - !mounted) { - return; - } - _mapController.move(_playback.position, _mapController.camera.zoom); + if (!mounted) return; + followPacketCamera( + _mapController, + _playback, + enabled: _followPacket && _animationEnabled, + ); } void _toggleFollowPacket() { @@ -606,13 +611,10 @@ class _ChannelMessagePathMapScreenState DisplayPath? _buildDisplayPath({ required int index, required bool isPrimary, - required Uint8List orientedBytes, required List<_PathHop> hops, - required MeshCoreConnector connector, + required LatLng? selfPoint, }) { final l10n = context.l10n; - final selfLat = connector.selfLatitude; - final selfLon = connector.selfLongitude; final points = []; final labels = []; @@ -623,8 +625,8 @@ class _ChannelMessagePathMapScreenState var locatedHops = 0; void addSelf() { - if (selfLat == null || selfLon == null) return; - points.add(LatLng(selfLat, selfLon)); + if (selfPoint == null) return; + points.add(selfPoint); labels.add(l10n.pathTrace_you); confirmed.add(true); rowIdx.add(-1); @@ -685,24 +687,131 @@ class _ChannelMessagePathMapScreenState ); } - /// Updates the playback path after this frame, but only when the selected - /// path's geometry actually changed, so rebuilds don't reset a running - /// animation. + /// Returns the resolved paths for the current selection, recomputing them + /// (hop resolution, display paths, polyline) only when an input changed. + _PathMapModel _resolveModel(MeshCoreConnector connector) { + final l10n = context.l10n; + final width = (widget.message.pathHashWidth ?? connector.pathHashByteWidth) + .clamp(1, 4) + .toInt(); + final selfPoint = plausibleSelfPoint(connector); + final contacts = connector.allContacts; + final key = ( + widget.message, + widget.channelMessage, + _selectedPath?.join(','), + width, + contactListSignature(contacts), + selfPoint, + l10n.localeName, + ); + final cached = _model; + if (cached != null && key == _modelKey) return cached; + + final primaryPath = _selectPrimaryPath( + widget.message.pathBytes, + widget.message.pathVariants, + ); + final observedPaths = _buildObservedPaths( + primaryPath, + widget.message.pathVariants, + ); + final selectedPathTmp = _resolveSelectedPath( + _selectedPath, + observedPaths, + primaryPath, + ); + final selectedPath = _orientPath(selectedPathTmp, width); + + // Match on the unoriented bytes — observedPaths stores them as + // recorded, while selectedPath may be reversed for display. + final selectedIndex = _indexForPath(selectedPathTmp, observedPaths); + final resolveFromEnd = !widget.message.isOutgoing; + final hops = _buildPathHops( + selectedPath, + contacts, + selfPoint, + l10n, + width, + resolveFromEnd: resolveFromEnd, + ); + + // Renderable paths for the animation and combined view. + final entries = <_ObservedPathEntry>[]; + _ObservedPathEntry? selectedEntry; + for (var i = 0; i < observedPaths.length; i++) { + final pathHops = i == selectedIndex + ? hops + : _buildPathHops( + _orientPath(observedPaths[i].pathBytes, width), + contacts, + selfPoint, + l10n, + width, + resolveFromEnd: resolveFromEnd, + ); + final display = _buildDisplayPath( + index: i, + isPrimary: observedPaths[i].isPrimary, + hops: pathHops, + selfPoint: selfPoint, + ); + if (display == null) continue; + final entry = _ObservedPathEntry( + index: i, + observedBytes: observedPaths[i].pathBytes, + display: display, + hops: pathHops, + ); + entries.add(entry); + if (i == selectedIndex) selectedEntry = entry; + } + + // Self sits at the sending end for outgoing messages, the receiving end + // otherwise; it is omitted without a GPS fix. + final points = [ + if (widget.message.isOutgoing) ?selfPoint, + for (final hop in hops) + if (hop.hasLocation) hop.position!, + if (!widget.message.isOutgoing) ?selfPoint, + ]; + + final initialZoom = points.isNotEmpty ? 13.0 : 2.0; + final model = _PathMapModel( + observedPaths: observedPaths, + selectedIndex: selectedIndex, + width: width, + selectedPath: selectedPath, + hops: hops, + entries: entries, + selectedEntry: selectedEntry, + points: points, + polylines: points.length > 1 + ? [Polyline(points: points, strokeWidth: 4, color: MeshPalette.blue)] + : const [], + initialCenter: points.isNotEmpty ? points.first : const LatLng(0, 0), + initialZoom: initialZoom, + bounds: points.length > 1 ? LatLngBounds.fromPoints(points) : null, + pathDistance: getPathDistanceMeters(points), + hasSelfPoint: selfPoint != null, + ); + _model = model; + _modelKey = key; + return model; + } + + /// Updates the playback path after this frame when the selected path + /// changed. Geometry is compared before resetting, so rebuilds don't + /// restart a running animation. void _schedulePlaybackSync(DisplayPath? selected) { - final points = selected?.points ?? const []; + if (identical(selected, _syncedDisplay)) return; + _syncedDisplay = selected; + if (_playbackSyncPending) return; + _playbackSyncPending = true; WidgetsBinding.instance.addPostFrameCallback((_) { + _playbackSyncPending = false; if (!mounted) return; - if (points.length == _playback.points.length) { - var same = true; - for (var i = 0; i < points.length; i++) { - if (points[i] != _playback.points[i]) { - same = false; - break; - } - } - if (same) return; - } - _playback.setPath(points); + syncPlaybackPath(_playback, _syncedDisplay?.points ?? const []); }); } @@ -735,23 +844,6 @@ class _ChannelMessagePathMapScreenState }); } - bool _isDesktopPlatform(TargetPlatform platform) { - return platform == TargetPlatform.linux || - platform == TargetPlatform.windows || - platform == TargetPlatform.macOS; - } - - double _getPathDistance(List points) { - double totalDistance = 0.0; - final distanceCalculator = Distance(); - - for (int i = 0; i < points.length - 1; i++) { - totalDistance += distanceCalculator(points[i], points[i + 1]); - } - - return totalDistance; - } - void _focusHop(_PathHop hop) { if (!hop.hasLocation) return; final targetZoom = _didReceivePositionUpdate @@ -768,70 +860,6 @@ class _ChannelMessagePathMapScreenState }); } - void _zoomMapBy(double delta) { - final camera = _mapController.camera; - final nextZoom = (camera.zoom + delta) - .clamp(_mapMinZoom, _mapMaxZoom) - .toDouble(); - _mapController.move(camera.center, nextZoom); - } - - void _resetMapView({ - required LatLng initialCenter, - required double initialZoom, - required LatLngBounds? bounds, - }) { - if (bounds != null) { - _mapController.fitCamera( - CameraFit.bounds( - bounds: bounds, - padding: const EdgeInsets.all(64), - maxZoom: 16, - ), - ); - return; - } - _mapController.move(initialCenter, initialZoom); - } - - Widget _buildDesktopMapControls({ - required LatLng initialCenter, - required double initialZoom, - required LatLngBounds? bounds, - }) { - return Positioned( - left: 16, - top: 16, - child: Card( - elevation: 4, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - icon: const Icon(Icons.add), - tooltip: context.l10n.map_zoomIn, - onPressed: () => _zoomMapBy(1), - ), - IconButton( - icon: const Icon(Icons.remove), - tooltip: context.l10n.map_zoomOut, - onPressed: () => _zoomMapBy(-1), - ), - IconButton( - icon: const Icon(Icons.my_location), - tooltip: context.l10n.map_centerMap, - onPressed: () => _resetMapView( - initialCenter: initialCenter, - initialZoom: initialZoom, - bounds: bounds, - ), - ), - ], - ), - ), - ); - } - @override Widget build(BuildContext context) { return Consumer( @@ -840,79 +868,18 @@ class _ChannelMessagePathMapScreenState final isImperial = settings.unitSystem == UnitSystem.imperial; final tileCache = context.read(); final mapScheme = Theme.of(context).colorScheme; - final primaryPath = _selectPrimaryPath( - widget.message.pathBytes, - widget.message.pathVariants, - ); - final observedPaths = _buildObservedPaths( - primaryPath, - widget.message.pathVariants, - ); - final isDesktop = _isDesktopPlatform(defaultTargetPlatform); - final selectedPathTmp = _resolveSelectedPath( - _selectedPath, - observedPaths, - primaryPath, - ); + final model = _resolveModel(connector); + final observedPaths = model.observedPaths; + final selectedIndex = model.selectedIndex; + final width = model.width; + final hops = model.hops; + final entries = model.entries; + final points = model.points; - final width = - (widget.message.pathHashWidth ?? connector.pathHashByteWidth) - .clamp(1, 4) - .toInt(); - final selectedPath = _orientPath(selectedPathTmp, width); - - // Match on the unoriented bytes — observedPaths stores them as - // recorded, while selectedPath may be reversed for display. - final selectedIndex = _indexForPath(selectedPathTmp, observedPaths); - final hops = _buildPathHops( - selectedPath, - connector, - context.l10n, - width, - resolveFromEnd: !widget.message.isOutgoing, - ); - - // Renderable paths for the animation and combined view. - final entries = <_ObservedPathEntry>[]; - for (var i = 0; i < observedPaths.length; i++) { - final oriented = _orientPath(observedPaths[i].pathBytes, width); - final pathHops = i == selectedIndex - ? hops - : _buildPathHops( - oriented, - connector, - context.l10n, - width, - resolveFromEnd: !widget.message.isOutgoing, - ); - final display = _buildDisplayPath( - index: i, - isPrimary: observedPaths[i].isPrimary, - orientedBytes: oriented, - hops: pathHops, - connector: connector, - ); - if (display != null) { - entries.add( - _ObservedPathEntry( - index: i, - observedBytes: observedPaths[i].pathBytes, - display: display, - hops: pathHops, - ), - ); - } - } final effectiveMode = entries.length > 1 ? _viewMode : PathViewMode.single; - _ObservedPathEntry? selectedEntry; - for (final entry in entries) { - if (entry.index == selectedIndex) { - selectedEntry = entry; - break; - } - } + final selectedEntry = model.selectedEntry; final selectedDisplay = selectedEntry?.display; final visibleEntries = effectiveMode == PathViewMode.single ? [?selectedEntry] @@ -922,48 +889,12 @@ class _ChannelMessagePathMapScreenState final visibleDisplays = visibleEntries.map((e) => e.display).toList(); _schedulePlaybackSync(selectedDisplay); - final points = []; - - if ((widget.message.isOutgoing && !widget.channelMessage) || - (widget.message.isOutgoing && widget.channelMessage)) { - points.add(LatLng(connector.selfLatitude!, connector.selfLongitude!)); - } - - for (final hop in hops) { - if (hop.hasLocation) { - points.add(hop.position!); - } - } - - if ((!widget.message.isOutgoing && !widget.channelMessage) || - (!widget.message.isOutgoing && widget.channelMessage)) { - points.add(LatLng(connector.selfLatitude!, connector.selfLongitude!)); - } - - final polylines = points.length > 1 - ? [ - Polyline( - points: points, - strokeWidth: 4, - color: MeshPalette.blue, - ), - ] - : []; - - final initialCenter = points.isNotEmpty - ? points.first - : const LatLng(0, 0); - final initialZoom = points.isNotEmpty ? 13.0 : 2.0; if (!_didReceivePositionUpdate) { - _showNodeLabels = initialZoom >= _labelZoomThreshold; + _showNodeLabels = model.initialZoom >= _labelZoomThreshold; } - final bounds = points.length > 1 - ? LatLngBounds.fromPoints(points) - : null; final mapKey = ValueKey( - '${_formatPathPrefixes(selectedPath, width)},${context.l10n.pathTrace_you}', + '${_formatPathPrefixes(model.selectedPath, width)},${context.l10n.pathTrace_you}', ); - _pathDistance = _getPathDistance(points); return Scaffold( appBar: AppBar( @@ -976,31 +907,10 @@ class _ChannelMessagePathMapScreenState FlutterMap( key: mapKey, mapController: _mapController, - options: MapOptions( - initialCenter: initialCenter, - initialZoom: initialZoom, - initialCameraFit: bounds == null - ? null - : CameraFit.bounds( - bounds: bounds, - padding: const EdgeInsets.all(64), - maxZoom: 16, - ), - minZoom: _mapMinZoom, - maxZoom: _mapMaxZoom, - interactionOptions: InteractionOptions( - flags: ~InteractiveFlag.rotate, - scrollWheelVelocity: isDesktop ? 0.012 : 0.005, - cursorKeyboardRotationOptions: - CursorKeyboardRotationOptions.disabled(), - keyboardOptions: isDesktop - ? const KeyboardOptions( - enableArrowKeysPanning: true, - enableWASDPanning: true, - enableRFZooming: true, - ) - : const KeyboardOptions.disabled(), - ), + options: buildPathMapOptions( + initialCenter: model.initialCenter, + initialZoom: model.initialZoom, + bounds: model.bounds, onPositionChanged: (camera, hasGesture) { if (!mounted) return; // A manual pan/zoom releases the follow lock. @@ -1026,7 +936,7 @@ class _ChannelMessagePathMapScreenState builder: (context, _) { List lines; if (visibleDisplays.isEmpty) { - lines = polylines; + lines = model.polylines; } else { final animating = _animationEnabled && @@ -1081,11 +991,16 @@ class _ChannelMessagePathMapScreenState ), ], ), - if (isDesktop) - _buildDesktopMapControls( - initialCenter: initialCenter, - initialZoom: initialZoom, - bounds: bounds, + if (isDesktopMapPlatform()) + PathMapDesktopControls( + onZoomIn: () => zoomMapBy(_mapController, 1), + onZoomOut: () => zoomMapBy(_mapController, -1), + onReset: () => resetMapView( + _mapController, + bounds: model.bounds, + center: model.initialCenter, + zoom: model.initialZoom, + ), ), if (entries.length > 1) PathViewModeToggle( @@ -1127,6 +1042,8 @@ class _ChannelMessagePathMapScreenState entries: entries, selectedEntry: selectedEntry, effectiveMode: effectiveMode, + pathDistance: model.pathDistance, + hasSelfPoint: model.hasSelfPoint, ), ], ), @@ -1225,20 +1142,14 @@ class _ChannelMessagePathMapScreenState decoration: BoxDecoration( color: MeshPalette.blue, shape: BoxShape.circle, - border: Border.all(color: Colors.white, width: 2), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.3), - blurRadius: 4, - offset: const Offset(0, 2), - ), - ], + border: Border.all(color: MapPalette.markerOutline, width: 2), + boxShadow: [_markerShadow], ), alignment: Alignment.center, child: Text( hop.index.toString(), style: const TextStyle( - color: Colors.white, + color: MapPalette.textPrimary, fontWeight: FontWeight.bold, fontSize: 12, ), @@ -1249,7 +1160,7 @@ class _ChannelMessagePathMapScreenState ); if (showLabels) { markers.add( - _buildNodeLabelMarker( + buildPathNodeLabelMarker( point: point, label: hop.contact?.name ?? _formatPrefix(hop.prefix), ), @@ -1263,11 +1174,9 @@ class _ChannelMessagePathMapScreenState } List _buildSelfMarkers({required bool showLabels}) { - final selfLat = context.read().selfLatitude; - final selfLon = context.read().selfLongitude; - if (selfLat == null || selfLon == null) return const []; + final selfPoint = plausibleSelfPoint(context.read()); + if (selfPoint == null) return const []; final markers = []; - final selfPoint = LatLng(selfLat, selfLon); markers.add( Marker( point: selfPoint, @@ -1280,22 +1189,20 @@ class _ChannelMessagePathMapScreenState decoration: BoxDecoration( color: MeshPalette.signal, shape: BoxShape.circle, - border: Border.all(color: Colors.white, width: 2), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.3), - blurRadius: 4, - offset: const Offset(0, 2), - ), - ], + border: Border.all(color: MapPalette.markerOutline, width: 2), + boxShadow: [_markerShadow], ), alignment: Alignment.center, - child: Text( - context.l10n.pathTrace_you, - style: const TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold, - fontSize: 12, + padding: const EdgeInsets.all(3), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + context.l10n.pathTrace_you, + style: const TextStyle( + color: MapPalette.textPrimary, + fontWeight: FontWeight.bold, + fontSize: 12, + ), ), ), ), @@ -1304,7 +1211,7 @@ class _ChannelMessagePathMapScreenState ); if (showLabels) { markers.add( - _buildNodeLabelMarker( + buildPathNodeLabelMarker( point: selfPoint, label: context.l10n.pathTrace_you, ), @@ -1369,24 +1276,22 @@ class _ChannelMessagePathMapScreenState color: MeshPalette.blue, shape: BoxShape.circle, border: Border.all( - color: Colors.white, + color: MapPalette.markerOutline, width: shared ? 2.5 : 2, ), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.3), - blurRadius: 4, - offset: const Offset(0, 2), - ), - ], + boxShadow: [_markerShadow], ), alignment: Alignment.center, - child: Text( - label, - style: const TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold, - fontSize: 11, + padding: const EdgeInsets.all(2), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + label, + style: const TextStyle( + color: MapPalette.textPrimary, + fontWeight: FontWeight.bold, + fontSize: 12, + ), ), ), ), @@ -1394,24 +1299,7 @@ class _ChannelMessagePathMapScreenState Positioned( top: 0, right: 0, - child: Container( - width: 17, - height: 17, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: MeshPalette.bg1, - border: Border.all(color: MeshPalette.line3), - ), - alignment: Alignment.center, - child: Text( - '${node.paths.length}', - style: MeshTheme.mono( - fontSize: 9, - fontWeight: FontWeight.w700, - color: MeshPalette.ink, - ), - ), - ), + child: PathSharedCountBadge(count: node.paths.length), ), ], ), @@ -1420,7 +1308,7 @@ class _ChannelMessagePathMapScreenState ); if (showLabels) { markers.add( - _buildNodeLabelMarker( + buildPathNodeLabelMarker( point: point, label: hop.contact?.name ?? label, ), @@ -1441,41 +1329,6 @@ class _ChannelMessagePathMapScreenState return _orientPathBytes(bytes, hashByteWidth, reverse: reverse); } - Marker _buildNodeLabelMarker({required LatLng point, required String label}) { - return Marker( - point: point, - width: 120, - height: 24, - alignment: Alignment.topCenter, - child: IgnorePointer( - child: Transform.translate( - offset: const Offset(0, -20), - child: FittedBox( - fit: BoxFit.contain, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: Colors.black54, - borderRadius: BorderRadius.circular(8), - ), - alignment: Alignment.center, - child: Text( - label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - color: Colors.white, - fontSize: 11, - fontWeight: FontWeight.w500, - ), - ), - ), - ), - ), - ), - ); - } - Widget _buildLegendCard( BuildContext context, List<_PathHop> hops, @@ -1483,21 +1336,12 @@ class _ChannelMessagePathMapScreenState required List<_ObservedPathEntry> entries, required _ObservedPathEntry? selectedEntry, required PathViewMode effectiveMode, + required double pathDistance, + required bool hasSelfPoint, }) { final l10n = context.l10n; final combined = effectiveMode == PathViewMode.combined; final selectedDisplay = selectedEntry?.display; - final maxHeight = - MediaQuery.of(context).size.height * (combined ? 0.45 : 0.35); - - double cardHeight; - if (_panelCollapsed) { - cardHeight = 128; - } else { - final summaryHeight = combined ? 34.0 + entries.length * 36.0 : 0; - final estimatedHeight = 132.0 + summaryHeight + hops.length * 56.0; - cardHeight = max(176.0, min(maxHeight, estimatedHeight)); - } final hopUseCount = {}; if (combined) { @@ -1509,152 +1353,62 @@ class _ChannelMessagePathMapScreenState } } - return Positioned( - left: 16, - right: 16, - bottom: 16, - child: SizedBox( - height: cardHeight, - child: Container( - decoration: BoxDecoration( - color: MeshPalette.bg1, - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MeshPalette.line2), - ), - clipBehavior: Clip.antiAlias, - child: DefaultTextStyle( - style: const TextStyle(color: MeshPalette.ink), - child: IconTheme( - data: const IconThemeData(color: MeshPalette.ink), - child: TextButtonTheme( - data: TextButtonThemeData( - style: TextButton.styleFrom(foregroundColor: MeshPalette.ink), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(12, 8, 4, 0), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded( - child: Text( - l10n.channelPath_repeaterHops, - style: const TextStyle( - fontWeight: FontWeight.w600, - ), - ), - ), - Text( - formatDistance( - selectedDisplay?.distanceMeters ?? - _pathDistance, - isImperial: isImperial, - ), - style: MeshTheme.mono( - fontSize: 12, - color: MeshPalette.ink2, - ), - ), - ], - ), - const SizedBox(height: 4), - PathMiniLegend( - combined: combined, - showInferred: false, - ), - ], - ), - ), - IconButton( - visualDensity: VisualDensity.compact, - icon: Icon( - _panelCollapsed - ? Icons.expand_less - : Icons.expand_more, - size: 20, - ), - tooltip: _panelCollapsed - ? l10n.pathMap_expandPanel - : l10n.pathMap_collapsePanel, - onPressed: () => setState( - () => _panelCollapsed = !_panelCollapsed, - ), - ), - ], - ), - ), - PathAnimationControls( - playback: _playback, - selected: selectedDisplay, - animationEnabled: _animationEnabled, - onToggleAnimation: () => setState(() { - _animationEnabled = !_animationEnabled; - if (!_animationEnabled) _playback.stop(); - }), - followEnabled: _followPacket, - onToggleFollow: _toggleFollowPacket, - ), - if (!_panelCollapsed) ...[ - if (selectedDisplay != null && - selectedDisplay.unresolvedHops > 0) - Padding( - padding: const EdgeInsets.fromLTRB(12, 0, 12, 4), - child: Text( - l10n.pathMap_partialAnimation( - selectedDisplay.unresolvedHops, - ), - style: TextStyle( - fontSize: 10.5, - color: MeshPalette.warn, - ), - ), - ), - if (combined) - PathSummaryList( - paths: entries.map((e) => e.display).toList(), - selectedId: selectedDisplay?.id ?? '', - hiddenIds: _hiddenPathIds, - isImperial: isImperial, - onSelect: (display) { - for (final entry in entries) { - if (entry.display.id == display.id) { - _selectEntry(entry); - break; - } - } - }, - onToggleVisibility: (display) => - _togglePathVisibility( - display, - entries, - selectedDisplay, - ), - onShowAll: () => setState(_hiddenPathIds.clear), - ), - const Divider(height: 1), - Expanded( - child: _buildHopListView( - hops, - selectedDisplay, - hopUseCount, - ), - ), - ], - ], - ), - ), + return PathMapBottomPanel( + header: Row( + children: [ + Expanded( + child: Text( + l10n.channelPath_repeaterHops, + style: const TextStyle(fontWeight: FontWeight.w600), ), ), - ), + Text( + formatDistance( + selectedDisplay?.distanceMeters ?? pathDistance, + isImperial: isImperial, + l10n: l10n, + ), + style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink2), + ), + ], ), + combined: combined, + showInferredLegend: false, + collapsed: _panelCollapsed, + onToggleCollapsed: () => + setState(() => _panelCollapsed = !_panelCollapsed), + playback: _playback, + selected: selectedDisplay, + animationEnabled: _animationEnabled, + onToggleAnimation: () => setState(() { + _animationEnabled = !_animationEnabled; + if (!_animationEnabled) _playback.stop(); + }), + followEnabled: _followPacket, + onToggleFollow: _toggleFollowPacket, + showNoSelfGpsNote: !hasSelfPoint, + pathCount: entries.length, + hopRowCount: hops.length, + summary: combined + ? PathSummaryList( + paths: entries.map((e) => e.display).toList(), + selectedId: selectedDisplay?.id ?? '', + hiddenIds: _hiddenPathIds, + isImperial: isImperial, + onSelect: (display) { + for (final entry in entries) { + if (entry.display.id == display.id) { + _selectEntry(entry); + break; + } + } + }, + onToggleVisibility: (display) => + _togglePathVisibility(display, entries, selectedDisplay), + onShowAll: () => setState(_hiddenPathIds.clear), + ) + : null, + hopList: _buildHopListView(hops, selectedDisplay, hopUseCount), ); } @@ -1702,8 +1456,8 @@ class _ChannelMessagePathMapScreenState child: Row( children: [ Container( - width: 28, - height: 28, + width: 30, + height: 30, decoration: BoxDecoration( color: MeshPalette.blueDim.withValues(alpha: 0.3), shape: BoxShape.circle, @@ -1712,12 +1466,15 @@ class _ChannelMessagePathMapScreenState ), ), alignment: Alignment.center, - child: Text( - hop.index.toString(), - style: const TextStyle( - color: Colors.white, - fontSize: 11, - fontWeight: FontWeight.w700, + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + hop.index.toString(), + style: const TextStyle( + color: MeshPalette.ink, + fontSize: 12, + fontWeight: FontWeight.w700, + ), ), ), ), @@ -1746,7 +1503,7 @@ class _ChannelMessagePathMapScreenState ), ].join(' · '), style: MeshTheme.mono( - fontSize: 10, + fontSize: 12, color: MeshPalette.ink3, ), overflow: TextOverflow.ellipsis, @@ -1765,6 +1522,47 @@ class _ChannelMessagePathMapScreenState } } +final BoxShadow _markerShadow = BoxShadow( + color: MapPalette.markerShadow.withValues(alpha: 0.3), + blurRadius: 4, + offset: Offset(0, 2), +); + +/// Resolved map state for the current selection, cached between rebuilds. +class _PathMapModel { + final List<_ObservedPath> observedPaths; + final int selectedIndex; + final int width; + final Uint8List selectedPath; + final List<_PathHop> hops; + final List<_ObservedPathEntry> entries; + final _ObservedPathEntry? selectedEntry; + final List points; + final List polylines; + final LatLng initialCenter; + final double initialZoom; + final LatLngBounds? bounds; + final double pathDistance; + final bool hasSelfPoint; + + const _PathMapModel({ + required this.observedPaths, + required this.selectedIndex, + required this.width, + required this.selectedPath, + required this.hops, + required this.entries, + required this.selectedEntry, + required this.points, + required this.polylines, + required this.initialCenter, + required this.initialZoom, + required this.bounds, + required this.pathDistance, + required this.hasSelfPoint, + }); +} + /// One observed route paired with its renderable form and resolved hops. class _ObservedPathEntry { final int index; @@ -1827,20 +1625,17 @@ class _ObservedPath { List<_PathHop> _buildPathHops( Uint8List pathBytes, - MeshCoreConnector connector, + List contacts, + LatLng? endpoint, AppLocalizations l10n, int hashByteWidth, { bool resolveFromEnd = false, }) { if (pathBytes.isEmpty) return const []; final width = hashByteWidth.clamp(1, 4).toInt(); - final endpoint = - (connector.selfLatitude != null && connector.selfLongitude != null) - ? LatLng(connector.selfLatitude!, connector.selfLongitude!) - : null; final resolvedContacts = PathHopResolver.resolve( pathBytes: pathBytes, - contacts: connector.allContacts, + contacts: contacts, endpoint: endpoint, resolveFromEnd: resolveFromEnd, pathHashByteWidth: width, diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index a9c2716d..655f7af1 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -90,10 +90,11 @@ class _ChannelsScreenState extends State String _relativeTime(DateTime t) { final diff = DateTime.now().difference(t); - if (diff.inMinutes < 1) return 'now'; - if (diff.inMinutes < 60) return '${diff.inMinutes}m'; - if (diff.inHours < 24) return '${diff.inHours}h'; - return '${diff.inDays}d'; + final l10n = context.l10n; + if (diff.inMinutes < 1) return l10n.channels_timeNow; + if (diff.inMinutes < 60) return l10n.channels_timeMinutes(diff.inMinutes); + if (diff.inHours < 24) return l10n.channels_timeHours(diff.inHours); + return l10n.channels_timeDays(diff.inDays); } @override @@ -513,7 +514,7 @@ class _ChannelsScreenState extends State child: const Icon( Icons.people, size: 8, - color: Colors.white, + color: MeshPalette.ink, ), ), ), @@ -541,9 +542,9 @@ class _ChannelsScreenState extends State if (showDragHandle) ...[ const SizedBox(width: 6), Text( - 'CH ${channel.index}', + context.l10n.channels_indexChip(channel.index), style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: scheme.onSurfaceVariant.withValues( alpha: 0.7, ), @@ -568,7 +569,7 @@ class _ChannelsScreenState extends State Text( lastPreview, style: MeshTheme.mono( - fontSize: 11.5, + fontSize: 12, color: scheme.onSurfaceVariant, ), maxLines: 1, @@ -588,7 +589,7 @@ class _ChannelsScreenState extends State Text( _relativeTime(lastTime), style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: scheme.onSurfaceVariant, ), ), @@ -599,7 +600,7 @@ class _ChannelsScreenState extends State if (isMuted) ...[ Icon( Icons.notifications_off, - size: 14, + size: 18, color: scheme.onSurfaceVariant, ), const SizedBox(width: 4), @@ -645,8 +646,8 @@ class _ChannelsScreenState extends State final settingsService = context.read(); final isMuted = settingsService.isChannelMuted(channel.muteKey); - showModalBottomSheet( - context: parentContext, + showMeshSheet( + parentContext, builder: (sheetContext) => SafeArea( child: Column( mainAxisSize: MainAxisSize.min, @@ -829,7 +830,8 @@ class _ChannelsScreenState extends State String _normalizeChannelName(Channel channel) { if (channel.name.isEmpty) { - return 'Channel ${channel.index}'; // Fallback for sorting + // Same label the tile shows, so search and A-Z sort match it. + return context.l10n.channels_channelIndex(channel.index); } final trimmed = channel.name.trim(); if (trimmed.startsWith('#') && trimmed.length > 1) { @@ -843,9 +845,6 @@ class _ChannelsScreenState extends State if (_resolveFreeChannelSlot(context, connector) == null) return; final hasPublicChannel = connector.channels.any((c) => c.isPublicChannel); int? selectedOption; - final nameController = TextEditingController(); - final pskController = TextEditingController(); - final hashtagController = TextEditingController(); bool addPublicChannel = true; bool isRegularHashtag = true; Community? selectedCommunity; @@ -854,510 +853,307 @@ class _ChannelsScreenState extends State showMeshSheet( context, - builder: (sheetContext) => StatefulBuilder( - builder: (sheetContext, setSheetState) { - Widget buildOptionCard({ - required int optionIndex, - required IconData icon, - required String title, - required String subtitle, - bool enabled = true, - }) { - final isSelected = selectedOption == optionIndex; - final cardScheme = Theme.of(sheetContext).colorScheme; - return MeshCard( - margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), - borderColor: isSelected && enabled ? MeshPalette.blueLine : null, - color: isSelected && enabled ? MeshPalette.blueBg : null, - onTap: enabled - ? () { - setSheetState(() { - selectedOption = optionIndex; - nameController.clear(); - pskController.clear(); - hashtagController.clear(); - }); - } - : null, - child: Row( - children: [ - AvatarCircle( - name: title, - size: 38, - color: enabled - ? (isSelected + // The controllers live in a State so they are disposed with the sheet, + // after its exit animation, rather than leaked. + builder: (sheetContext) => _SheetTextControllers( + initialTexts: const ['', '', ''], + builder: (controllers) { + final nameController = controllers[0]; + final pskController = controllers[1]; + final hashtagController = controllers[2]; + return StatefulBuilder( + builder: (sheetContext, setSheetState) { + Widget buildOptionCard({ + required int optionIndex, + required IconData icon, + required String title, + required String subtitle, + bool enabled = true, + }) { + final isSelected = selectedOption == optionIndex; + final cardScheme = Theme.of(sheetContext).colorScheme; + return MeshCard( + margin: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + borderColor: isSelected && enabled + ? MeshPalette.blueLine + : null, + color: isSelected && enabled ? MeshPalette.blueBg : null, + onTap: enabled + ? () { + setSheetState(() { + selectedOption = optionIndex; + nameController.clear(); + pskController.clear(); + hashtagController.clear(); + }); + } + : null, + child: Row( + children: [ + AvatarCircle( + name: title, + size: 38, + color: enabled + ? (isSelected + ? MeshPalette.blue + : cardScheme.onSurfaceVariant) + : cardScheme.outline, + icon: icon, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: Theme.of(sheetContext).textTheme.bodyMedium + ?.copyWith( + fontWeight: FontWeight.w500, + color: enabled ? null : cardScheme.outline, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: Theme.of(sheetContext).textTheme.bodySmall + ?.copyWith( + color: enabled + ? cardScheme.onSurfaceVariant + : cardScheme.outline, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + if (enabled) + Icon( + Icons.chevron_right, + color: isSelected ? MeshPalette.blue - : cardScheme.onSurfaceVariant) - : cardScheme.outline, - icon: icon, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - title, - style: Theme.of(sheetContext).textTheme.bodyMedium - ?.copyWith( - fontWeight: FontWeight.w500, - color: enabled ? null : cardScheme.outline, - ), + : cardScheme.onSurfaceVariant, + size: 20, ), - const SizedBox(height: 2), - Text( - subtitle, - style: Theme.of(sheetContext).textTheme.bodySmall - ?.copyWith( - color: enabled - ? cardScheme.onSurfaceVariant - : cardScheme.outline, - ), - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - ], - ), + ], ), - if (enabled) - Icon( - Icons.chevron_right, - color: isSelected - ? MeshPalette.blue - : cardScheme.onSurfaceVariant, - size: 20, - ), - ], - ), - ); - } + ); + } - Widget? buildExpandedContent( - ChannelMessageStore channelMessageStore, - ) { - switch (selectedOption) { - case 0: // Create Private Channel - return Column( - children: [ - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: TextField( - controller: nameController, - decoration: InputDecoration( - labelText: sheetContext.l10n.channels_channelName, - border: const OutlineInputBorder(), - ), - inputFormatters: const [ - Utf8LengthLimitingTextInputFormatter( - maxRadioNameBytes, + Widget? buildExpandedContent( + ChannelMessageStore channelMessageStore, + ) { + switch (selectedOption) { + case 0: // Create Private Channel + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, ), - ], - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Row( - children: [ - Expanded( - child: FilledButton( - onPressed: () async { - final name = nameController.text.trim(); - if (name.isEmpty) { - showDismissibleSnackBar( - context, - content: Text( - sheetContext - .l10n - .channels_enterChannelName, - ), - ); - return; - } - final nextIndex = _resolveFreeChannelSlot( - context, - connector, - ); - if (nextIndex == null) return; - final psk = randomBytes(16); - Navigator.pop(sheetContext); - await connector.setChannel( - nextIndex, - name, - psk, - ); - await channelMessageStore.clearChannelMessages( - nextIndex, - ); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelAdded(name), - ), - ); - } - }, - child: Text(sheetContext.l10n.common_create), + child: TextField( + controller: nameController, + decoration: InputDecoration( + labelText: sheetContext.l10n.channels_channelName, + border: const OutlineInputBorder(), + ), + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter( + maxRadioNameBytes, + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Expanded( + child: FilledButton( + onPressed: () async { + final name = nameController.text.trim(); + if (name.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + sheetContext + .l10n + .channels_enterChannelName, + ), + ); + return; + } + final nextIndex = _resolveFreeChannelSlot( + context, + connector, + ); + if (nextIndex == null) return; + final psk = randomBytes(16); + Navigator.pop(sheetContext); + await connector.setChannel( + nextIndex, + name, + psk, + ); + await channelMessageStore + .clearChannelMessages(nextIndex); + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelAdded( + name, + ), + ), + ); + } + }, + child: Text(sheetContext.l10n.common_create), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ); + + case 1: // Join Private Channel + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: TextField( + controller: nameController, + decoration: InputDecoration( + labelText: sheetContext.l10n.channels_channelName, + border: const OutlineInputBorder(), + ), + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter( + maxRadioNameBytes, + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: TextField( + controller: pskController, + decoration: InputDecoration( + labelText: sheetContext.l10n.channels_pskHex, + border: const OutlineInputBorder(), ), ), - ], - ), - ), - const SizedBox(height: 8), - ], - ); - - case 1: // Join Private Channel - return Column( - children: [ - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: TextField( - controller: nameController, - decoration: InputDecoration( - labelText: sheetContext.l10n.channels_channelName, - border: const OutlineInputBorder(), ), - inputFormatters: const [ - Utf8LengthLimitingTextInputFormatter( - maxRadioNameBytes, + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Expanded( + child: FilledButton( + onPressed: () { + final name = nameController.text.trim(); + final pskHex = pskController.text.trim(); + if (name.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + sheetContext + .l10n + .channels_enterChannelName, + ), + ); + return; + } + Uint8List psk; + try { + psk = Channel.parsePskHex(pskHex); + } on FormatException { + showDismissibleSnackBar( + context, + content: Text( + sheetContext + .l10n + .channels_pskMustBe32Hex, + ), + ); + return; + } + final nextIndex = _resolveFreeChannelSlot( + context, + connector, + ); + if (nextIndex == null) return; + Navigator.pop(sheetContext); + connector.setChannel(nextIndex, name, psk); + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelAdded( + name, + ), + ), + ); + } + }, + child: Text(sheetContext.l10n.common_add), + ), + ), + ], ), - ], - ), - ), - Padding( + ), + const SizedBox(height: 8), + ], + ); + + case 2: // Join Public Channel + return Padding( padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 8, ), - child: TextField( - controller: pskController, - decoration: InputDecoration( - labelText: sheetContext.l10n.channels_pskHex, - border: const OutlineInputBorder(), - ), - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( children: [ Expanded( child: FilledButton( onPressed: () { - final name = nameController.text.trim(); - final pskHex = pskController.text.trim(); - if (name.isEmpty) { - showDismissibleSnackBar( - context, - content: Text( - sheetContext - .l10n - .channels_enterChannelName, - ), - ); - return; - } - Uint8List psk; - try { - psk = Channel.parsePskHex(pskHex); - } on FormatException { - showDismissibleSnackBar( - context, - content: Text( - sheetContext.l10n.channels_pskMustBe32Hex, - ), - ); - return; - } final nextIndex = _resolveFreeChannelSlot( context, connector, ); if (nextIndex == null) return; + final psk = Channel.parsePskHex( + Channel.publicChannelPsk, + ); Navigator.pop(sheetContext); - connector.setChannel(nextIndex, name, psk); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelAdded(name), - ), - ); - } - }, - child: Text(sheetContext.l10n.common_add), - ), - ), - ], - ), - ), - const SizedBox(height: 8), - ], - ); - - case 2: // Join Public Channel - return Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: Row( - children: [ - Expanded( - child: FilledButton( - onPressed: () { - final nextIndex = _resolveFreeChannelSlot( - context, - connector, - ); - if (nextIndex == null) return; - final psk = Channel.parsePskHex( - Channel.publicChannelPsk, - ); - Navigator.pop(sheetContext); - connector.setChannel( - nextIndex, - context.l10n.channels_public, - psk, - ); - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_publicChannelAdded, - ), - ); - } - }, - child: Text(sheetContext.l10n.common_add), - ), - ), - ], - ), - ); - - case 3: // Join Hashtag Channel - return Column( - children: [ - // Only show type selection if user has communities - if (_communities.isNotEmpty) ...[ - RadioGroup( - groupValue: isRegularHashtag, - onChanged: (v) => setSheetState(() { - if (v == null) return; - isRegularHashtag = v; - if (isRegularHashtag) { - selectedCommunity = null; - } else if (selectedCommunity == null && - _communities.isNotEmpty) { - selectedCommunity = _communities.first; - } - }), - child: Column( - children: [ - RadioListTile( - value: true, - title: Text( - sheetContext.l10n.community_regularHashtag, - ), - subtitle: Text( - sheetContext.l10n.community_regularHashtagDesc, - ), - dense: true, - ), - RadioListTile( - value: false, - title: Text( - sheetContext.l10n.community_communityHashtag, - ), - subtitle: Text( - sheetContext - .l10n - .community_communityHashtagDesc, - ), - dense: true, - ), - ], - ), - ), - ], - // Community dropdown (only if community hashtag selected) - if (!isRegularHashtag && _communities.isNotEmpty) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: DropdownButtonFormField( - initialValue: selectedCommunity, - items: _communities - .map( - (c) => DropdownMenuItem( - value: c, - child: Text(c.name), - ), - ) - .toList(), - onChanged: (c) => - setSheetState(() => selectedCommunity = c), - decoration: InputDecoration( - labelText: - sheetContext.l10n.community_selectCommunity, - border: const OutlineInputBorder(), - prefixIcon: const Icon(Icons.groups), - ), - ), - ), - // Hashtag name input - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: TextField( - controller: hashtagController, - decoration: InputDecoration( - labelText: sheetContext.l10n.channels_enterHashtag, - hintText: sheetContext.l10n.channels_hashtagHint, - border: const OutlineInputBorder(), - prefixIcon: const Icon(Icons.tag), - ), - inputFormatters: [ - Utf8LengthLimitingTextInputFormatter( - maxRadioNameBytes, - encoder: (text) { - final tag = text.trim().startsWith('#') - ? text.trim().substring(1) - : text.trim(); - if (!isRegularHashtag && - selectedCommunity != null) { - return '${selectedCommunity!.name} #$tag'; - } - return '#$tag'; - }, - ), - ], - ), - ), - // Privacy hint for community hashtags - if (!isRegularHashtag) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Text( - sheetContext.l10n.community_hashtagPrivacyHint, - style: TextStyle( - fontSize: 12, - color: Theme.of( - sheetContext, - ).colorScheme.onSurfaceVariant, - fontStyle: FontStyle.italic, - ), - ), - ), - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: Row( - children: [ - Expanded( - child: FilledButton( - onPressed: () async { - var hashtag = hashtagController.text.trim(); - if (hashtag.isEmpty) { - showDismissibleSnackBar( - context, - content: Text( - sheetContext - .l10n - .channels_enterChannelName, - ), - ); - return; - } - - // Normalize hashtag name (remove leading # if present) - if (hashtag.startsWith('#')) { - hashtag = hashtag.substring(1); - } - if (!isRegularHashtag && - selectedCommunity != null && - utf8ByteLength( - '${selectedCommunity!.name} #$hashtag', - ) > - maxRadioNameBytes) { - showDismissibleSnackBar( - context, - content: Text( - sheetContext.l10n.channels_nameTooLong( - maxRadioNameBytes, - ), - ), - ); - return; - } - final nextIndex = _resolveFreeChannelSlot( - context, - connector, - ); - if (nextIndex == null) return; - final String channelName; - - final Uint8List psk; - if (isRegularHashtag) { - channelName = '#$hashtag'; - // Regular hashtag - public derivation using SHA256 - psk = Channel.derivePskFromHashtag(hashtag); - } else { - // Community hashtag - HMAC derivation from community secret - if (selectedCommunity == null) { - showDismissibleSnackBar( - sheetContext, - content: Text( - sheetContext - .l10n - .community_selectCommunity, - ), - ); - return; - } - channelName = - '${selectedCommunity!.name} #$hashtag'; - psk = selectedCommunity! - .deriveCommunityHashtagPsk(hashtag); - // Track in community's hashtag list - await _communityStore.addHashtagChannel( - selectedCommunity!.id, - hashtag, - ); - _loadCommunities(); - } - - if (sheetContext.mounted) { - Navigator.pop(sheetContext); - } connector.setChannel( nextIndex, - channelName, + context.l10n.channels_public, psk, ); if (context.mounted) { showDismissibleSnackBar( context, content: Text( - context.l10n.channels_channelAdded( - channelName, - ), + context.l10n.channels_publicChannelAdded, ), ); } @@ -1367,260 +1163,512 @@ class _ChannelsScreenState extends State ), ], ), - ), - ], - ); + ); - case 4: // Scan Community QR - return Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 8, - ), - child: Row( - children: [ - Expanded( - child: FilledButton.icon( - onPressed: () async { - Navigator.pop(sheetContext); - if (context.mounted) { - final result = await Navigator.push( - context, - MaterialPageRoute( - builder: (context) => - const CommunityQrScannerScreen(), - ), - ); - // Result handled by scanner screen - if (result != null && context.mounted) { - // Community was joined, refresh might be needed + case 3: // Join Hashtag Channel + return Column( + children: [ + // Only show type selection if user has communities + if (_communities.isNotEmpty) ...[ + RadioGroup( + groupValue: isRegularHashtag, + onChanged: (v) => setSheetState(() { + if (v == null) return; + isRegularHashtag = v; + if (isRegularHashtag) { + selectedCommunity = null; + } else if (selectedCommunity == null && + _communities.isNotEmpty) { + selectedCommunity = _communities.first; } - } - }, - icon: const Icon(Icons.qr_code_scanner), - label: Text(sheetContext.l10n.community_scanQr), + }), + child: Column( + children: [ + RadioListTile( + value: true, + title: Text( + sheetContext.l10n.community_regularHashtag, + ), + subtitle: Text( + sheetContext + .l10n + .community_regularHashtagDesc, + ), + dense: true, + ), + RadioListTile( + value: false, + title: Text( + sheetContext + .l10n + .community_communityHashtag, + ), + subtitle: Text( + sheetContext + .l10n + .community_communityHashtagDesc, + ), + dense: true, + ), + ], + ), + ), + ], + // Community dropdown (only if community hashtag selected) + if (!isRegularHashtag && _communities.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: DropdownButtonFormField( + initialValue: selectedCommunity, + items: _communities + .map( + (c) => DropdownMenuItem( + value: c, + child: Text(c.name), + ), + ) + .toList(), + onChanged: (c) => + setSheetState(() => selectedCommunity = c), + decoration: InputDecoration( + labelText: + sheetContext.l10n.community_selectCommunity, + border: const OutlineInputBorder(), + prefixIcon: const Icon(Icons.groups), + ), + ), + ), + // Hashtag name input + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: TextField( + controller: hashtagController, + decoration: InputDecoration( + labelText: + sheetContext.l10n.channels_enterHashtag, + hintText: sheetContext.l10n.channels_hashtagHint, + border: const OutlineInputBorder(), + prefixIcon: const Icon(Icons.tag), + ), + inputFormatters: [ + Utf8LengthLimitingTextInputFormatter( + maxRadioNameBytes, + encoder: (text) { + final tag = text.trim().startsWith('#') + ? text.trim().substring(1) + : text.trim(); + if (!isRegularHashtag && + selectedCommunity != null) { + return '${selectedCommunity!.name} #$tag'; + } + return '#$tag'; + }, + ), + ], + ), ), - ), - ], - ), - ); + // Privacy hint for community hashtags + if (!isRegularHashtag) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + sheetContext.l10n.community_hashtagPrivacyHint, + style: TextStyle( + fontSize: 12, + color: Theme.of( + sheetContext, + ).colorScheme.onSurfaceVariant, + fontStyle: FontStyle.italic, + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: Row( + children: [ + Expanded( + child: FilledButton( + onPressed: () async { + var hashtag = hashtagController.text.trim(); + if (hashtag.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + sheetContext + .l10n + .channels_enterChannelName, + ), + ); + return; + } - case 5: // Create Community - return Column( - children: [ - Padding( + // Normalize hashtag name (remove leading # if present) + if (hashtag.startsWith('#')) { + hashtag = hashtag.substring(1); + } + if (!isRegularHashtag && + selectedCommunity != null && + utf8ByteLength( + '${selectedCommunity!.name} #$hashtag', + ) > + maxRadioNameBytes) { + showDismissibleSnackBar( + context, + content: Text( + sheetContext.l10n + .channels_nameTooLong( + maxRadioNameBytes, + ), + ), + ); + return; + } + final nextIndex = _resolveFreeChannelSlot( + context, + connector, + ); + if (nextIndex == null) return; + final String channelName; + + final Uint8List psk; + if (isRegularHashtag) { + channelName = '#$hashtag'; + // Regular hashtag - public derivation using SHA256 + psk = Channel.derivePskFromHashtag( + hashtag, + ); + } else { + // Community hashtag - HMAC derivation from community secret + if (selectedCommunity == null) { + showDismissibleSnackBar( + sheetContext, + content: Text( + sheetContext + .l10n + .community_selectCommunity, + ), + ); + return; + } + channelName = + '${selectedCommunity!.name} #$hashtag'; + psk = selectedCommunity! + .deriveCommunityHashtagPsk(hashtag); + // Track in community's hashtag list + await _communityStore.addHashtagChannel( + selectedCommunity!.id, + hashtag, + ); + _loadCommunities(); + } + + if (sheetContext.mounted) { + Navigator.pop(sheetContext); + } + connector.setChannel( + nextIndex, + channelName, + psk, + ); + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelAdded( + channelName, + ), + ), + ); + } + }, + child: Text(sheetContext.l10n.common_add), + ), + ), + ], + ), + ), + ], + ); + + case 4: // Scan Community QR + return Padding( padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 8, ), - child: TextField( - controller: nameController, - decoration: InputDecoration( - labelText: sheetContext.l10n.community_name, - hintText: sheetContext.l10n.community_enterName, - border: const OutlineInputBorder(), - prefixIcon: const Icon(Icons.groups), - ), - inputFormatters: [ - Utf8LengthLimitingTextInputFormatter( - maxRadioNameBytes, - encoder: (text) => - '$text ${sheetContext.l10n.channels_public}', - ), - ], - ), - ), - CheckboxListTile( - value: addPublicChannel, - onChanged: (value) { - setSheetState(() { - addPublicChannel = value ?? true; - }); - }, - title: Text(sheetContext.l10n.community_addPublicChannel), - subtitle: Text( - sheetContext.l10n.community_addPublicChannelHint, - ), - controlAffinity: ListTileControlAffinity.leading, - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( children: [ Expanded( - child: FilledButton( + child: FilledButton.icon( onPressed: () async { - final name = nameController.text.trim(); - final publicLabel = - context.l10n.channels_public; - if (name.isEmpty) { - showDismissibleSnackBar( - context, - content: Text( - sheetContext.l10n.community_enterName, - ), - ); - return; - } - - final nextIndex = addPublicChannel - ? _resolveFreeChannelSlot( - context, - connector, - ) - : null; - if (addPublicChannel && nextIndex == null) { - return; - } - - // Create community with random secret - final community = Community.create( - id: const Uuid().v4(), - name: name, - ); - - // Save to store - await _communityStore.addCommunity(community); - - // Optionally add the community public channel to the device - if (nextIndex != null) { - final psk = community - .deriveCommunityPublicPsk(); - final channelName = fitRadioName( - community.name, - publicLabel, - ); - connector.setChannel( - nextIndex, - channelName, - psk, - ); - } - - if (sheetContext.mounted) { - Navigator.pop(sheetContext); - } - - // Refresh communities list - _loadCommunities(); - + Navigator.pop(sheetContext); if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.community_created(name), - ), - ); - - // Show QR code dialog - await QrCodeShareDialog.show( - context: context, - data: community.toQrJson(), - title: context.l10n.community_qrTitle, - instructions: context.l10n - .community_qrInstructions(name), - embeddedImage: Image.asset( - 'assets/images/mesh-icon.png', - width: 40, - height: 40, - ), - ); + final result = + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + const CommunityQrScannerScreen(), + ), + ); + // The scanner saves the community; reload so the + // list, badges and hashtag options include it. + if (result != null && mounted) { + _loadCommunities(); + } } }, - child: Text(sheetContext.l10n.common_create), + icon: const Icon(Icons.qr_code_scanner), + label: Text(sheetContext.l10n.community_scanQr), ), ), ], ), - ), - const SizedBox(height: 8), - ], - ); + ); - default: - return null; - } - } - - return DraggableScrollableSheet( - expand: false, - initialChildSize: 0.7, - minChildSize: 0.4, - maxChildSize: 0.95, - builder: (_, scrollController) => Column( - children: [ - BottomSheetHeader(title: sheetContext.l10n.channels_addChannel), - Expanded( - child: ListView( - controller: scrollController, - padding: const EdgeInsets.only(bottom: 24), - children: [ - SectionHeader(sheetContext.l10n.channels_addSectionJoin), - if (!hasPublicChannel) ...[ - buildOptionCard( - optionIndex: 2, - icon: Icons.public, - title: sheetContext.l10n.channels_joinPublicChannel, - subtitle: - sheetContext.l10n.channels_joinPublicChannelDesc, + case 5: // Create Community + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: TextField( + controller: nameController, + decoration: InputDecoration( + labelText: sheetContext.l10n.community_name, + hintText: sheetContext.l10n.community_enterName, + border: const OutlineInputBorder(), + prefixIcon: const Icon(Icons.groups), + ), + inputFormatters: [ + Utf8LengthLimitingTextInputFormatter( + maxRadioNameBytes, + encoder: (text) => + '$text ${sheetContext.l10n.channels_public}', + ), + ], + ), ), - if (selectedOption == 2) - buildExpandedContent(_channelMessageStore)!, + CheckboxListTile( + value: addPublicChannel, + onChanged: (value) { + setSheetState(() { + addPublicChannel = value ?? true; + }); + }, + title: Text( + sheetContext.l10n.community_addPublicChannel, + ), + subtitle: Text( + sheetContext.l10n.community_addPublicChannelHint, + ), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Expanded( + child: FilledButton( + onPressed: () async { + final name = nameController.text.trim(); + final publicLabel = + context.l10n.channels_public; + if (name.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + sheetContext.l10n.community_enterName, + ), + ); + return; + } + + final nextIndex = addPublicChannel + ? _resolveFreeChannelSlot( + context, + connector, + ) + : null; + if (addPublicChannel && nextIndex == null) { + return; + } + + // Create community with random secret + final community = Community.create( + id: const Uuid().v4(), + name: name, + ); + + // Save to store + await _communityStore.addCommunity( + community, + ); + + // Optionally add the community public channel to the device + if (nextIndex != null) { + final psk = community + .deriveCommunityPublicPsk(); + final channelName = fitRadioName( + community.name, + publicLabel, + ); + connector.setChannel( + nextIndex, + channelName, + psk, + ); + } + + if (sheetContext.mounted) { + Navigator.pop(sheetContext); + } + + // Refresh communities list + _loadCommunities(); + + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.community_created(name), + ), + ); + + // Show QR code dialog + await QrCodeShareDialog.show( + context: context, + data: community.toQrJson(), + title: context.l10n.community_qrTitle, + instructions: context.l10n + .community_qrInstructions(name), + embeddedImage: Image.asset( + 'assets/images/mesh-icon.png', + width: 40, + height: 40, + ), + ); + } + }, + child: Text(sheetContext.l10n.common_create), + ), + ), + ], + ), + ), + const SizedBox(height: 8), ], - buildOptionCard( - optionIndex: 3, - icon: Icons.tag, - title: sheetContext.l10n.channels_joinHashtagChannel, - subtitle: - sheetContext.l10n.channels_joinHashtagChannelDesc, + ); + + default: + return null; + } + } + + return DraggableScrollableSheet( + expand: false, + initialChildSize: 0.7, + minChildSize: 0.4, + maxChildSize: 0.95, + builder: (_, scrollController) => Column( + children: [ + BottomSheetHeader( + title: sheetContext.l10n.channels_addChannel, + ), + Expanded( + child: ListView( + controller: scrollController, + padding: const EdgeInsets.only(bottom: 24), + children: [ + SectionHeader( + sheetContext.l10n.channels_addSectionJoin, + ), + if (!hasPublicChannel) ...[ + buildOptionCard( + optionIndex: 2, + icon: Icons.public, + title: + sheetContext.l10n.channels_joinPublicChannel, + subtitle: sheetContext + .l10n + .channels_joinPublicChannelDesc, + ), + if (selectedOption == 2) + buildExpandedContent(_channelMessageStore)!, + ], + buildOptionCard( + optionIndex: 3, + icon: Icons.tag, + title: + sheetContext.l10n.channels_joinHashtagChannel, + subtitle: sheetContext + .l10n + .channels_joinHashtagChannelDesc, + ), + if (selectedOption == 3) + buildExpandedContent(_channelMessageStore)!, + buildOptionCard( + optionIndex: 1, + icon: Icons.lock, + title: + sheetContext.l10n.channels_joinPrivateChannel, + subtitle: sheetContext + .l10n + .channels_joinPrivateChannelDesc, + ), + if (selectedOption == 1) + buildExpandedContent(_channelMessageStore)!, + buildOptionCard( + optionIndex: 4, + icon: Icons.qr_code_scanner, + title: sheetContext.l10n.community_scanQr, + subtitle: sheetContext.l10n.community_join, + ), + if (selectedOption == 4) + buildExpandedContent(_channelMessageStore)!, + SectionHeader( + sheetContext.l10n.channels_addSectionCreate, + ), + buildOptionCard( + optionIndex: 0, + icon: Icons.add, + title: + sheetContext.l10n.channels_createPrivateChannel, + subtitle: sheetContext + .l10n + .channels_createPrivateChannelDesc, + ), + if (selectedOption == 0) + buildExpandedContent(_channelMessageStore)!, + buildOptionCard( + optionIndex: 5, + icon: Icons.groups, + title: sheetContext.l10n.community_create, + subtitle: sheetContext.l10n.community_createDesc, + ), + if (selectedOption == 5) + buildExpandedContent(_channelMessageStore)!, + ], ), - if (selectedOption == 3) - buildExpandedContent(_channelMessageStore)!, - buildOptionCard( - optionIndex: 1, - icon: Icons.lock, - title: sheetContext.l10n.channels_joinPrivateChannel, - subtitle: - sheetContext.l10n.channels_joinPrivateChannelDesc, - ), - if (selectedOption == 1) - buildExpandedContent(_channelMessageStore)!, - buildOptionCard( - optionIndex: 4, - icon: Icons.qr_code_scanner, - title: sheetContext.l10n.community_scanQr, - subtitle: sheetContext.l10n.community_join, - ), - if (selectedOption == 4) - buildExpandedContent(_channelMessageStore)!, - SectionHeader( - sheetContext.l10n.channels_addSectionCreate, - ), - buildOptionCard( - optionIndex: 0, - icon: Icons.add, - title: sheetContext.l10n.channels_createPrivateChannel, - subtitle: - sheetContext.l10n.channels_createPrivateChannelDesc, - ), - if (selectedOption == 0) - buildExpandedContent(_channelMessageStore)!, - buildOptionCard( - optionIndex: 5, - icon: Icons.groups, - title: sheetContext.l10n.community_create, - subtitle: sheetContext.l10n.community_createDesc, - ), - if (selectedOption == 5) - buildExpandedContent(_channelMessageStore)!, - ], - ), + ), + ], ), - ], - ), + ); + }, ); }, ), @@ -1636,8 +1684,6 @@ class _ChannelsScreenState extends State context, listen: false, ); - final nameController = TextEditingController(text: channel.name); - final pskController = TextEditingController(text: channel.pskHex); bool smazEnabled = connector.isChannelSmazEnabled(channel.index); bool cyr2latEnabled = connector.isChannelCyr2LatEnabled(channel.index); bool urlImagesEnabled = connector.isChannelUrlImagesEnabled(channel.index); @@ -1647,195 +1693,220 @@ class _ChannelsScreenState extends State showMeshSheet( context, - builder: (sheetContext) => StatefulBuilder( - builder: (sheetContext, setSheetState) => DraggableScrollableSheet( - expand: false, - initialChildSize: 0.65, - minChildSize: 0.4, - maxChildSize: 0.95, - builder: (_, scrollController) => Column( - children: [ - BottomSheetHeader( - title: sheetContext.l10n.channels_editChannelTitle( - channel.index, - ), - ), - Expanded( - child: ListView( - controller: scrollController, - padding: const EdgeInsets.symmetric(horizontal: 16), - children: [ - const SizedBox(height: 8), - TextField( - controller: nameController, - decoration: InputDecoration( - labelText: sheetContext.l10n.channels_channelName, - border: const OutlineInputBorder(), - ), - inputFormatters: const [ - Utf8LengthLimitingTextInputFormatter(maxRadioNameBytes), - ], + builder: (sheetContext) => _SheetTextControllers( + initialTexts: [channel.name, channel.pskHex], + builder: (controllers) { + final nameController = controllers[0]; + final pskController = controllers[1]; + return StatefulBuilder( + builder: (sheetContext, setSheetState) => DraggableScrollableSheet( + expand: false, + initialChildSize: 0.65, + minChildSize: 0.4, + maxChildSize: 0.95, + builder: (_, scrollController) => Column( + children: [ + BottomSheetHeader( + title: sheetContext.l10n.channels_editChannelTitle( + channel.index, ), - const SizedBox(height: 16), - TextField( - controller: pskController, - decoration: InputDecoration( - labelText: sheetContext.l10n.channels_pskHex, - border: const OutlineInputBorder(), - suffixIcon: IconButton( - icon: const Icon(Icons.casino), - tooltip: sheetContext.l10n.channels_generateRandomPsk, - onPressed: () { - final bytes = randomBytes(16); - pskController.text = Channel.formatPskHex(bytes); - }, - ), - ), - ), - const SizedBox(height: 16), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(sheetContext.l10n.channels_smazCompression), - value: smazEnabled, - onChanged: (value) => setSheetState(() { - smazEnabled = value; - if (smazEnabled) { - cyr2latEnabled = false; - } - }), - ), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text( - sheetContext.l10n.channels_cyr2latCompression, - ), - subtitle: Text( - sheetContext.l10n.channels_cyr2latCompressionDscr, - ), - value: cyr2latEnabled, - onChanged: (value) => setSheetState(() { - cyr2latEnabled = value; - if (cyr2latEnabled) { - smazEnabled = false; - } - }), - ), - if (cyr2latEnabled) ...[ - Padding( - padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), - child: DropdownButtonFormField( - initialValue: selectedCyr2LatProfileId, + ), + Expanded( + child: ListView( + controller: scrollController, + padding: const EdgeInsets.symmetric(horizontal: 16), + children: [ + const SizedBox(height: 8), + TextField( + controller: nameController, decoration: InputDecoration( - labelText: sheetContext - .l10n - .channels_cyr2latSettingsSubheading, + labelText: sheetContext.l10n.channels_channelName, border: const OutlineInputBorder(), ), - items: appSettingsService.settings.cyr2latProfiles - .map((profile) { - return DropdownMenuItem( - value: profile.id, - child: Text(profile.name), + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter( + maxRadioNameBytes, + ), + ], + ), + const SizedBox(height: 16), + TextField( + controller: pskController, + decoration: InputDecoration( + labelText: sheetContext.l10n.channels_pskHex, + border: const OutlineInputBorder(), + suffixIcon: IconButton( + icon: const Icon(Icons.casino), + tooltip: + sheetContext.l10n.channels_generateRandomPsk, + onPressed: () { + final bytes = randomBytes(16); + pskController.text = Channel.formatPskHex( + bytes, ); - }) - .toList(), + }, + ), + ), + ), + const SizedBox(height: 16), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text( + sheetContext.l10n.channels_smazCompression, + ), + value: smazEnabled, onChanged: (value) => setSheetState(() { - selectedCyr2LatProfileId = value; + smazEnabled = value; + if (smazEnabled) { + cyr2latEnabled = false; + } }), ), - ), - ], - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(sheetContext.l10n.urlImage_enable), - value: urlImagesEnabled, - onChanged: (value) => - setSheetState(() => urlImagesEnabled = value), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text( + sheetContext.l10n.channels_cyr2latCompression, + ), + subtitle: Text( + sheetContext.l10n.channels_cyr2latCompressionDscr, + ), + value: cyr2latEnabled, + onChanged: (value) => setSheetState(() { + cyr2latEnabled = value; + if (cyr2latEnabled) { + smazEnabled = false; + } + }), + ), + if (cyr2latEnabled) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), + child: DropdownButtonFormField( + initialValue: selectedCyr2LatProfileId, + decoration: InputDecoration( + labelText: sheetContext + .l10n + .channels_cyr2latSettingsSubheading, + border: const OutlineInputBorder(), + ), + items: appSettingsService.settings.cyr2latProfiles + .map((profile) { + return DropdownMenuItem( + value: profile.id, + child: Text(profile.name), + ); + }) + .toList(), + onChanged: (value) => setSheetState(() { + selectedCyr2LatProfileId = value; + }), + ), + ), + ], + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(sheetContext.l10n.urlImage_enable), + value: urlImagesEnabled, + onChanged: (value) => + setSheetState(() => urlImagesEnabled = value), + ), + const SizedBox(height: 24), + ], ), - const SizedBox(height: 24), - ], - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: Row( - children: [ - Expanded( - child: OutlinedButton( - onPressed: () => Navigator.pop(sheetContext), - child: Text(sheetContext.l10n.common_cancel), - ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - onPressed: () async { - final name = nameController.text.trim(); - final pskHex = pskController.text.trim(); + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => Navigator.pop(sheetContext), + child: Text(sheetContext.l10n.common_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + onPressed: () async { + final name = nameController.text.trim(); + final pskHex = pskController.text.trim(); + if (name.isEmpty) { + showDismissibleSnackBar( + sheetContext, + content: Text( + sheetContext.l10n.channels_enterChannelName, + ), + ); + return; + } - Uint8List psk; - try { - psk = Channel.parsePskHex(pskHex); - } on FormatException { - showDismissibleSnackBar( - sheetContext, - content: Text( - sheetContext.l10n.channels_pskMustBe32Hex, - ), - ); - return; - } + Uint8List psk; + try { + psk = Channel.parsePskHex(pskHex); + } on FormatException { + showDismissibleSnackBar( + sheetContext, + content: Text( + sheetContext.l10n.channels_pskMustBe32Hex, + ), + ); + return; + } - Navigator.pop(sheetContext); - try { - await connector.setChannel( - channel.index, - name, - psk, - ); - await connector.setChannelSmazEnabled( - channel.index, - smazEnabled, - ); - await connector.setChannelCyr2LatEnabled( - channel.index, - cyr2latEnabled, - ); - await connector.setChannelUrlImagesEnabled( - channel.index, - urlImagesEnabled, - ); - await connector.setChannelCyr2LatProfileId( - channel.index, - selectedCyr2LatProfileId, - ); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelUpdated(name), - ), - ); - } catch (e, st) { - debugPrint(st.toString()); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text( - context.l10n.channels_channelUpdateFailed('$e'), - ), - ); - } - }, - child: Text(sheetContext.l10n.common_save), - ), + Navigator.pop(sheetContext); + try { + await connector.setChannel( + channel.index, + name, + psk, + ); + await connector.setChannelSmazEnabled( + channel.index, + smazEnabled, + ); + await connector.setChannelCyr2LatEnabled( + channel.index, + cyr2latEnabled, + ); + await connector.setChannelUrlImagesEnabled( + channel.index, + urlImagesEnabled, + ); + await connector.setChannelCyr2LatProfileId( + channel.index, + selectedCyr2LatProfileId, + ); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelUpdated(name), + ), + ); + } catch (e, st) { + debugPrint(st.toString()); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + context.l10n.channels_channelUpdateFailed( + '$e', + ), + ), + ); + } + }, + child: Text(sheetContext.l10n.common_save), + ), + ), + ], ), - ], - ), + ), + ], ), - ], - ), - ), + ), + ); + }, ), ); } @@ -1852,12 +1923,15 @@ class _ChannelsScreenState extends State } on ProviderNotFoundException { imageStore = null; } + final channelLabel = channel.name.isEmpty + ? context.l10n.channels_channelIndex(channel.index) + : channel.name; showDialog( context: context, builder: (dialogContext) => AlertDialog( title: Text(dialogContext.l10n.channels_deleteChannel), content: Text( - dialogContext.l10n.channels_deleteChannelConfirm(channel.name), + dialogContext.l10n.channels_deleteChannelConfirm(channelLabel), ), actions: [ TextButton( @@ -1878,7 +1952,7 @@ class _ChannelsScreenState extends State showDismissibleSnackBar( context, content: Text( - context.l10n.channels_channelDeleted(channel.name), + context.l10n.channels_channelDeleted(channelLabel), ), ); } catch (e, st) { @@ -1887,7 +1961,7 @@ class _ChannelsScreenState extends State showDismissibleSnackBar( context, content: Text( - context.l10n.channels_channelDeleteFailed(channel.name), + context.l10n.channels_channelDeleteFailed(channelLabel), ), ); @@ -2187,3 +2261,35 @@ class _ChannelsScreenState extends State ); } } + +/// Owns a sheet's [TextEditingController]s so they are disposed together with +/// the sheet's widgets (after its exit animation) instead of being leaked. +class _SheetTextControllers extends StatefulWidget { + final List initialTexts; + final Widget Function(List controllers) builder; + + const _SheetTextControllers({ + required this.initialTexts, + required this.builder, + }); + + @override + State<_SheetTextControllers> createState() => _SheetTextControllersState(); +} + +class _SheetTextControllersState extends State<_SheetTextControllers> { + late final List _controllers = [ + for (final text in widget.initialTexts) TextEditingController(text: text), + ]; + + @override + void dispose() { + for (final controller in _controllers) { + controller.dispose(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.builder(_controllers); +} diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e5d71c3f..c0c503b4 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -24,22 +24,21 @@ import '../models/channel_message.dart'; import '../models/contact.dart'; import '../l10n/contact_localization.dart'; import '../models/message.dart'; -import '../models/translation_support.dart'; import '../services/app_settings_service.dart'; import '../services/chat_text_scale_service.dart'; import '../services/path_history_service.dart'; import '../services/translation_service.dart'; +import '../widgets/chat_composer.dart'; +import '../widgets/chat_send_pipeline.dart'; import '../widgets/chat_zoom_wrapper.dart'; -import '../widgets/byte_count_input.dart'; -import '../widgets/marker_label_dialog.dart'; +import '../widgets/message_bubble_frame.dart'; +import '../widgets/reaction_chips.dart'; import '../widgets/chat_day_separator.dart'; import 'channel_message_path_screen.dart'; import 'map_screen.dart'; import '../widgets/emoji_picker.dart'; import '../widgets/gif_message.dart'; import '../widgets/jump_to_bottom_button.dart'; -import '../widgets/gif_picker.dart'; -import '../widgets/message_translation_button.dart'; import '../widgets/routing_sheet.dart'; import '../widgets/radio_stats_entry.dart'; import '../widgets/sync_progress_overlay.dart'; @@ -83,14 +82,18 @@ class _ChatScreenState extends State { MeshCoreConnector? _connector; Message? _pendingUnreadScrollTarget; String? _unreadDividerMessageId; - DateTime? _lastTextSendAt; - // True while a send is awaiting outgoing translation, so a second tap - // can't send the same text again. - bool _isSendingText = false; + final ChatSendGuard _sendGuard = ChatSendGuard(); + + /// Contact keys of the chat screens currently on the navigation stack, in + /// push order. A room chat can push a nested ChatScreen for one of its + /// posters; when that one is popped, the room underneath must become the + /// active conversation again rather than none at all. + static final List _activeContactStack = []; @override void initState() { super.initState(); + _activeContactStack.add(widget.contact.publicKeyHex); _textFieldFocusNode.addListener(_onTextFieldFocusChange); _scrollController.onScrollNearTop = _loadOlderMessages; _scrollController.showJumpToBottom.addListener(_clearDividerAtBottom); @@ -179,7 +182,16 @@ class _ChatScreenState extends State { @override void dispose() { - _connector?.setActiveContact(null); + final index = _activeContactStack.lastIndexOf(widget.contact.publicKeyHex); + final wasTop = index == _activeContactStack.length - 1; + if (index >= 0) _activeContactStack.removeAt(index); + if (wasTop) { + // Restore whichever chat is now on top (e.g. the room this nested chat + // was opened from), or clear when this was the only one. + _connector?.setActiveContact( + _activeContactStack.isEmpty ? null : _activeContactStack.last, + ); + } _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); _textFieldFocusNode.dispose(); @@ -212,15 +224,26 @@ class _ChatScreenState extends State { ContactRoutingSheet.show(context, contact: contact), child: Padding( padding: const EdgeInsets.symmetric(vertical: 6), - child: Text( - pathLabel, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - fontSize: 11, - fontWeight: FontWeight.normal, - decoration: TextDecoration.underline, - decorationStyle: TextDecorationStyle.dotted, - ), + child: Builder( + builder: (context) { + // Follows the chat text size, capped so the two-line + // title still fits the app bar. + final textScale = context + .select( + (service) => service.scale, + ) + .clamp(1.0, 1.3); + return Text( + pathLabel, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12 * textScale, + fontWeight: FontWeight.normal, + decoration: TextDecoration.underline, + decorationStyle: TextDecorationStyle.dotted, + ), + ); + }, ), ), ), @@ -478,363 +501,77 @@ class _ChatScreenState extends State { } Widget _buildInputBar(MeshCoreConnector connector) { - final maxBytes = maxContactMessageBytes(); - final scheme = Theme.of(context).colorScheme; - final settings = context.watch().settings; - return Container( - decoration: BoxDecoration( - color: scheme.surface, - border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), + final keyHex = widget.contact.publicKeyHex; + final useEncoder = + connector.isContactSmazEnabled(keyHex) || + connector.isContactCyr2LatEnabled(keyHex); + return ChatComposer( + controller: _textController, + focusNode: _textFieldFocusNode, + maxBytes: maxContactMessageBytes(), + softLimitBytes: maxTextPayloadBytesAfterFullLengthAttempts, + softLimitNote: context.l10n.chat_longMessageRetryNote( + maxFullLengthTextAttempt + 1, ), - child: SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - 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.chat_shareMyLocation), - ], - ), - ), - ], - ); - if (!mounted || !menuContext.mounted) return; - if (selected == null) return; - switch (selected) { - case 'gif': - _showGifPicker(context); - break; - case 'send-my-location': - await _shareMyLocation( - context.read(), - ); - break; - } - }, - ); - }, - ), - if (settings.translationEnabled) - MessageTranslationButton( - enabled: settings.composerTranslationEnabled, - languageCode: settings.translationTargetLanguageCode, - onPressed: _showTranslationOptions, - ), - // No image button here: the image wire format is GRP_DATA, a - // channel primitive with no DM equivalent (see the note at the - // top of this file). - Expanded( - child: ValueListenableBuilder( - valueListenable: _textController, - builder: (context, value, child) { - final gifId = GifHelper.parseGif(value.text); - if (gifId != null) { - return Focus( - autofocus: true, - onKeyEvent: (node, event) { - if (event is KeyDownEvent && - (event.logicalKey == LogicalKeyboardKey.enter || - event.logicalKey == - LogicalKeyboardKey.numpadEnter)) { - _sendMessage(connector); - return KeyEventResult.handled; - } - return KeyEventResult.ignored; - }, - child: Row( - children: [ - Expanded( - child: ClipRRect( - borderRadius: BorderRadius.circular(12), - child: GifMessage( - url: - 'https://media.giphy.com/media/$gifId/giphy.gif', - backgroundColor: - scheme.surfaceContainerHighest, - fallbackTextColor: scheme.onSurface - .withValues(alpha: 0.6), - maxSize: 160, - ), - ), - ), - const SizedBox(width: 8), - IconButton( - icon: const Icon(Icons.close), - tooltip: context.l10n.chat_removeGif, - onPressed: () { - _textController.clear(); - _textFieldFocusNode.requestFocus(); - }, - ), - ], - ), - ); - } - return ByteCountedTextField( - maxBytes: maxBytes, - softLimitBytes: - maxTextPayloadBytesAfterFullLengthAttempts, - softLimitNote: context.l10n.chat_longMessageRetryNote( - maxFullLengthTextAttempt + 1, - ), - controller: _textController, - focusNode: _textFieldFocusNode, - hintText: context.l10n.chat_typeMessage, - onSubmitted: (_) => _sendMessage(connector), - encoder: - (connector.isContactSmazEnabled( - widget.contact.publicKeyHex, - ) || - connector.isContactCyr2LatEnabled( - widget.contact.publicKeyHex, - )) - ? (text) => connector.prepareContactOutboundText( - widget.contact, - text, - ) - : null, - decoration: InputDecoration( - hintText: context.l10n.chat_typeMessage, - 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, - ), - ), - ); - }, - ), - ), - const SizedBox(width: 6), - ValueListenableBuilder( - valueListenable: _textController, - builder: (context, value, _) { - final hasText = value.text.trim().isNotEmpty; - return AnimatedContainer( - duration: const Duration(milliseconds: 180), - curve: Curves.easeInOut, - child: IconButton.filled( - icon: const Icon(Icons.send, size: 20), - tooltip: context.l10n.chat_sendMessageTo( - _resolveContact(connector).name, - ), - style: IconButton.styleFrom( - backgroundColor: hasText - ? scheme.primary - : scheme.surfaceContainerHighest, - foregroundColor: hasText - ? scheme.onPrimary - : scheme.onSurfaceVariant, - minimumSize: const Size(40, 40), - shape: const CircleBorder(), - ), - onPressed: hasText - ? () { - HapticFeedback.lightImpact(); - _sendMessage(connector); - } - : null, - ), - ); - }, - ), - ], - ), + encoder: useEncoder + ? (text) => connector.prepareContactOutboundText(widget.contact, text) + : null, + onSend: () => _sendMessage(connector), + sendTooltip: context.l10n.chat_sendMessageTo( + _resolveContact(connector).name, + ), + // No image action here: the image wire format is GRP_DATA, a channel + // primitive with no DM equivalent (see the note at the top of this + // file). + actionsBuilder: () => [ + ChatComposerAction( + id: 'gif', + icon: Icons.gif_box, + label: context.l10n.chat_sendGif, ), - ), - ); - } - - void _showGifPicker(BuildContext context) { - showModalBottomSheet( - context: context, - isScrollControlled: true, - builder: (context) => GifPicker( - onGifSelected: (gifId) { - _textController.text = GifHelper.encodeGif(gifId); - }, - ), - ); - } - - Future _showTranslationOptions() async { - final settingsService = context.read(); - final settings = settingsService.settings; - await showMessageTranslationSheet( - context: context, - enabled: settings.composerTranslationEnabled, - selectedLanguageCode: settings.translationTargetLanguageCode, - onEnabledChanged: settingsService.setComposerTranslationEnabled, - onLanguageSelected: settingsService.setTranslationTargetLanguageCode, + ChatComposerAction( + id: 'send-my-location', + icon: Icons.my_location, + label: context.l10n.chat_shareMyLocation, + ), + ], + onAction: (action) { + if (!mounted) return; + switch (action) { + case 'gif': + showChatGifPicker(context, _textController); + case 'send-my-location': + _shareMyLocation(context.read()); + } + }, ); } /// Shares the radio's own position as a map marker. Shares the text send /// guard and cooldown so it can't race or flood alongside typed messages. - Future _shareMyLocation(MeshCoreConnector connector) async { - final lat = connector.selfLatitude; - final lon = connector.selfLongitude; - if (!hasShareableLocation(lat, lon)) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_noRadioLocation), - ); - return; - } - final selfName = connector.selfName; - final label = await showMarkerLabelDialog( - context, - lat: lat!, - lon: lon!, - defaultLabel: selfName != null && selfName.isNotEmpty - ? selfName - : context.l10n.map_sharedPin, - flags: 'poi', - confirmText: context.l10n.common_share, + Future _shareMyLocation(MeshCoreConnector connector) { + return shareMyLocationMarker( + context: context, + connector: connector, + guard: _sendGuard, + send: (markerText) => + connector.sendMessage(_resolveContact(connector), markerText), ); - if (label == null || label.isEmpty || !mounted || _isSendingText) return; - final now = DateTime.now(); - if (_lastTextSendAt != null && - now.difference(_lastTextSendAt!) < const Duration(seconds: 1)) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_sendCooldown), - ); - return; - } - _lastTextSendAt = now; - _isSendingText = true; - try { - await connector.sendMessage( - _resolveContact(connector), - formatMarkerText(lat, lon, label, 'poi'), - ); - } catch (e) { - appLogger.warn('Sharing location failed: $e', tag: 'Chat'); - } finally { - _isSendingText = false; - } } - Future _sendMessage(MeshCoreConnector connector) async { - if (_isSendingText) return; - _isSendingText = true; - try { - await _sendMessageInner(connector); - } finally { - _isSendingText = false; - } + Future _sendMessage(MeshCoreConnector connector) { + return _sendGuard.runExclusive(() => _sendMessageInner(connector)); } Future _sendMessageInner(MeshCoreConnector connector) async { final text = _textController.text.trim(); if (text.isEmpty) return; + if (!_sendGuard.checkCooldown(context)) return; - final now = DateTime.now(); - if (_lastTextSendAt != null && - now.difference(_lastTextSendAt!) < const Duration(seconds: 1)) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_sendCooldown), - ); - return; - } - _lastTextSendAt = now; + final translation = await translateOutgoingText(context, text); + if (translation == null || !mounted) return; + var outgoingText = translation.text; - final settings = context.read().settings; - final translationService = context.read(); - var outgoingText = text; - String? originalText; - String? translatedLanguageCode; - String? translationModelId; - if (settings.translationEnabled) { - final targetLanguageCode = translationService.resolvedTargetLanguageCode( - Localizations.localeOf(context).languageCode, - ); - if (translationService.shouldTranslateOutgoing( - text: text, - targetLanguageCode: targetLanguageCode, - )) { - final result = await translationService.translateOutgoingText( - text: text, - targetLanguageCode: targetLanguageCode, - ); - if (!mounted) return; - if (result != null && - result.status == MessageTranslationStatus.completed && - result.translatedText.isNotEmpty) { - outgoingText = result.translatedText; - originalText = text; - translatedLanguageCode = result.targetLanguageCode; - translationModelId = result.modelId; - } - } - } final maxBytes = maxContactMessageBytes(); final outboundText = connector.prepareContactOutboundText( _resolveContact(connector), @@ -868,36 +605,23 @@ class _ChatScreenState extends State { connector.sendMessage( _resolveContact(connector), outgoingText, - originalText: originalText, - translatedLanguageCode: translatedLanguageCode, - translationModelId: translationModelId, + originalText: translation.originalText, + translatedLanguageCode: translation.languageCode, + translationModelId: translation.modelId, ); + // Only a dispatched send starts the cooldown. + _sendGuard.markDispatched(); } Future _confirmClearChat( BuildContext context, MeshCoreConnector connector, ) async { - final confirmed = await showDialog( - context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.contact_clearChat), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext, false), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () => Navigator.pop(dialogContext, true), - style: TextButton.styleFrom( - foregroundColor: Theme.of(context).colorScheme.error, - ), - child: Text(context.l10n.common_delete), - ), - ], - ), + final confirmed = await confirmClearChat( + context, + message: context.l10n.chat_clearChatConfirm, ); - if (confirmed == true) { + if (confirmed) { connector.clearMessagesForContact(widget.contact); } } @@ -1020,7 +744,9 @@ class _ChatScreenState extends State { ); connector.ensureContactSmazSettingLoaded(widget.contact.publicKeyHex); connector.ensureContactCyr2LatSettingLoaded(widget.contact.publicKeyHex); - final contact = widget.contact; + // The live contact carries the current telemetry flags; widget.contact + // is the snapshot this screen was opened with. + final contact = _resolveContact(connector); bool smazEnabled = connector.isContactSmazEnabled(contact.publicKeyHex); bool cyr2latEnabled = connector.isContactCyr2LatEnabled( contact.publicKeyHex, @@ -1034,6 +760,18 @@ class _ChatScreenState extends State { bool teleBaseEnabled = contact.teleBaseEnabled; bool teleLocEnabled = contact.teleLocEnabled; bool teleEnvEnabled = contact.teleEnvEnabled; + // Each toggle is committed immediately, like the compression switches, + // so dismissing the dialog by tapping outside keeps the change. All three + // flags are sent every time so overlapping writes can't undo each other. + void commitTelemetryFlags() { + connector.setContactFlags( + contact, + teleBase: teleBaseEnabled, + teleLoc: teleLocEnabled, + teleEnv: teleEnvEnabled, + ); + } + showDialog( context: context, builder: (context) => StatefulBuilder( @@ -1147,6 +885,7 @@ class _ChatScreenState extends State { value: teleBaseEnabled, onChanged: (value) { setDialogState(() => teleBaseEnabled = value); + commitTelemetryFlags(); }, ), const Divider(height: 8), @@ -1157,6 +896,7 @@ class _ChatScreenState extends State { value: teleLocEnabled, onChanged: (value) { setDialogState(() => teleLocEnabled = value); + commitTelemetryFlags(); }, ), const Divider(height: 8), @@ -1167,6 +907,7 @@ class _ChatScreenState extends State { value: teleEnvEnabled, onChanged: (value) { setDialogState(() => teleEnvEnabled = value); + commitTelemetryFlags(); }, ), ], @@ -1174,15 +915,7 @@ class _ChatScreenState extends State { ), actions: [ TextButton( - onPressed: () { - connector.setContactFlags( - contact, - teleBase: teleBaseEnabled, - teleLoc: teleLocEnabled, - teleEnv: teleEnvEnabled, - ); - Navigator.pop(context); - }, + onPressed: () => Navigator.pop(context), child: Text(context.l10n.common_close), ), ], @@ -1341,7 +1074,7 @@ class _ChatScreenState extends State { title: Text(context.l10n.common_copy), onTap: () { Navigator.pop(sheetContext); - _copyMessageText(message.text); + copyChatMessageText(context, message.text); }, ), if (canTranslateMessage) @@ -1409,17 +1142,6 @@ 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), - ); - } - Future _deleteMessage(Message message) async { await context.read().deleteMessage(message); if (!mounted) return; @@ -1503,40 +1225,15 @@ class _MessageBubble extends StatelessWidget { (connector) => connector.isContactUrlImagesEnabled(sourceId), ); - // Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk. - final bubbleColor = isFailed - ? scheme.errorContainer - : isOutgoing - ? MeshPalette.me - : scheme.surfaceContainerLow; - final bubbleBorder = isFailed - ? scheme.error - : isOutgoing - ? MeshPalette.meBorder - : scheme.outlineVariant; - final textColor = isFailed - ? scheme.onErrorContainer - : isOutgoing - ? MeshPalette.meInk - : scheme.onSurface; - final metaColor = textColor.withValues(alpha: 0.65); + final colors = MessageBubbleColors.of( + scheme, + isOutgoing: isOutgoing, + isFailed: isFailed, + ); + final textColor = colors.text; + final metaColor = colors.meta; const bodyFontSize = 14.0; - // Asymmetric radius: outgoing — top-left large, others also large; outgoing bottom-right tight. - final borderRadius = isOutgoing - ? const BorderRadius.only( - topLeft: Radius.circular(MeshRadii.lg), - topRight: Radius.circular(MeshRadii.lg), - bottomLeft: Radius.circular(MeshRadii.lg), - bottomRight: Radius.circular(MeshRadii.xs), - ) - : const BorderRadius.only( - topLeft: Radius.circular(MeshRadii.xs), - topRight: Radius.circular(MeshRadii.lg), - bottomLeft: Radius.circular(MeshRadii.lg), - bottomRight: Radius.circular(MeshRadii.lg), - ); - // Do not strip room-server author bytes here: the parser stores them in // fourByteRoomContactKey, so message.text is safe to render as-is. final messageText = message.text; @@ -1597,21 +1294,11 @@ class _MessageBubble extends StatelessWidget { const SizedBox(width: 6), ], Flexible( - child: Container( - padding: gifId != null - ? const EdgeInsets.all(4) - : const EdgeInsets.symmetric( - horizontal: 12, - vertical: 8, - ), - constraints: BoxConstraints( - maxWidth: constraints.maxWidth * 0.72, - ), - decoration: BoxDecoration( - color: bubbleColor, - borderRadius: borderRadius, - border: Border.all(color: bubbleBorder, width: 1), - ), + child: MessageBubbleFrame( + isOutgoing: isOutgoing, + isFailed: isFailed, + compact: gifId != null, + maxWidth: constraints.maxWidth, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -1627,9 +1314,9 @@ class _MessageBubble extends StatelessWidget { child: Text( senderName, style: MeshTheme.mono( - fontSize: 11, + fontSize: 13 * textScale, fontWeight: FontWeight.w700, - color: _colorForName(senderName), + color: senderNameColor(senderName), ), ), ), @@ -1725,7 +1412,7 @@ class _MessageBubble extends StatelessWidget { context.l10n.urlImage_possible, style: TextStyle( color: metaColor, - fontSize: 11 * textScale, + fontSize: 12 * textScale, ), ), ), @@ -1749,7 +1436,7 @@ class _MessageBubble extends StatelessWidget { .maxMessageRetries, ), style: MeshTheme.mono( - fontSize: 9.5 * textScale, + fontSize: 12 * textScale, color: metaColor, ), ), @@ -1801,7 +1488,7 @@ class _MessageBubble extends StatelessWidget { const SizedBox(width: 2), Icon( Icons.speed, - size: 10 * textScale, + size: 14 * textScale, color: isOutgoing ? metaColor : scheme.tertiary, @@ -1809,7 +1496,7 @@ class _MessageBubble extends StatelessWidget { Text( '${(message.tripTimeMs! / 1000).toStringAsFixed(1)}s', style: MeshTheme.mono( - fontSize: 11 * textScale, + fontSize: 12 * textScale, color: isOutgoing ? metaColor : scheme.tertiary, @@ -1831,7 +1518,13 @@ class _MessageBubble extends StatelessWidget { const SizedBox(height: 4), Padding( padding: EdgeInsets.only(left: isOutgoing ? 0 : 42), - child: _buildReactionsDisplay(context, message, scheme), + child: ReactionChips( + reactions: message.reactions, + statuses: message.reactionStatuses, + onRetry: onRetryReaction == null + ? null + : (emoji) => onRetryReaction!(message, emoji), + ), ), ], ], @@ -1905,104 +1598,7 @@ class _MessageBubble extends StatelessWidget { ); } - Widget _buildReactionsDisplay( - BuildContext context, - Message message, - ColorScheme scheme, - ) { - return Wrap( - spacing: 6, - runSpacing: 6, - children: message.reactions.entries.map((entry) { - final emoji = entry.key; - final count = entry.value.length; - final status = message.reactionStatuses[emoji]; - final isPending = - status == MessageStatus.pending || status == MessageStatus.sent; - final isFailed = status == MessageStatus.failed; - - return GestureDetector( - onTap: isFailed && onRetryReaction != null - ? () => onRetryReaction!(message, emoji) - : null, - child: Opacity( - opacity: isPending ? 0.5 : 1.0, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: isFailed - ? scheme.errorContainer - : scheme.surfaceContainerHigh, - borderRadius: BorderRadius.circular(MeshRadii.pill), - border: Border.all( - color: isFailed ? scheme.error : scheme.outlineVariant, - width: 1, - ), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - emoji, - style: MeshTheme.emoji(fontSize: 16), - textHeightBehavior: const TextHeightBehavior( - applyHeightToFirstAscent: false, - applyHeightToLastDescent: false, - ), - ), - if (count > 1) ...[ - const SizedBox(width: 4), - Text( - '$count', - style: MeshTheme.mono( - fontSize: 11, - fontWeight: FontWeight.w700, - color: scheme.onSurface, - ), - ), - ], - if (isPending) ...[ - const SizedBox(width: 2), - SizedBox( - width: 8, - height: 8, - child: CircularProgressIndicator( - strokeWidth: 1.5, - color: scheme.primary, - ), - ), - ], - if (isFailed) ...[ - const SizedBox(width: 2), - Icon(Icons.replay, size: 10, color: scheme.error), - ], - ], - ), - ), - ), - ); - }).toList(), - ); - } - Widget _buildAvatar(String senderName) { return AvatarCircle(name: senderName, size: 32); } } - -/// Deterministic name-to-hue mapping consistent with [AvatarCircle]. -Color _colorForName(String name) { - const hues = [ - MeshPalette.blue, - MeshPalette.magenta, - MeshPalette.signal, - MeshPalette.warn, - Color(0xFF8FA8F0), - Color(0xFF6FD9CE), - ]; - var h = 0; - for (final c in name.codeUnits) { - h = (h * 31 + c) & 0x7fffffff; - } - return hues[h % hues.length]; -} diff --git a/lib/screens/community_qr_scanner_screen.dart b/lib/screens/community_qr_scanner_screen.dart index 248f8a47..8f720729 100644 --- a/lib/screens/community_qr_scanner_screen.dart +++ b/lib/screens/community_qr_scanner_screen.dart @@ -32,6 +32,24 @@ class _CommunityQrScannerScreenState extends State { final CommunityStore _communityStore = CommunityStore(); bool _isProcessing = false; + /// QR data whose join prompt was just cancelled. Ignored for a short + /// cooldown so a code still in view doesn't immediately re-prompt. + String? _cancelledData; + DateTime? _cancelledAt; + static const Duration _cancelCooldown = Duration(seconds: 3); + + void _markCancelled(String data) { + _cancelledData = data; + _cancelledAt = DateTime.now(); + } + + bool _isRecentlyCancelled(String data) { + final at = _cancelledAt; + return data == _cancelledData && + at != null && + DateTime.now().difference(at) < _cancelCooldown; + } + @override Widget build(BuildContext context) { return Scaffold( @@ -40,87 +58,21 @@ class _CommunityQrScannerScreenState extends State { centerTitle: true, ), body: _isProcessing - ? Container( - color: Theme.of(context).colorScheme.surface, - child: const Center(child: CircularProgressIndicator()), - ) + ? const QrScannerProcessingBody() : QrScannerWidget( onScanned: (data) => _handleScannedData(context, data), - validator: Community.isValidQrData, - onValidationFailed: (_) => _showInvalidQrError(context), + validator: (data) => + Community.isValidQrData(data) && !_isRecentlyCancelled(data), + onValidationFailed: (data) { + if (_isRecentlyCancelled(data)) return; + _showInvalidQrError(context); + }, instructions: context.l10n.community_scanInstructions, - overlay: _buildThemedOverlay(context), + themed: true, ), ); } - Widget _buildThemedOverlay(BuildContext context) { - return Stack( - fit: StackFit.expand, - children: [ - // Dark semi-transparent background with cutout - ColorFiltered( - colorFilter: ColorFilter.mode( - Colors.black.withValues(alpha: 0.5), - BlendMode.srcOut, - ), - child: Stack( - fit: StackFit.expand, - children: [ - Container( - decoration: const BoxDecoration( - color: Colors.black, - backgroundBlendMode: BlendMode.dstOut, - ), - ), - Center( - child: Container( - height: 250, - width: 250, - decoration: BoxDecoration( - color: Colors.red, - borderRadius: BorderRadius.circular(16), - ), - ), - ), - ], - ), - ), - // Corner brackets on top - const ScannerCornerOverlay( - scanWindowSize: 250, - borderColor: MeshPalette.blue, - borderWidth: 2, - cornerLength: 24, - ), - // Instructions pill below the scan window - Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const SizedBox(height: 250 + 24), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 10, - ), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.72), - borderRadius: BorderRadius.circular(MeshRadii.pill), - ), - child: Text( - context.l10n.community_scanInstructions, - style: const TextStyle(color: MeshPalette.ink2, fontSize: 13), - textAlign: TextAlign.center, - ), - ), - ], - ), - ), - ], - ); - } - Future _handleScannedData(BuildContext context, String data) async { if (_isProcessing) return; @@ -130,6 +82,9 @@ class _CommunityQrScannerScreenState extends State { final connector = context.read(); _communityStore.setPublicKeyHex = connector.selfPublicKeyHex; + // Set when this screen is about to pop: keep the spinner up so the camera + // doesn't restart on a closing route and detect the code again. + var leaving = false; try { // Parse the community data @@ -142,14 +97,15 @@ class _CommunityQrScannerScreenState extends State { if (existing != null) { if (context.mounted) { - _showAlreadyMemberDialog(context, existing); + leaving = await _showAlreadyMemberDialog(context, existing); + if (!leaving) _markCancelled(data); } return; } // Show confirmation dialog if (context.mounted) { - await _showJoinConfirmationDialog(context, community); + leaving = await _showJoinConfirmationDialog(context, community, data); } } catch (e) { if (context.mounted) { @@ -160,7 +116,7 @@ class _CommunityQrScannerScreenState extends State { ); } } finally { - if (mounted) { + if (mounted && !leaving) { setState(() { _isProcessing = false; }); @@ -169,16 +125,15 @@ class _CommunityQrScannerScreenState extends State { } void _showInvalidQrError(BuildContext context) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.community_invalidQrCode), - backgroundColor: MeshPalette.warn, - duration: const Duration(seconds: 2), - ); + showInvalidQrSnackBar(context, context.l10n.community_invalidQrCode); } - void _showAlreadyMemberDialog(BuildContext context, Community community) { - showMeshSheet( + /// Returns true when the screen popped itself (OK pressed). + Future _showAlreadyMemberDialog( + BuildContext context, + Community community, + ) async { + final ok = await showMeshSheet( context, builder: (sheetContext) { final sheetScheme = Theme.of(sheetContext).colorScheme; @@ -215,9 +170,11 @@ class _CommunityQrScannerScreenState extends State { ), ), Text( - 'ID: ${community.shortCommunityId}...', + context.l10n.community_shortId( + community.shortCommunityId, + ), style: MeshTheme.mono( - fontSize: 11.5, + fontSize: 13, color: sheetScheme.onSurfaceVariant, ), ), @@ -230,10 +187,7 @@ class _CommunityQrScannerScreenState extends State { Padding( padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), child: FilledButton( - onPressed: () { - Navigator.pop(sheetContext); - Navigator.pop(context); - }, + onPressed: () => Navigator.pop(sheetContext, true), child: Text(context.l10n.common_ok), ), ), @@ -241,11 +195,16 @@ class _CommunityQrScannerScreenState extends State { ); }, ); + if (ok != true || !context.mounted) return false; + Navigator.pop(context); + return true; } - Future _showJoinConfirmationDialog( + /// Returns true when the community was joined and the screen popped. + Future _showJoinConfirmationDialog( BuildContext context, Community community, + String data, ) async { bool addPublicChannel = true; final completer = Completer(); @@ -289,9 +248,11 @@ class _CommunityQrScannerScreenState extends State { ), ), Text( - 'ID: ${community.shortCommunityId}...', + context.l10n.community_shortId( + community.shortCommunityId, + ), style: MeshTheme.mono( - fontSize: 11.5, + fontSize: 13, color: joinScheme.onSurfaceVariant, ), ), @@ -353,14 +314,16 @@ class _CommunityQrScannerScreenState extends State { final result = await completer.future; if (result && context.mounted) { - await _joinCommunity(context, community, addPublicChannel); - } else if (context.mounted) { - // User cancelled - go back - Navigator.pop(context); + return _joinCommunity(context, community, addPublicChannel); } + // User cancelled: stay on the scanner and resume scanning, ignoring this + // code briefly so it doesn't re-prompt while still in view. + _markCancelled(data); + return false; } - Future _joinCommunity( + /// Returns true when the screen popped itself. + Future _joinCommunity( BuildContext context, Community community, bool addPublicChannel, @@ -409,7 +372,9 @@ class _CommunityQrScannerScreenState extends State { // Return to previous screen Navigator.pop(context, community); + return true; } + return false; } int? _findNextAvailableChannelIndex(MeshCoreConnector connector) { diff --git a/lib/screens/companion_radio_stats_screen.dart b/lib/screens/companion_radio_stats_screen.dart index 748f4a20..3bf6f354 100644 --- a/lib/screens/companion_radio_stats_screen.dart +++ b/lib/screens/companion_radio_stats_screen.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/models/companion_radio_stats.dart'; @@ -328,8 +329,11 @@ class _NoiseChartPainter extends CustomPainter { @override bool shouldRepaint(covariant _NoiseChartPainter oldDelegate) { - return oldDelegate.samples.length != samples.length || - oldDelegate.colorScheme != colorScheme; + // Once the ring buffer is full its length stays constant, so compare the + // contents (samples is a fresh copy per build). + return !listEquals(oldDelegate.samples, samples) || + oldDelegate.colorScheme != colorScheme || + oldDelegate.textTheme != textTheme; } TextPainter _yAxisLabel(double v) { diff --git a/lib/screens/contact_qr_scanner_screen.dart b/lib/screens/contact_qr_scanner_screen.dart index 87348c0f..02bf70c0 100644 --- a/lib/screens/contact_qr_scanner_screen.dart +++ b/lib/screens/contact_qr_scanner_screen.dart @@ -44,10 +44,7 @@ class _ContactQrScannerScreenState extends State { ], ), body: _isProcessing - ? Container( - color: Theme.of(context).colorScheme.surface, - child: const Center(child: CircularProgressIndicator()), - ) + ? const QrScannerProcessingBody() : _importFailed ? _buildImportFailed(context) : QrScannerWidget( @@ -55,7 +52,7 @@ class _ContactQrScannerScreenState extends State { validator: (data) => parseContactQr(data) != null, onValidationFailed: (_) => _showInvalidQrError(), instructions: context.l10n.contacts_scanQrInstructions, - overlay: _buildThemedOverlay(context), + themed: true, ), ); } @@ -90,73 +87,6 @@ class _ContactQrScannerScreenState extends State { ); } - Widget _buildThemedOverlay(BuildContext context) { - return Stack( - fit: StackFit.expand, - children: [ - // Dark semi-transparent background with cutout - ColorFiltered( - colorFilter: ColorFilter.mode( - Colors.black.withValues(alpha: 0.5), - BlendMode.srcOut, - ), - child: Stack( - fit: StackFit.expand, - children: [ - Container( - decoration: const BoxDecoration( - color: Colors.black, - backgroundBlendMode: BlendMode.dstOut, - ), - ), - Center( - child: Container( - height: 250, - width: 250, - decoration: BoxDecoration( - color: Colors.red, - borderRadius: BorderRadius.circular(16), - ), - ), - ), - ], - ), - ), - // Corner brackets on top - const ScannerCornerOverlay( - scanWindowSize: 250, - borderColor: MeshPalette.blue, - borderWidth: 2, - cornerLength: 24, - ), - // Instructions pill below the scan window - Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const SizedBox(height: 250 + 24), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 10, - ), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.72), - borderRadius: BorderRadius.circular(MeshRadii.pill), - ), - child: Text( - context.l10n.contacts_scanQrInstructions, - style: const TextStyle(color: MeshPalette.ink2, fontSize: 13), - textAlign: TextAlign.center, - ), - ), - ], - ), - ), - ], - ); - } - Future _pickFromGallery() async { if (_isProcessing) return; @@ -291,12 +221,7 @@ class _ContactQrScannerScreenState extends State { } void _showInvalidQrError() { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_invalidAdvertFormat), - backgroundColor: MeshPalette.warn, - duration: const Duration(seconds: 2), - ); + showInvalidQrSnackBar(context, context.l10n.contacts_invalidAdvertFormat); } void _showGalleryError() { diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index a5d205bc..e7f8f4b0 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -23,6 +23,7 @@ import '../utils/dialog_utils.dart'; import '../utils/disconnect_navigation_mixin.dart'; import '../utils/emoji_utils.dart'; import '../utils/route_transitions.dart'; +import '../widgets/contact_visuals.dart'; import '../widgets/list_filter_widget.dart'; import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; @@ -45,6 +46,17 @@ enum RoomLoginDestination { chat, management } enum ContactOperationType { import, export, zeroHopShare } +/// An export/import/share awaiting its generic OK/ERR ack. The timer drops +/// it if no ack arrives, so a stuck op can't consume a later unrelated ack. +class _PendingContactOperation { + final ContactOperationType type; + final Timer timeout; + + _PendingContactOperation(this.type, this.timeout); +} + +const Duration _contactOperationTimeout = Duration(seconds: 5); + class ContactsScreen extends StatefulWidget { final bool hideBackButton; @@ -63,7 +75,8 @@ class _ContactsScreenState extends State String _loadedGroupScopeKeyHex = ''; Timer? _searchDebounce; - final List _pendingOperations = []; + final List<_PendingContactOperation> _pendingOperations = []; + final DerivedListCache _filteredCache = DerivedListCache(); StreamSubscription? _frameSubscription; @@ -101,10 +114,86 @@ class _ContactsScreenState extends State _searchDebounce?.cancel(); _searchController.dispose(); _frameSubscription?.cancel(); + for (final op in _pendingOperations) { + op.timeout.cancel(); + } + _pendingOperations.clear(); _scopeSyncConnector?.removeListener(_handleConnectorScopeChange); super.dispose(); } + void _addPendingOperation(ContactOperationType type) { + late final _PendingContactOperation op; + op = _PendingContactOperation( + type, + Timer(_contactOperationTimeout, () { + if (!_pendingOperations.remove(op)) return; + _showOperationResult(type, success: false); + }), + ); + _pendingOperations.add(op); + } + + /// Removes the oldest pending operation of [type] (or of any type when + /// null) and returns its type, or null when nothing is pending. + ContactOperationType? _takePendingOperation([ContactOperationType? type]) { + final index = type == null + ? (_pendingOperations.isEmpty ? -1 : 0) + : _pendingOperations.indexWhere((op) => op.type == type); + if (index < 0) return null; + final op = _pendingOperations.removeAt(index); + op.timeout.cancel(); + return op.type; + } + + void _showOperationResult( + ContactOperationType type, { + required bool success, + }) { + if (!mounted) return; + final l10n = context.l10n; + final String message; + switch (type) { + case ContactOperationType.import: + message = success + ? l10n.contacts_contactImported + : l10n.contacts_contactImportFailed; + case ContactOperationType.zeroHopShare: + message = success + ? l10n.contacts_zeroHopContactAdvertSent + : l10n.contacts_zeroHopContactAdvertFailed; + case ContactOperationType.export: + message = success + ? l10n.contacts_contactAdvertCopied + : l10n.contacts_contactAdvertCopyFailed; + } + showDismissibleSnackBar(context, content: Text(message)); + } + + Future _sendSelfAdvert( + MeshCoreConnector connector, { + required bool flood, + }) async { + var sent = false; + try { + if (connector.isConnected) { + await connector.sendSelfAdvert(flood: flood); + sent = true; + } + } catch (e) { + appLogger.error('Self advert failed: $e', tag: 'ContactsScreen'); + } + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text( + sent + ? context.l10n.settings_advertisementSent + : context.l10n.contacts_advertFailed, + ), + ); + } + void _handleConnectorScopeChange() { final connector = _scopeSyncConnector; if (connector == null) return; @@ -182,12 +271,12 @@ class _ContactsScreenState extends State content: Text(context.l10n.contacts_invalidAdvertFormat), ); } - _pendingOperations.remove(ContactOperationType.export); + _takePendingOperation(ContactOperationType.export); return; } final hexString = pubKeyToHex(advertPacket); Clipboard.setData(ClipboardData(text: "meshcore://$hexString")); - _pendingOperations.remove(ContactOperationType.export); + _takePendingOperation(ContactOperationType.export); if (mounted) { showDismissibleSnackBar( context, @@ -199,50 +288,11 @@ class _ContactsScreenState extends State // Generic OK/ERR acks carry no command correlation, so consume only // the oldest pending operation per ack instead of clearing all. - if (code == respCodeOk) { + if (code == respCodeOk || code == respCodeErr) { if (!mounted) return; - if (_pendingOperations.isEmpty) return; - final op = _pendingOperations.removeAt(0); - switch (op) { - case ContactOperationType.import: - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactImported), - ); - case ContactOperationType.zeroHopShare: - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_zeroHopContactAdvertSent), - ); - case ContactOperationType.export: - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactAdvertCopied), - ); - } - } - - if (code == respCodeErr) { - if (!mounted) return; - if (_pendingOperations.isEmpty) return; - final op = _pendingOperations.removeAt(0); - switch (op) { - case ContactOperationType.import: - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactImportFailed), - ); - case ContactOperationType.zeroHopShare: - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_zeroHopContactAdvertFailed), - ); - case ContactOperationType.export: - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactAdvertCopyFailed), - ); - } + final op = _takePendingOperation(); + if (op == null) return; + _showOperationResult(op, success: code == respCodeOk); } } catch (e) { appLogger.error( @@ -256,11 +306,11 @@ class _ContactsScreenState extends State Future _contactExport(Uint8List pubKey) async { final connector = Provider.of(context, listen: false); final exportContactFrame = buildExportContactFrame(pubKey); - _pendingOperations.add(ContactOperationType.export); + _addPendingOperation(ContactOperationType.export); try { await connector.sendFrame(exportContactFrame, expectsGenericAck: true); } catch (e) { - _pendingOperations.remove(ContactOperationType.export); + _takePendingOperation(ContactOperationType.export); if (mounted) { showDismissibleSnackBar( context, @@ -273,14 +323,14 @@ class _ContactsScreenState extends State Future _contactZeroHop(Uint8List pubKey) async { final connector = Provider.of(context, listen: false); final exportContactZeroHopFrame = buildZeroHopContact(pubKey); - _pendingOperations.add(ContactOperationType.zeroHopShare); + _addPendingOperation(ContactOperationType.zeroHopShare); try { await connector.sendFrame( exportContactZeroHopFrame, expectsGenericAck: true, ); } catch (e) { - _pendingOperations.remove(ContactOperationType.zeroHopShare); + _takePendingOperation(ContactOperationType.zeroHopShare); if (mounted) { showDismissibleSnackBar( context, @@ -326,11 +376,11 @@ class _ContactsScreenState extends State } return; } - _pendingOperations.add(ContactOperationType.import); + _addPendingOperation(ContactOperationType.import); try { await connector.sendFrame(importContactFrame, expectsGenericAck: true); } catch (e) { - _pendingOperations.remove(ContactOperationType.import); + _takePendingOperation(ContactOperationType.import); if (mounted) { showDismissibleSnackBar( context, @@ -355,7 +405,7 @@ class _ContactsScreenState extends State child: Scaffold( appBar: AppBar( title: AppBarTitle(context.l10n.contacts_title), - automaticallyImplyLeading: false, + automaticallyImplyLeading: !widget.hideBackButton, bottom: const SyncProgressAppBarBottom(), actions: [ PopupMenuButton( @@ -410,13 +460,7 @@ class _ContactsScreenState extends State Text(context.l10n.contacts_zeroHopAdvert), ], ), - onTap: () => { - connector.sendSelfAdvert(flood: false), - showDismissibleSnackBar( - context, - content: Text(context.l10n.settings_advertisementSent), - ), - }, + onTap: () => _sendSelfAdvert(connector, flood: false), ), PopupMenuItem( child: Row( @@ -426,13 +470,7 @@ class _ContactsScreenState extends State Text(context.l10n.contacts_floodAdvert), ], ), - onTap: () => { - connector.sendSelfAdvert(flood: true), - showDismissibleSnackBar( - context, - content: Text(context.l10n.settings_advertisementSent), - ), - }, + onTap: () => _sendSelfAdvert(connector, flood: true), ), PopupMenuItem( child: Row( @@ -577,15 +615,106 @@ class _ContactsScreenState extends State } } - void _closeDropdownAndRun(BuildContext popupContext, VoidCallback action) { - final route = ModalRoute.of(popupContext); - if (route != null && route.isCurrent) { - Navigator.of(popupContext).pop(); + /// Dropdown value that opens the group-management sheet instead of + /// selecting a group. Contains a NUL so it can't collide with a name. + static const String _manageGroupsValue = '\u0000manage_groups'; + + void _showManageGroupsSheet(BuildContext context, List contacts) { + if (!_hasGroupStoreScope(context.read())) { + _showGroupsUnavailableMessage(context); + return; } - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) return; - action(); - }); + showMeshSheet( + context, + builder: (sheetContext) { + final l10n = sheetContext.l10n; + final scheme = Theme.of(sheetContext).colorScheme; + final groups = [ + ..._groups, + ]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + void closeThen(VoidCallback action) { + Navigator.pop(sheetContext); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + action(); + }); + } + + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.85, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BottomSheetHeader(title: l10n.contacts_manageGroups), + ListTile( + minTileHeight: 56, + leading: Icon(Icons.group_add, color: scheme.primary), + title: Text( + l10n.contacts_newGroup, + style: const TextStyle(fontSize: 16), + ), + onTap: () => + closeThen(() => _showGroupEditor(this.context, contacts)), + ), + if (groups.isNotEmpty) const Divider(height: 1), + Flexible( + child: ListView.builder( + shrinkWrap: true, + itemCount: groups.length, + itemBuilder: (context, index) { + final group = groups[index]; + return ListTile( + minTileHeight: 56, + leading: const Icon(Icons.group_outlined), + title: Text( + group.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 16), + ), + onTap: () => closeThen( + () => _showGroupEditor( + this.context, + contacts, + group: group, + ), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + tooltip: l10n.contacts_editGroup, + icon: const Icon(Icons.edit), + onPressed: () => closeThen( + () => _showGroupEditor( + this.context, + contacts, + group: group, + ), + ), + ), + IconButton( + tooltip: l10n.contacts_deleteGroup, + icon: Icon(Icons.delete, color: scheme.error), + onPressed: () => closeThen( + () => _confirmDeleteGroup(this.context, group), + ), + ), + ], + ), + ); + }, + ), + ), + const SizedBox(height: 8), + ], + ), + ); + }, + ); } Widget _buildFilterButton( @@ -615,7 +744,6 @@ class _ContactsScreenState extends State List contacts, List sortedGroups, ) { - final canManageGroups = _hasGroupStoreScope(connector); final selectedGroupName = _selectedGroupForName(viewState.contactsSelectedGroupName)?.name ?? context.l10n.listFilter_all; @@ -628,79 +756,39 @@ class _ContactsScreenState extends State position: PopupMenuPosition.under, constraints: BoxConstraints.tightFor(width: menuWidth), onSelected: (String value) { + if (value == _manageGroupsValue) { + _showManageGroupsSheet(this.context, contacts); + return; + } viewState.setContactsSelectedGroupName(value); }, itemBuilder: (menuContext) => [ PopupMenuItem( value: contactsAllGroupsValue, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text(menuContext.l10n.listFilter_all), - IconButton( - tooltip: menuContext.l10n.contacts_newGroup, - icon: const Icon(Icons.group_add, size: 20), - onPressed: canManageGroups - ? () => _closeDropdownAndRun( - menuContext, - () => _showGroupEditor(this.context, contacts), - ) - : () => _closeDropdownAndRun( - menuContext, - () => _showGroupsUnavailableMessage(this.context), - ), - ), - ], - ), + child: Text(menuContext.l10n.listFilter_all), ), ...sortedGroups.map((group) { return PopupMenuItem( value: group.name, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Expanded( - child: Text(group.name, overflow: TextOverflow.ellipsis), - ), - IconButton( - tooltip: menuContext.l10n.contacts_editGroup, - icon: const Icon(Icons.edit, size: 20), - onPressed: canManageGroups - ? () => _closeDropdownAndRun( - menuContext, - () => _showGroupEditor( - this.context, - contacts, - group: group, - ), - ) - : () => _closeDropdownAndRun( - menuContext, - () => _showGroupsUnavailableMessage(this.context), - ), - ), - const SizedBox(width: 8), - IconButton( - tooltip: menuContext.l10n.contacts_deleteGroup, - icon: Icon( - Icons.delete, - size: 20, - color: Theme.of(context).colorScheme.error, - ), - onPressed: canManageGroups - ? () => _closeDropdownAndRun( - menuContext, - () => _confirmDeleteGroup(this.context, group), - ) - : () => _closeDropdownAndRun( - menuContext, - () => _showGroupsUnavailableMessage(this.context), - ), - ), - ], - ), + child: Text(group.name, overflow: TextOverflow.ellipsis), ); }), + const PopupMenuDivider(), + PopupMenuItem( + value: _manageGroupsValue, + child: Row( + children: [ + const Icon(Icons.group_add), + const SizedBox(width: 12), + Expanded( + child: Text( + menuContext.l10n.contacts_manageGroups, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), ], child: SizedBox( height: 48, @@ -998,7 +1086,7 @@ class _ContactsScreenState extends State index: index, contact: contact, pathHashByteWidth: connector.pathHashByteWidth, - lastSeen: _resolveLastSeen(contact), + lastSeen: resolveContactLastSeen(contact), unreadCount: unreadCount, isFavorite: contact.isFavorite, onTap: () => _openChat(context, contact), @@ -1018,6 +1106,42 @@ class _ContactsScreenState extends State List contacts, MeshCoreConnector connector, UiViewStateService viewState, + ) { + final selectedGroup = _selectedGroupForName( + viewState.contactsSelectedGroupName, + ); + final selfKey = connector.selfPublicKey; + // Unread counts and last-message times change without the contact list + // changing, so they join the cache key only when they affect the result. + final unreadSignature = viewState.contactsShowUnreadOnly + ? [for (final c in contacts) connector.getUnreadCountForContact(c)] + : const []; + final recentSignature = + viewState.contactsSortOption == ContactSortOption.recentMessages + ? [for (final c in contacts) _lastMessageTime(connector, c)] + : const []; + return _filteredCache.get(contacts, [ + viewState.contactsSearchText, + viewState.contactsSelectedGroupName, + selectedGroup?.memberKeys ?? const [], + selfKey == null ? null : pubKeyToHex(selfKey), + viewState.contactsTypeFilter, + viewState.contactsShowUnreadOnly, + viewState.contactsSortOption, + unreadSignature, + recentSignature, + ], () => _computeFilteredContacts(contacts, connector, viewState)); + } + + DateTime _lastMessageTime(MeshCoreConnector connector, Contact contact) { + final messages = connector.getMessages(contact); + return messages.isEmpty ? DateTime(1970) : messages.last.timestamp; + } + + List _computeFilteredContacts( + List contacts, + MeshCoreConnector connector, + UiViewStateService viewState, ) { var filtered = contacts.where((contact) { if (viewState.contactsSearchText.isEmpty) return true; @@ -1060,21 +1184,15 @@ class _ContactsScreenState extends State switch (viewState.contactsSortOption) { case ContactSortOption.lastSeen: filtered.sort( - (a, b) => _resolveLastSeen(b).compareTo(_resolveLastSeen(a)), + (a, b) => + resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)), ); break; case ContactSortOption.recentMessages: - filtered.sort((a, b) { - final aMessages = connector.getMessages(a); - final bMessages = connector.getMessages(b); - final aLastMsg = aMessages.isEmpty - ? DateTime(1970) - : aMessages.last.timestamp; - final bLastMsg = bMessages.isEmpty - ? DateTime(1970) - : bMessages.last.timestamp; - return bLastMsg.compareTo(aLastMsg); - }); + final lastMessageAt = { + for (final c in filtered) c: _lastMessageTime(connector, c), + }; + filtered.sort((a, b) => lastMessageAt[b]!.compareTo(lastMessageAt[a]!)); break; case ContactSortOption.name: filtered.sort( @@ -1101,13 +1219,6 @@ class _ContactsScreenState extends State } } - DateTime _resolveLastSeen(Contact contact) { - if (contact.type != advTypeChat) return contact.lastSeen; - return contact.lastMessageAt.isAfter(contact.lastSeen) - ? contact.lastMessageAt - : contact.lastSeen; - } - void _openChat(BuildContext context, Contact contact) { // Check if this is a repeater if (contact.type == advTypeRepeater) { @@ -1264,171 +1375,176 @@ class _ContactsScreenState extends State final sortedContacts = List.from(contacts) ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); - showDialog( + showDialog( context: context, - builder: (dialogContext) => StatefulBuilder( - builder: (builderContext, setDialogState) { - final filteredContacts = filterQuery.isEmpty - ? sortedContacts - : sortedContacts - .where( - (contact) => matchesContactQuery(contact, filterQuery), - ) - .toList(); - return AlertDialog( - title: Text( - isEditing - ? context.l10n.contacts_editGroup - : context.l10n.contacts_newGroup, - ), - content: SizedBox( - width: double.maxFinite, - child: ConstrainedBox( - constraints: BoxConstraints( - maxHeight: MediaQuery.of(context).size.height * 0.8, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: nameController, - decoration: InputDecoration( - labelText: context.l10n.contacts_groupName, - border: const OutlineInputBorder(), + builder: (dialogContext) => _DisposeControllerOnUnmount( + controller: nameController, + child: StatefulBuilder( + builder: (builderContext, setDialogState) { + final filteredContacts = filterQuery.isEmpty + ? sortedContacts + : sortedContacts + .where( + (contact) => matchesContactQuery(contact, filterQuery), + ) + .toList(); + return AlertDialog( + title: Text( + isEditing + ? context.l10n.contacts_editGroup + : context.l10n.contacts_newGroup, + ), + content: SizedBox( + width: double.maxFinite, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(context).size.height * 0.8, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: nameController, + decoration: InputDecoration( + labelText: context.l10n.contacts_groupName, + border: const OutlineInputBorder(), + ), ), - ), - const SizedBox(height: 12), - TextField( - decoration: InputDecoration( - hintText: context.l10n.contacts_filterContacts, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: true, + const SizedBox(height: 12), + TextField( + decoration: InputDecoration( + hintText: context.l10n.contacts_filterContacts, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: true, + ), + onChanged: (value) { + setDialogState(() { + filterQuery = value.toLowerCase(); + }); + }, ), - onChanged: (value) { - setDialogState(() { - filterQuery = value.toLowerCase(); - }); - }, - ), - const SizedBox(height: 12), - Expanded( - child: filteredContacts.isEmpty - ? Center( - child: Text( - context.l10n.contacts_noContactsMatchFilter, + const SizedBox(height: 12), + Expanded( + child: filteredContacts.isEmpty + ? Center( + child: Text( + context.l10n.contacts_noContactsMatchFilter, + ), + ) + : ListView.builder( + itemCount: filteredContacts.length, + itemBuilder: (context, index) { + final contact = filteredContacts[index]; + final isSelected = selectedKeys.contains( + contact.publicKeyHex, + ); + return CheckboxListTile( + value: isSelected, + title: Text(contact.name), + subtitle: Text( + contact.typeLabel(context.l10n), + ), + onChanged: (value) { + setDialogState(() { + if (value == true) { + selectedKeys.add( + contact.publicKeyHex, + ); + } else { + selectedKeys.remove( + contact.publicKeyHex, + ); + } + }); + }, + ); + }, ), - ) - : ListView.builder( - itemCount: filteredContacts.length, - itemBuilder: (context, index) { - final contact = filteredContacts[index]; - final isSelected = selectedKeys.contains( - contact.publicKeyHex, - ); - return CheckboxListTile( - value: isSelected, - title: Text(contact.name), - subtitle: Text( - contact.typeLabel(context.l10n), - ), - onChanged: (value) { - setDialogState(() { - if (value == true) { - selectedKeys.add(contact.publicKeyHex); - } else { - selectedKeys.remove( - contact.publicKeyHex, - ); - } - }); - }, - ); - }, - ), - ), - ], + ), + ], + ), ), ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () async { - final name = nameController.text.trim(); - if (name.isEmpty) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_groupNameRequired), - ); - return; - } - if (name.toLowerCase() == - contactsAllGroupsValue.toLowerCase()) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_groupNameReserved), - ); - return; - } - final exists = _groups.any((g) { - if (isEditing && g.name == group.name) return false; - return g.name.toLowerCase() == name.toLowerCase(); - }); - if (exists) { - showDismissibleSnackBar( - context, - content: Text( - context.l10n.contacts_groupAlreadyExists(name), - ), - ); - return; - } - setState(() { - final viewState = context.read(); - if (isEditing) { - final index = _groups.indexWhere( - (g) => g.name == group.name, + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(context.l10n.common_cancel), + ), + TextButton( + onPressed: () async { + final name = nameController.text.trim(); + if (name.isEmpty) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_groupNameRequired), ); - if (index != -1) { - final wasSelected = - viewState.contactsSelectedGroupName == group.name; - _groups[index] = ContactGroup( - name: name, - memberKeys: selectedKeys.toList(), - ); - if (wasSelected) { - viewState.setContactsSelectedGroupName(name); - } - } - } else { - _groups.add( - ContactGroup( - name: name, - memberKeys: selectedKeys.toList(), + return; + } + if (name.toLowerCase() == + contactsAllGroupsValue.toLowerCase()) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_groupNameReserved), + ); + return; + } + final exists = _groups.any((g) { + if (isEditing && g.name == group.name) return false; + return g.name.toLowerCase() == name.toLowerCase(); + }); + if (exists) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.contacts_groupAlreadyExists(name), ), ); - viewState.setContactsSelectedGroupName(name); + return; } - _ensureValidSelectedGroup(); - }); - await _saveGroups(); - if (dialogContext.mounted) { - Navigator.pop(dialogContext); - } - }, - child: Text( - isEditing - ? context.l10n.common_save - : context.l10n.common_create, + setState(() { + final viewState = context.read(); + if (isEditing) { + final index = _groups.indexWhere( + (g) => g.name == group.name, + ); + if (index != -1) { + final wasSelected = + viewState.contactsSelectedGroupName == group.name; + _groups[index] = ContactGroup( + name: name, + memberKeys: selectedKeys.toList(), + ); + if (wasSelected) { + viewState.setContactsSelectedGroupName(name); + } + } + } else { + _groups.add( + ContactGroup( + name: name, + memberKeys: selectedKeys.toList(), + ), + ); + viewState.setContactsSelectedGroupName(name); + } + _ensureValidSelectedGroup(); + }); + await _saveGroups(); + if (dialogContext.mounted) { + Navigator.pop(dialogContext); + } + }, + child: Text( + isEditing + ? context.l10n.common_save + : context.l10n.common_create, + ), ), - ), - ], - ); - }, + ], + ); + }, + ), ), ); } @@ -1695,35 +1811,6 @@ class _ContactTile extends StatelessWidget { this.onManage, }); - /// Node-type avatar color per design language. - Color _avatarColor() { - switch (contact.type) { - case advTypeRepeater: - return MeshPalette.warn; - case advTypeRoom: - return MeshPalette.magenta; - case advTypeSensor: - return const Color(0xFF4ACCC4); // teal - default: - return MeshPalette - .blue; // chat — AvatarCircle handles deterministic hue - } - } - - /// Node-type avatar icon. Returns null for chat nodes so AvatarCircle shows initials. - IconData? _avatarIcon() { - switch (contact.type) { - case advTypeRepeater: - return Icons.cell_tower; - case advTypeRoom: - return Icons.meeting_room; - case advTypeSensor: - return Icons.sensors; - default: - return null; // chat uses initials - } - } - @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; @@ -1755,8 +1842,8 @@ class _ContactTile extends StatelessWidget { AvatarCircle( name: contact.name, size: 42, - color: isChat ? null : _avatarColor(), - icon: _avatarIcon(), + color: isChat ? null : contactTypeColor(contact.type), + icon: contactTypeIcon(contact.type), ), const SizedBox(width: 12), // Main content @@ -1784,16 +1871,14 @@ class _ContactTile extends StatelessWidget { ), if (isFavorite) ...[ const SizedBox(width: 4), - Icon(Icons.star, size: 13, color: MeshPalette.warn), + Icon(Icons.star, size: 16, color: MeshPalette.warn), ], if (contact.hasLocation) ...[ const SizedBox(width: 4), Icon( Icons.location_on, - size: 13, - color: scheme.onSurfaceVariant.withValues( - alpha: 0.55, - ), + size: 16, + color: scheme.onSurfaceVariant, ), ], ], @@ -1811,7 +1896,7 @@ class _ContactTile extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( - fontSize: 12, + fontSize: 13, color: scheme.onSurfaceVariant, ), ), @@ -1822,13 +1907,11 @@ class _ContactTile extends StatelessWidget { ), ), const SizedBox(width: 10), - // Trailing: time + unread badge - // Clamp text scale to prevent overflow in trailing section. - MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaler: TextScaler.linear( - MediaQuery.textScalerOf(context).scale(1.0).clamp(1.0, 1.3), - ), + // Trailing: time + unread badge. A width cap + wrapping keeps + // large text scales from overflowing without clamping them. + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: MediaQuery.sizeOf(context).width * 0.25, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -1840,12 +1923,12 @@ class _ContactTile extends StatelessWidget { const SizedBox(height: 4), ], Text( - _formatLastSeen(context, lastSeen), - maxLines: 1, + formatContactLastSeen(context.l10n, lastSeen), + maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.right, style: MeshTheme.mono( - fontSize: 11, + fontSize: 12.5, color: unreadCount > 0 ? MeshPalette.blue : scheme.onSurfaceVariant, @@ -1868,28 +1951,34 @@ class _ContactTile extends StatelessWidget { ), ); } +} - String _formatLastSeen(BuildContext context, DateTime lastSeen) { - final now = DateTime.now(); - final diff = now.difference(lastSeen); +/// Disposes [controller] when the dialog content unmounts, i.e. after the +/// route's exit animation, so the TextField never sees a disposed controller. +class _DisposeControllerOnUnmount extends StatefulWidget { + final TextEditingController controller; + final Widget child; - if (diff.isNegative || diff.inMinutes < 5) { - return context.l10n.contacts_lastSeenNow; - } - if (diff.inMinutes < 60) { - return context.l10n.contacts_lastSeenMinsAgo(diff.inMinutes); - } - if (diff.inHours < 24) { - final hours = diff.inHours; - return hours == 1 - ? context.l10n.contacts_lastSeenHourAgo - : context.l10n.contacts_lastSeenHoursAgo(hours); - } - final days = diff.inDays; - return days == 1 - ? context.l10n.contacts_lastSeenDayAgo - : context.l10n.contacts_lastSeenDaysAgo(days); + const _DisposeControllerOnUnmount({ + required this.controller, + required this.child, + }); + + @override + State<_DisposeControllerOnUnmount> createState() => + _DisposeControllerOnUnmountState(); +} + +class _DisposeControllerOnUnmountState + extends State<_DisposeControllerOnUnmount> { + @override + void dispose() { + widget.controller.dispose(); + super.dispose(); } + + @override + Widget build(BuildContext context) => widget.child; } // Wrap each contact tile with staggered entrance. diff --git a/lib/screens/discovery_screen.dart b/lib/screens/discovery_screen.dart index 114c6720..3bcda5f7 100644 --- a/lib/screens/discovery_screen.dart +++ b/lib/screens/discovery_screen.dart @@ -17,13 +17,12 @@ import '../utils/contact_search.dart'; import '../utils/platform_info.dart'; import '../utils/share_origin.dart'; import '../widgets/app_bar.dart'; +import '../widgets/contact_visuals.dart'; import '../widgets/list_filter_widget.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/node_scan_sheet.dart'; import '../helpers/snack_bar_builder.dart'; -enum DiscoverySortOption { lastSeen, name, type } - class DiscoveryScreen extends StatefulWidget { const DiscoveryScreen({super.key}); @@ -35,10 +34,9 @@ class _DiscoveryScreenState extends State { final TextEditingController _searchController = TextEditingController(); String searchQuery = ''; ContactSortOption sortOption = ContactSortOption.lastSeen; - bool showUnreadOnly = false; ContactTypeFilter typeFilter = ContactTypeFilter.all; - DiscoverySortOption discoverySortOption = DiscoverySortOption.lastSeen; Timer? _searchDebounce; + final DerivedListCache _filteredCache = DerivedListCache(); ScaffoldMessengerState? _messenger; @override @@ -55,41 +53,6 @@ class _DiscoveryScreenState extends State { super.dispose(); } - DateTime _resolveLastSeen(Contact contact) { - if (contact.type != advTypeChat) return contact.lastSeen; - return contact.lastMessageAt.isAfter(contact.lastSeen) - ? contact.lastMessageAt - : contact.lastSeen; - } - - /// Node-type avatar color per design language. - Color _avatarColor(int type) { - switch (type) { - case advTypeRepeater: - return MeshPalette.warn; - case advTypeRoom: - return MeshPalette.magenta; - case advTypeSensor: - return const Color(0xFF4ACCC4); // teal - default: - return MeshPalette.blue; - } - } - - /// Node-type avatar icon; null = show initials for chat nodes. - IconData? _avatarIcon(int type) { - switch (type) { - case advTypeRepeater: - return Icons.cell_tower; - case advTypeRoom: - return Icons.meeting_room; - case advTypeSensor: - return Icons.sensors; - default: - return null; - } - } - @override Widget build(BuildContext context) { final l10n = context.l10n; @@ -231,8 +194,8 @@ class _DiscoveryScreenState extends State { AvatarCircle( name: contact.name, size: 42, - color: isChat ? null : _avatarColor(contact.type), - icon: _avatarIcon(contact.type), + color: isChat ? null : contactTypeColor(contact.type), + icon: contactTypeIcon(contact.type), ), const SizedBox(width: 12), Expanded( @@ -257,8 +220,8 @@ class _DiscoveryScreenState extends State { const SizedBox(width: 6), StatusChip( label: contact.typeLabel(context.l10n).toUpperCase(), - color: _avatarColor(contact.type), - icon: _avatarIcon(contact.type), + color: contactTypeColor(contact.type), + icon: contactTypeIcon(contact.type), ), ], ), @@ -272,7 +235,7 @@ class _DiscoveryScreenState extends State { maxLines: 1, overflow: TextOverflow.ellipsis, style: MeshTheme.mono( - fontSize: 11, + fontSize: 12.5, color: scheme.onSurfaceVariant, ), ), @@ -281,20 +244,16 @@ class _DiscoveryScreenState extends State { const SizedBox(width: 6), Icon( Icons.location_on, - size: 13, - color: scheme.onSurfaceVariant.withValues( - alpha: 0.55, - ), + size: 16, + color: scheme.onSurfaceVariant, ), ], if (contact.rawPacket != null) ...[ const SizedBox(width: 4), Icon( Icons.cell_tower, - size: 13, - color: scheme.onSurfaceVariant.withValues( - alpha: 0.55, - ), + size: 16, + color: scheme.onSurfaceVariant, ), ], ], @@ -303,21 +262,26 @@ class _DiscoveryScreenState extends State { ), ), const SizedBox(width: 10), - // Last seen time - MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaler: TextScaler.linear( - MediaQuery.textScalerOf(context).scale(1.0).clamp(1.0, 1.3), + // Last seen time. A width cap + wrapping keeps large text scales + // from overflowing without clamping the user's text size. + Flexible( + flex: 0, + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: MediaQuery.sizeOf(context).width * 0.25, ), - ), - child: Text( - _formatLastSeen(context, _resolveLastSeen(contact)), - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.right, - style: MeshTheme.mono( - fontSize: 11, - color: scheme.onSurfaceVariant, + child: Text( + formatContactLastSeen( + context.l10n, + resolveContactLastSeen(contact), + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.right, + style: MeshTheme.mono( + fontSize: 12.5, + color: scheme.onSurfaceVariant, + ), ), ), ), @@ -579,39 +543,20 @@ class _DiscoveryScreenState extends State { List filteredAndSorted, MeshCoreConnector connector, ) { - String hintText = ""; - switch (typeFilter) { - case ContactTypeFilter.all: - hintText = context.l10n.contacts_searchContacts( - filteredAndSorted.length, - showUnreadOnly ? " ${context.l10n.contacts_unread}" : "", - ); - break; - case ContactTypeFilter.users: - hintText = context.l10n.contacts_searchUsers( - filteredAndSorted.length, - showUnreadOnly ? " ${context.l10n.contacts_unread}" : "", - ); - break; - case ContactTypeFilter.repeaters: - hintText = context.l10n.contacts_searchRepeaters( - filteredAndSorted.length, - showUnreadOnly ? " ${context.l10n.contacts_unread}" : "", - ); - break; - case ContactTypeFilter.rooms: - hintText = context.l10n.contacts_searchRoomServers( - filteredAndSorted.length, - showUnreadOnly ? " ${context.l10n.contacts_unread}" : "", - ); - break; - case ContactTypeFilter.favorites: - hintText = context.l10n.contacts_searchFavorites( - filteredAndSorted.length, - showUnreadOnly ? " ${context.l10n.contacts_unread}" : "", - ); - break; - } + final count = filteredAndSorted.length; + final hintText = switch (typeFilter) { + ContactTypeFilter.users => context.l10n.contacts_searchUsers(count, ''), + ContactTypeFilter.repeaters => context.l10n.contacts_searchRepeaters( + count, + '', + ), + ContactTypeFilter.rooms => context.l10n.contacts_searchRoomServers( + count, + '', + ), + // Discovery offers no favorites filter; fall back to the generic hint. + _ => context.l10n.contacts_searchContacts(count, ''), + }; return Column( children: [ @@ -683,27 +628,35 @@ class _DiscoveryScreenState extends State { List contacts, MeshCoreConnector connector, ) { - var filtered = contacts.where((contact) { - if (searchQuery.isEmpty) return true; - return matchesDiscoveryContactQuery(contact, searchQuery); + // knownContactKeys returns a fresh copy; read it once per build. + final knownKeys = connector.knownContactKeys; + final selfKey = connector.selfPublicKey; + final selfPubKeyHex = selfKey == null ? null : pubKeyToHex(selfKey); + return _filteredCache.get(contacts, [ + searchQuery, + typeFilter, + sortOption, + selfPubKeyHex, + Object.hashAllUnordered(knownKeys), + ], () => _computeFilteredContacts(contacts, knownKeys, selfPubKeyHex)); + } + + List _computeFilteredContacts( + List contacts, + Set knownKeys, + String? selfPubKeyHex, + ) { + final filtered = contacts.where((contact) { + if (searchQuery.isNotEmpty && + !matchesDiscoveryContactQuery(contact, searchQuery)) { + return false; + } + if (knownKeys.contains(contact.publicKeyHex)) return false; + // Filter out own node from the list + if (contact.publicKeyHex == selfPubKeyHex) return false; + return _matchesTypeFilter(contact); }).toList(); - filtered = filtered.where((contact) { - return !connector.knownContactKeys.contains(contact.publicKeyHex); - }).toList(); - - // Filter out own node from the list - if (connector.selfPublicKey != null) { - final selfPubKeyHex = pubKeyToHex(connector.selfPublicKey!); - filtered = filtered.where((contact) { - return contact.publicKeyHex != selfPubKeyHex; - }).toList(); - } - - if (typeFilter != ContactTypeFilter.all) { - filtered = filtered.where(_matchesTypeFilter).toList(); - } - switch (sortOption) { case ContactSortOption.lastSeen: filtered.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); @@ -730,30 +683,9 @@ class _DiscoveryScreenState extends State { return contact.type == advTypeRepeater; case ContactTypeFilter.rooms: return contact.type == advTypeRoom; - default: - return false; + case ContactTypeFilter.favorites: + // Not offered by the discovery filter menu. + return true; } } - - String _formatLastSeen(BuildContext context, DateTime lastSeen) { - final now = DateTime.now(); - final diff = now.difference(lastSeen); - - if (diff.isNegative || diff.inMinutes < 5) { - return context.l10n.contacts_lastSeenNow; - } - if (diff.inMinutes < 60) { - return context.l10n.contacts_lastSeenMinsAgo(diff.inMinutes); - } - if (diff.inHours < 24) { - final hours = diff.inHours; - return hours == 1 - ? context.l10n.contacts_lastSeenHourAgo - : context.l10n.contacts_lastSeenHoursAgo(hours); - } - final days = diff.inDays; - return days == 1 - ? context.l10n.contacts_lastSeenDayAgo - : context.l10n.contacts_lastSeenDaysAgo(days); - } } diff --git a/lib/screens/line_of_sight_map_screen.dart b/lib/screens/line_of_sight_map_screen.dart index 865ff73b..bc872516 100644 --- a/lib/screens/line_of_sight_map_screen.dart +++ b/lib/screens/line_of_sight_map_screen.dart @@ -1,9 +1,10 @@ +import 'dart:async'; import 'dart:math' as math; import 'dart:ui' as ui; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; +import 'package:http/http.dart' as http; import 'package:latlong2/latlong.dart'; import 'package:provider/provider.dart'; @@ -17,6 +18,7 @@ import '../services/map_tile_cache_service.dart'; import '../utils/route_transitions.dart'; import '../connector/meshcore_connector.dart'; import '../widgets/app_bar.dart'; +import '../widgets/path_map_scaffold.dart'; import '../widgets/quick_switch_bar.dart'; import '../icons/los_icon.dart'; import '../theme/mesh_theme.dart'; @@ -57,10 +59,9 @@ class _LineOfSightMapScreenState extends State { static const double _kmToMiles = 0.621371; static const double _maxAntennaFeet = 400.0; static const double _maxAntennaMeters = _maxAntennaFeet / _metersToFeet; - static const double _labelZoomThreshold = 8.5; - static const double _mapMinZoom = 2.0; - static const double _mapMaxZoom = 18.0; + static const double _labelZoomThreshold = kPathMapLabelZoomThreshold; static const double _marginalClearanceMeters = 5.0; + static const Duration _antennaRerunDebounce = Duration(milliseconds: 400); final LineOfSightService _lineOfSightService = LineOfSightService(); final MapController _mapController = MapController(); @@ -84,6 +85,12 @@ class _LineOfSightMapScreenState extends State { int _losRequestNonce = 0; bool _initialLosScheduled = false; bool _showTerrainLayer = true; + // True when the last failure looks like missing connectivity. + bool _networkError = false; + // Antenna heights the current [_result] was computed with. + double? _resultStartAntenna; + double? _resultEndAntenna; + Timer? _antennaRerunTimer; @override void initState() { @@ -106,46 +113,23 @@ class _LineOfSightMapScreenState extends State { }); } + @override + void didUpdateWidget(LineOfSightMapScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.candidates, widget.candidates)) { + _sanitizeSelection(); + } + } + @override void dispose() { + _antennaRerunTimer?.cancel(); _mapController.dispose(); _panelController.dispose(); _lineOfSightService.dispose(); super.dispose(); } - bool _isDesktopPlatform(TargetPlatform platform) { - return platform == TargetPlatform.linux || - platform == TargetPlatform.windows || - platform == TargetPlatform.macOS; - } - - void _zoomMapBy(double delta) { - final camera = _mapController.camera; - final nextZoom = (camera.zoom + delta) - .clamp(_mapMinZoom, _mapMaxZoom) - .toDouble(); - _mapController.move(camera.center, nextZoom); - } - - void _resetMapView({ - required LatLng initialCenter, - required double initialZoom, - required LatLngBounds? bounds, - }) { - if (bounds != null) { - _mapController.fitCamera( - CameraFit.bounds( - bounds: bounds, - padding: const EdgeInsets.all(64), - maxZoom: 16, - ), - ); - return; - } - _mapController.move(initialCenter, initialZoom); - } - Future _runLos() async { final start = _start; final end = _end; @@ -164,6 +148,7 @@ class _LineOfSightMapScreenState extends State { setState(() { _loading = true; _error = null; + _networkError = false; }); try { @@ -176,35 +161,31 @@ class _LineOfSightMapScreenState extends State { frequencyMHz: frequencyMHz, ); if (!mounted) return; - if (!_isRunRequestCurrent( - requestId: requestId, - start: start, - end: end, - startAntenna: startAntenna, - endAntenna: endAntenna, - )) { + if (!_isRunRequestCurrent(requestId: requestId, start: start, end: end)) { return; } setState(() { _result = result; + _resultStartAntenna = startAntenna; + _resultEndAntenna = endAntenna; _selectedObstruction = _defaultObstructionFor(result); _menuExpanded = false; }); + // A slider moved while this run was in flight: refresh again. + if (_resultIsStale) _scheduleAntennaRerun(); } catch (e) { if (!mounted) return; - if (!_isRunRequestCurrent( - requestId: requestId, - start: start, - end: end, - startAntenna: startAntenna, - endAntenna: endAntenna, - )) { + if (!_isRunRequestCurrent(requestId: requestId, start: start, end: end)) { return; } + final isNetwork = _isNetworkError(e); setState(() { _result = null; _selectedObstruction = null; - _error = context.l10n.losRunFailed(e.toString()); + _networkError = isNetwork; + _error = isNetwork + ? context.l10n.losErrorNoInternet + : context.l10n.losRunFailed(e.toString()); }); } finally { if (mounted && requestId == _losRequestNonce) { @@ -215,20 +196,48 @@ class _LineOfSightMapScreenState extends State { } } + /// Antenna changes don't invalidate a run: its result is kept (marked + /// stale) and a follow-up run is scheduled when the slider is released. bool _isRunRequestCurrent({ required int requestId, required LineOfSightEndpoint start, required LineOfSightEndpoint end, - required double startAntenna, - required double endAntenna, }) { return requestId == _losRequestNonce && identical(_start, start) && - identical(_end, end) && - _startAntennaHeight == startAntenna && - _endAntennaHeight == endAntenna; + identical(_end, end); } + static bool _isNetworkError(Object error) { + if (error is http.ClientException || error is TimeoutException) { + return true; + } + // SocketException lives in dart:io, which is unavailable on web. + final text = '${error.runtimeType} $error'; + return text.contains('SocketException') || + text.contains('Failed host lookup') || + text.contains('Network is unreachable'); + } + + bool get _resultIsStale => + _result != null && + (_resultStartAntenna != _startAntennaHeight || + _resultEndAntenna != _endAntennaHeight); + + void _scheduleAntennaRerun() { + _antennaRerunTimer?.cancel(); + if (!_resultIsStale || _start == null || _end == null) return; + _antennaRerunTimer = Timer(_antennaRerunDebounce, () { + if (mounted && _resultIsStale) _runLos(); + }); + } + + String _distanceUnit(bool isImperial) => + isImperial ? context.l10n.units_mi : context.l10n.units_km; + + String _heightUnit(bool isImperial) => + isImperial ? context.l10n.units_ft : context.l10n.units_m; + void _selectFromMap(LineOfSightEndpoint endpoint) { setState(() { _result = null; @@ -306,33 +315,10 @@ class _LineOfSightMapScreenState extends State { } Future _renameCustomPoint(LineOfSightEndpoint endpoint) async { - final controller = TextEditingController(text: endpoint.label); final newLabel = await showDialog( context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.losRenameCustomPoint), - content: TextField( - controller: controller, - decoration: InputDecoration( - border: const OutlineInputBorder(), - labelText: context.l10n.losPointName, - ), - autofocus: true, - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(context.l10n.common_cancel), - ), - TextButton( - onPressed: () { - final value = controller.text.trim(); - Navigator.pop(dialogContext, value); - }, - child: Text(context.l10n.common_save), - ), - ], - ), + builder: (dialogContext) => + _RenamePointDialog(initialLabel: endpoint.label), ); if (newLabel == null || newLabel.isEmpty) return; @@ -369,7 +355,6 @@ class _LineOfSightMapScreenState extends State { ? LatLngBounds.fromPoints(mapPoints) : null; final initialZoom = mapPoints.length > 1 ? 13.0 : 2.0; - final isDesktop = _isDesktopPlatform(defaultTargetPlatform); if (!_didReceivePositionUpdate) { _showMarkerLabels = initialZoom >= _labelZoomThreshold; } @@ -403,31 +388,10 @@ class _LineOfSightMapScreenState extends State { children: [ FlutterMap( mapController: _mapController, - options: MapOptions( + options: buildPathMapOptions( initialCenter: initialCenter, initialZoom: initialZoom, - initialCameraFit: bounds == null - ? null - : CameraFit.bounds( - bounds: bounds, - padding: const EdgeInsets.all(64), - maxZoom: 16, - ), - interactionOptions: InteractionOptions( - flags: ~InteractiveFlag.rotate, - scrollWheelVelocity: isDesktop ? 0.012 : 0.005, - cursorKeyboardRotationOptions: - CursorKeyboardRotationOptions.disabled(), - keyboardOptions: isDesktop - ? const KeyboardOptions( - enableArrowKeysPanning: true, - enableWASDPanning: true, - enableRFZooming: true, - ) - : const KeyboardOptions.disabled(), - ), - minZoom: _mapMinZoom, - maxZoom: _mapMaxZoom, + bounds: bounds, onLongPress: (_, point) => _addCustomPoint(point), onSecondaryTap: (_, point) => _addCustomPoint(point), onPositionChanged: (camera, hasGesture) { @@ -512,75 +476,86 @@ class _LineOfSightMapScreenState extends State { top: 10, left: 12, right: 12, - child: IgnorePointer( - ignoring: false, - child: Material( - color: LosPalette.panelDark, - borderRadius: BorderRadius.circular(MeshRadii.md), - shadowColor: LosPalette.shadow, - elevation: 4, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), - child: Row( - children: [ - Container( - width: 36, - height: 36, - decoration: BoxDecoration( - color: _statusColorFor(status).withValues(alpha: 0.18), - shape: BoxShape.circle, - border: Border.all(color: _statusColorFor(status)), - ), - child: Icon( - _statusIcon(status), - color: _statusColorFor(status), - size: 20, - ), + child: Material( + color: LosPalette.panelDark, + borderRadius: BorderRadius.circular(MeshRadii.md), + shadowColor: LosPalette.shadow, + elevation: 4, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: _statusColorFor(status).withValues(alpha: 0.18), + shape: BoxShape.circle, + border: Border.all(color: _statusColorFor(status)), ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '${_start?.label ?? 'A'} → ${_end?.label ?? 'B'}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - color: LosPalette.text, - fontSize: 14, - fontWeight: FontWeight.w800, - ), + child: Icon( + _statusIcon(status), + color: _statusColorFor(status), + size: 20, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${_start?.label ?? context.l10n.losEndpointA} → ' + '${_end?.label ?? context.l10n.losEndpointB}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: LosPalette.text, + fontSize: 14, + fontWeight: FontWeight.w800, ), - const SizedBox(height: 2), - Text( - segment == null - ? _statusText() - : '${_statusLabel(status)} • ' - '${_formatDistanceValue(segment.totalDistanceMeters, isImperial)} ' - '${isImperial ? 'mi' : 'km'}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - color: LosPalette.textMuted, - fontSize: 11.5, - fontWeight: FontWeight.w600, - ), + ), + const SizedBox(height: 2), + Text( + segment == null + ? _statusText() + : '${_statusLabel(status)} • ' + '${_formatDistanceValue(segment.totalDistanceMeters, isImperial)} ' + '${_distanceUnit(isImperial)}', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: LosPalette.textMuted, + fontSize: 13, + fontWeight: FontWeight.w600, ), - ], + ), + ], + ), + ), + if (_networkError && !_loading) ...[ + const SizedBox(width: 6), + TextButton( + onPressed: _runLos, + style: TextButton.styleFrom( + foregroundColor: LosPalette.selected, + minimumSize: const Size(48, 48), ), - ), - _headerMetric( - Icons.battery_5_bar, - battery == null ? '--' : '$battery%', - ), - const SizedBox(width: 10), - _headerMetric( - Icons.network_cell, - snr == null ? '--' : '${snr.toStringAsFixed(1)} dB', + child: Text(context.l10n.common_retry), ), ], - ), + _headerMetric( + Icons.battery_5_bar, + battery == null ? '--' : '$battery%', + ), + const SizedBox(width: 10), + _headerMetric( + Icons.network_cell, + snr == null + ? '--' + : context.l10n.losSnrValue(snr.toStringAsFixed(1)), + ), + ], ), ), ), @@ -597,7 +572,7 @@ class _LineOfSightMapScreenState extends State { value, style: MeshTheme.mono( color: LosPalette.text, - fontSize: 10, + fontSize: 12, fontWeight: FontWeight.w700, ), ), @@ -627,22 +602,23 @@ class _LineOfSightMapScreenState extends State { color: LosPalette.text, icon: const Icon(Icons.add), tooltip: context.l10n.map_zoomIn, - onPressed: () => _zoomMapBy(1), + onPressed: () => zoomMapBy(_mapController, 1), ), IconButton( color: LosPalette.text, icon: const Icon(Icons.remove), tooltip: context.l10n.map_zoomOut, - onPressed: () => _zoomMapBy(-1), + onPressed: () => zoomMapBy(_mapController, -1), ), IconButton( color: LosPalette.text, icon: const Icon(Icons.center_focus_strong), tooltip: context.l10n.map_centerMap, - onPressed: () => _resetMapView( - initialCenter: initialCenter, - initialZoom: initialZoom, + onPressed: () => resetMapView( + _mapController, bounds: bounds, + center: initialCenter, + zoom: initialZoom, ), ), IconButton( @@ -657,7 +633,7 @@ class _LineOfSightMapScreenState extends State { IconButton( color: LosPalette.text, icon: Text( - isImperial ? 'ft' : 'm', + _heightUnit(isImperial), style: const TextStyle( color: LosPalette.text, fontSize: 12, @@ -688,8 +664,8 @@ class _LineOfSightMapScreenState extends State { Widget _buildResultSummary(LineOfSightResult? segment, bool isImperial) { final status = _losStatusFor(segment); final color = _statusColorFor(status); - final distanceUnit = isImperial ? 'mi' : 'km'; - final heightUnit = isImperial ? 'ft' : 'm'; + final distanceUnit = _distanceUnit(isImperial); + final heightUnit = _heightUnit(isImperial); final worst = _defaultObstructionFor(_result); final minClearance = segment == null || segment.samples.isEmpty ? null @@ -732,6 +708,38 @@ class _LineOfSightMapScreenState extends State { ), ], ), + if (_resultIsStale) ...[ + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: LosPalette.marginal.withValues(alpha: 0.16), + borderRadius: BorderRadius.circular(MeshRadii.pill), + border: Border.all(color: LosPalette.marginal), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon( + Icons.update, + size: 18, + color: LosPalette.marginal, + ), + const SizedBox(width: 6), + Flexible( + child: Text( + context.l10n.losResultStale, + style: const TextStyle( + color: LosPalette.marginal, + fontSize: 13, + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ), + ), + ], const SizedBox(height: 12), Row( children: [ @@ -774,7 +782,7 @@ class _LineOfSightMapScreenState extends State { label.toUpperCase(), style: const TextStyle( color: LosPalette.textMuted, - fontSize: 9, + fontSize: 12, fontWeight: FontWeight.w700, ), ), @@ -785,7 +793,7 @@ class _LineOfSightMapScreenState extends State { overflow: TextOverflow.ellipsis, style: MeshTheme.mono( color: valueColor ?? LosPalette.text, - fontSize: 11.5, + fontSize: 13, fontWeight: FontWeight.w800, ), ), @@ -802,8 +810,8 @@ class _LineOfSightMapScreenState extends State { }) { final selected = _selectedObstruction?.sampleIndex == obstruction.sampleIndex; - final distanceUnit = isImperial ? 'mi' : 'km'; - final heightUnit = isImperial ? 'ft' : 'm'; + final distanceUnit = _distanceUnit(isImperial); + final heightUnit = _heightUnit(isImperial); return InkWell( onTap: () => _centerOnObstruction(obstruction), borderRadius: BorderRadius.circular(MeshRadii.sm), @@ -854,7 +862,7 @@ class _LineOfSightMapScreenState extends State { child: Text( context.l10n.losWorstBadge, style: TextStyle( - color: Colors.white, + color: LosPalette.text, fontSize: 12, fontWeight: FontWeight.w900, ), @@ -869,7 +877,7 @@ class _LineOfSightMapScreenState extends State { ), style: const TextStyle( color: LosPalette.textMuted, - fontSize: 11, + fontSize: 12, fontWeight: FontWeight.w600, ), ), @@ -884,8 +892,8 @@ class _LineOfSightMapScreenState extends State { LineOfSightResult segment, bool isImperial, ) { - final distanceUnit = isImperial ? 'mi' : 'km'; - final heightUnit = isImperial ? 'ft' : 'm'; + final distanceUnit = _distanceUnit(isImperial); + final heightUnit = _heightUnit(isImperial); return Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( @@ -951,7 +959,7 @@ class _LineOfSightMapScreenState extends State { label.toUpperCase(), style: const TextStyle( color: LosPalette.textMuted, - fontSize: 9, + fontSize: 12, fontWeight: FontWeight.w700, ), ), @@ -973,7 +981,6 @@ class _LineOfSightMapScreenState extends State { bool isImperial, ScrollController scrollController, ) { - _sanitizeSelection(); final segment = _primarySegmentResult(); final connector = context.read(); final reportedFrequencyMHz = _normalizeFrequencyMHz( @@ -984,8 +991,8 @@ class _LineOfSightMapScreenState extends State { final obstructions = segment?.obstructions ?? const []; final endpoints = _visibleEndpoints(); - final distanceUnit = isImperial ? 'mi' : 'km'; - final heightUnit = isImperial ? 'ft' : 'm'; + final distanceUnit = _distanceUnit(isImperial); + final heightUnit = _heightUnit(isImperial); final antennaAMeters = _startAntennaHeight; final antennaBMeters = _endAntennaHeight; final antennaADisplay = _toDisplayHeight(antennaAMeters, isImperial); @@ -1085,7 +1092,7 @@ class _LineOfSightMapScreenState extends State { ), subtitle: Text( context.l10n.losMenuSubtitle, - style: const TextStyle(color: LosPalette.textMuted, fontSize: 11), + style: const TextStyle(color: LosPalette.textMuted, fontSize: 12), ), children: [ SwitchListTile( @@ -1121,18 +1128,18 @@ class _LineOfSightMapScreenState extends State { ), subtitle: Text( '${point.point.latitude.toStringAsFixed(5)}, ${point.point.longitude.toStringAsFixed(5)}', - style: const TextStyle(fontSize: 11), + style: const TextStyle(fontSize: 12), ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( - icon: const Icon(Icons.edit, size: 18), + icon: const Icon(Icons.edit), onPressed: () => _renameCustomPoint(point), tooltip: context.l10n.common_edit, ), IconButton( - icon: const Icon(Icons.delete_outline, size: 18), + icon: const Icon(Icons.delete_outline), onPressed: () => _deleteCustomPoint(point), tooltip: context.l10n.common_delete, ), @@ -1186,10 +1193,12 @@ class _LineOfSightMapScreenState extends State { max: antennaSliderMax, divisions: antennaSliderDivisions, onChanged: (value) { + _antennaRerunTimer?.cancel(); setState(() { _startAntennaHeight = _toMetersHeight(value, isImperial); }); }, + onChangeEnd: (_) => _scheduleAntennaRerun(), ), Text( context.l10n.losAntennaB( @@ -1204,10 +1213,12 @@ class _LineOfSightMapScreenState extends State { max: antennaSliderMax, divisions: antennaSliderDivisions, onChanged: (value) { + _antennaRerunTimer?.cancel(); setState(() { _endAntennaHeight = _toMetersHeight(value, isImperial); }); }, + onChangeEnd: (_) => _scheduleAntennaRerun(), ), Align( alignment: Alignment.centerRight, @@ -1223,13 +1234,15 @@ class _LineOfSightMapScreenState extends State { const SizedBox(height: 10), Row( children: [ - Text( - '${context.l10n.losFrequencyLabel}: ' - '${displayFrequencyMHz.toStringAsFixed(3)} MHz' - '${kFactorUsed == null ? '' : ' k=${kFactorUsed.toStringAsFixed(3)}'}', - style: const TextStyle( - color: LosPalette.textMuted, - fontSize: 11, + Flexible( + child: Text( + '${context.l10n.losFrequencyLabel}: ' + '${context.l10n.losFrequencyValue(displayFrequencyMHz.toStringAsFixed(3))}' + '${kFactorUsed == null ? '' : ' ${context.l10n.losKFactorValue(kFactorUsed.toStringAsFixed(3))}'}', + style: const TextStyle( + color: LosPalette.textMuted, + fontSize: 12, + ), ), ), if (kFactorUsed != null) @@ -1248,7 +1261,7 @@ class _LineOfSightMapScreenState extends State { ], Text( context.l10n.losElevationAttribution, - style: const TextStyle(color: LosPalette.textMuted, fontSize: 10), + style: const TextStyle(color: LosPalette.textMuted, fontSize: 12), ), ], ), @@ -1335,8 +1348,8 @@ class _LineOfSightMapScreenState extends State { LineOfSightObstruction obstruction, bool isImperial, ) { - final distanceUnit = isImperial ? 'mi' : 'km'; - final heightUnit = isImperial ? 'ft' : 'm'; + final distanceUnit = _distanceUnit(isImperial); + final heightUnit = _heightUnit(isImperial); return context.l10n.losBlockedSpotChip( _formatDistanceValue(obstruction.distanceMeters, isImperial), distanceUnit, @@ -1351,73 +1364,46 @@ class _LineOfSightMapScreenState extends State { String heightUnit, bool isImperial, ) { + const chartHeight = 200.0; + const badgeStyle = TextStyle( + color: LosPalette.textMuted, + fontSize: 12, + fontWeight: FontWeight.w600, + ); + final painter = _LosProfilePainter( + samples: segment.samples, + isImperial: isImperial, + distanceUnit: distanceUnit, + heightUnit: heightUnit, + badgeTextStyle: badgeStyle, + endpointALabel: context.l10n.losEndpointA, + endpointBLabel: context.l10n.losEndpointB, + selectedLabel: context.l10n.losSelectedPill, + selectedSampleIndex: _selectedObstruction?.sampleIndex, + ); if (segment.samples.length < 2) { return SizedBox( - height: 190, + height: chartHeight, width: double.infinity, - child: CustomPaint( - painter: _LosProfilePainter( - samples: segment.samples, - distanceUnit: distanceUnit, - heightUnit: heightUnit, - badgeTextStyle: - Theme.of(context).textTheme.labelSmall?.copyWith( - color: LosPalette.textMuted, - fontSize: 10, - fontWeight: FontWeight.w600, - ) ?? - const TextStyle( - color: LosPalette.textMuted, - fontSize: 10, - fontWeight: FontWeight.w600, - ), - terrainLabel: context.l10n.losLegendTerrain, - losBeamLabel: context.l10n.losLegendLosBeam, - radioHorizonLabel: context.l10n.losLegendRadioHorizon, - selectedLabel: context.l10n.losSelectedPill, - selectedSampleIndex: _selectedObstruction?.sampleIndex, - ), - ), + child: CustomPaint(painter: painter), ); } return SizedBox( - height: 190, + height: chartHeight, width: double.infinity, child: LayoutBuilder( builder: (context, constraints) { - final size = Size(constraints.maxWidth, 190); + final size = Size(constraints.maxWidth, chartHeight); final geometry = _LosProfileGeometry( samples: segment.samples, size: size, ); + // Visible dot stays small; the tap target is at least 40px. + const hitSize = 44.0; return Stack( clipBehavior: Clip.none, children: [ - Positioned.fill( - child: CustomPaint( - painter: _LosProfilePainter( - samples: segment.samples, - distanceUnit: distanceUnit, - heightUnit: heightUnit, - badgeTextStyle: - Theme.of(context).textTheme.labelSmall?.copyWith( - color: LosPalette.textMuted, - fontSize: 10, - fontWeight: FontWeight.w600, - ) ?? - const TextStyle( - color: LosPalette.textMuted, - fontSize: 10, - fontWeight: FontWeight.w600, - ), - terrainLabel: context.l10n.losLegendTerrain, - losBeamLabel: context.l10n.losLegendLosBeam, - radioHorizonLabel: context.l10n.losLegendRadioHorizon, - selectedLabel: context.l10n.losSelectedPill, - selectedSampleIndex: _selectedObstruction?.sampleIndex, - ), - ), - ), + Positioned.fill(child: CustomPaint(painter: painter)), for (final obstruction in segment.obstructions) Builder( builder: (context) { @@ -1429,40 +1415,45 @@ class _LineOfSightMapScreenState extends State { final isSelected = _selectedObstruction?.sampleIndex == obstruction.sampleIndex; - final markerSize = isSelected ? 18.0 : 14.0; - final left = (position.dx - markerSize / 2) - .clamp(0.0, math.max(0.0, size.width - markerSize)) + final markerSize = isSelected ? 20.0 : 16.0; + final left = (position.dx - hitSize / 2) + .clamp(0.0, math.max(0.0, size.width - hitSize)) .toDouble(); - final top = (position.dy - markerSize / 2) - .clamp(0.0, math.max(0.0, size.height - markerSize)) + final top = (position.dy - hitSize / 2) + .clamp(0.0, math.max(0.0, size.height - hitSize)) .toDouble(); return Positioned( left: left, top: top, + width: hitSize, + height: hitSize, child: Tooltip( message: _obstructionChipLabel(obstruction, isImperial), child: GestureDetector( + behavior: HitTestBehavior.opaque, onTap: () => _centerOnObstruction(obstruction), - child: Container( - width: markerSize, - height: markerSize, - decoration: BoxDecoration( - color: isSelected - ? LosPalette.selected - : LosPalette.blocked, - shape: BoxShape.circle, - border: Border.all( + child: Center( + child: Container( + width: markerSize, + height: markerSize, + decoration: BoxDecoration( color: isSelected - ? LosPalette.text - : LosPalette.chartBackground, - width: isSelected ? 2 : 1.5, - ), - boxShadow: const [ - BoxShadow( - color: LosPalette.shadow, - blurRadius: 4, + ? LosPalette.selected + : LosPalette.blocked, + shape: BoxShape.circle, + border: Border.all( + color: isSelected + ? LosPalette.text + : LosPalette.chartBackground, + width: isSelected ? 2 : 1.5, ), - ], + boxShadow: const [ + BoxShadow( + color: LosPalette.shadow, + blurRadius: 4, + ), + ], + ), ), ), ), @@ -1489,7 +1480,7 @@ class _LineOfSightMapScreenState extends State { strokeWidth: 5, color: color, borderStrokeWidth: 2, - borderColor: Colors.white, + borderColor: MapPalette.markerOutline, ), ); } @@ -1548,67 +1539,12 @@ class _LineOfSightMapScreenState extends State { for (final endpoint in endpoints) Marker( point: endpoint.point, - width: 36, - height: 36, + width: 48, + height: 48, child: GestureDetector( + behavior: HitTestBehavior.opaque, onTap: () => _selectFromMap(endpoint), - child: Container( - decoration: BoxDecoration( - shape: BoxShape.circle, - color: (endpoint == _start || endpoint == _end) - ? endpoint.color - : LosPalette.panelDark, - border: Border.all( - color: (endpoint == _start || endpoint == _end) - ? Colors.white - : endpoint.color.withValues(alpha: 0.75), - width: (endpoint == _start || endpoint == _end) ? 2.5 : 1.5, - ), - boxShadow: const [ - BoxShadow( - color: LosPalette.shadow, - blurRadius: 7, - offset: Offset(0, 2), - ), - ], - ), - child: Stack( - children: [ - Center( - child: Icon( - endpoint.icon, - color: endpoint == _start || endpoint == _end - ? Colors.white - : endpoint.color, - size: 17, - ), - ), - if (endpoint == _start || endpoint == _end) - Positioned( - right: 0, - bottom: 0, - child: Container( - width: 14, - height: 14, - decoration: BoxDecoration( - color: LosPalette.chartBackground, - borderRadius: BorderRadius.circular(7), - border: Border.all(color: endpoint.color, width: 1), - ), - alignment: Alignment.center, - child: Text( - endpoint == _start ? 'A' : 'B', - style: MeshTheme.mono( - fontSize: 9, - fontWeight: FontWeight.w700, - color: endpoint.color, - ), - ), - ), - ), - ], - ), - ), + child: Center(child: _buildEndpointMarker(endpoint)), ), ), for (final endpoint in endpoints) @@ -1639,7 +1575,7 @@ class _LineOfSightMapScreenState extends State { maxLines: 1, overflow: TextOverflow.ellipsis, style: MeshTheme.mono( - fontSize: 10, + fontSize: 12, fontWeight: FontWeight.w700, color: LosPalette.text, ), @@ -1652,6 +1588,68 @@ class _LineOfSightMapScreenState extends State { ]; } + Widget _buildEndpointMarker(LineOfSightEndpoint endpoint) { + final isSelected = endpoint == _start || endpoint == _end; + return Container( + width: 40, + height: 40, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isSelected ? endpoint.color : LosPalette.panelDark, + border: Border.all( + color: isSelected + ? MapPalette.markerOutline + : endpoint.color.withValues(alpha: 0.75), + width: isSelected ? 2.5 : 1.5, + ), + boxShadow: const [ + BoxShadow( + color: LosPalette.shadow, + blurRadius: 7, + offset: Offset(0, 2), + ), + ], + ), + child: Stack( + clipBehavior: Clip.none, + children: [ + Center( + child: Icon( + endpoint.icon, + color: isSelected ? LosPalette.text : endpoint.color, + size: 20, + ), + ), + if (isSelected) + Positioned( + right: -4, + bottom: -4, + child: Container( + width: 20, + height: 20, + decoration: BoxDecoration( + color: LosPalette.chartBackground, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: endpoint.color, width: 1), + ), + alignment: Alignment.center, + child: Text( + endpoint == _start + ? context.l10n.losEndpointA + : context.l10n.losEndpointB, + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w700, + color: endpoint.color, + ), + ), + ), + ), + ], + ), + ); + } + String _statusText() { if (_loading) return context.l10n.losStatusChecking; if (_error == _errorSelectStartEnd) { @@ -1788,10 +1786,10 @@ class _LineOfSightMapScreenState extends State { enum _LosDisplayStatus { clear, marginal, blocked, unknown } class _LosProfileGeometry { - static const leftPadding = 38.0; + static const leftPadding = 46.0; static const rightPadding = 14.0; - static const topPadding = 20.0; - static const bottomPadding = 28.0; + static const topPadding = 22.0; + static const bottomPadding = 30.0; final List samples; final Size size; @@ -1835,24 +1833,27 @@ class _LosProfileGeometry { } class _LosProfilePainter extends CustomPainter { + static const double _metersToFeet = 3.28084; + static const double _kmToMiles = 0.621371; + final List samples; + final bool isImperial; final String distanceUnit; final String heightUnit; final TextStyle badgeTextStyle; - final String terrainLabel; - final String losBeamLabel; - final String radioHorizonLabel; + final String endpointALabel; + final String endpointBLabel; final String selectedLabel; final int? selectedSampleIndex; const _LosProfilePainter({ required this.samples, + required this.isImperial, required this.distanceUnit, required this.heightUnit, required this.badgeTextStyle, - required this.terrainLabel, - required this.losBeamLabel, - required this.radioHorizonLabel, + required this.endpointALabel, + required this.endpointBLabel, required this.selectedLabel, this.selectedSampleIndex, }); @@ -1865,37 +1866,18 @@ class _LosProfilePainter extends CustomPainter { if (samples.length < 2) return; - final minY = samples - .map( - (s) => math.min( - math.min(s.terrainMeters, s.lineHeightMeters), - s.refractedHeightMeters, - ), - ) - .reduce(math.min); - final maxY = samples - .map( - (s) => math.max( - math.max(s.terrainMeters, s.lineHeightMeters), - s.refractedHeightMeters, - ), - ) - .reduce(math.max); - final ySpan = math.max(1.0, maxY - minY); - final maxDist = math.max(1.0, samples.last.distanceMeters); + final geometry = _LosProfileGeometry(samples: samples, size: size); + final minY = geometry.minY; + final maxY = geometry.maxY; + final ySpan = geometry.ySpan; + final maxDist = geometry.maxDist; const leftPadding = _LosProfileGeometry.leftPadding; const rightPadding = _LosProfileGeometry.rightPadding; const topPadding = _LosProfileGeometry.topPadding; const bottomPadding = _LosProfileGeometry.bottomPadding; - final chartWidth = math.max(1.0, size.width - leftPadding - rightPadding); - final chartHeight = math.max(1.0, size.height - topPadding - bottomPadding); - - Offset mapPoint(double x, double y) { - final px = leftPadding + (x / maxDist) * chartWidth; - final py = - size.height - bottomPadding - ((y - minY) / ySpan) * chartHeight; - return Offset(px, py); - } + final chartWidth = geometry.chartWidth; + final chartHeight = geometry.chartHeight; + final mapPoint = geometry.mapPoint; final gridPaint = Paint() ..color = LosPalette.textMuted.withValues(alpha: 0.16) @@ -1924,7 +1906,7 @@ class _LosProfilePainter extends CustomPainter { _paintLabel( canvas, _displayHeight(elevation).toStringAsFixed(0), - Offset(leftPadding - 6, y - 6), + Offset(leftPadding - 6, y - 8), alignRight: true, ); } @@ -2106,11 +2088,15 @@ class _LosProfilePainter extends CustomPainter { ); } - _paintEndpoint(canvas, mapPoint(0, samples.first.lineHeightMeters), 'A'); + _paintEndpoint( + canvas, + mapPoint(0, samples.first.lineHeightMeters), + endpointALabel, + ); _paintEndpoint( canvas, mapPoint(maxDist, samples.last.lineHeightMeters), - 'B', + endpointBLabel, ); if (selectedSampleIndex != null && @@ -2150,13 +2136,11 @@ class _LosProfilePainter extends CustomPainter { } double _displayDistance(double meters) { - return distanceUnit == 'mi' - ? (meters / 1000.0) * 0.621371 - : meters / 1000.0; + return isImperial ? (meters / 1000.0) * _kmToMiles : meters / 1000.0; } double _displayHeight(double meters) { - return heightUnit == 'ft' ? meters * 3.28084 : meters; + return isImperial ? meters * _metersToFeet : meters; } void _paintLabel( @@ -2171,7 +2155,7 @@ class _LosProfilePainter extends CustomPainter { text: text, style: const TextStyle( color: LosPalette.textMuted, - fontSize: 9, + fontSize: 12, fontWeight: FontWeight.w600, ), ), @@ -2184,16 +2168,16 @@ class _LosProfilePainter extends CustomPainter { } void _paintEndpoint(Canvas canvas, Offset point, String label) { - canvas.drawCircle(point, 9, Paint()..color = LosPalette.chartBackground); + canvas.drawCircle(point, 11, Paint()..color = LosPalette.chartBackground); canvas.drawCircle( point, - 9, + 11, Paint() ..color = LosPalette.beam ..style = PaintingStyle.stroke ..strokeWidth = 2, ); - _paintLabel(canvas, label, Offset(point.dx, point.dy - 5), center: true); + _paintLabel(canvas, label, Offset(point.dx, point.dy - 8), center: true); } void _paintPill(Canvas canvas, String text, Offset center) { @@ -2202,15 +2186,15 @@ class _LosProfilePainter extends CustomPainter { text: text, style: const TextStyle( color: LosPalette.text, - fontSize: 9, + fontSize: 12, fontWeight: FontWeight.w800, ), ), textDirection: TextDirection.ltr, )..layout(); final rect = RRect.fromRectAndRadius( - Rect.fromCenter(center: center, width: painter.width + 12, height: 20), - const Radius.circular(10), + Rect.fromCenter(center: center, width: painter.width + 14, height: 22), + const Radius.circular(11), ); canvas.drawRRect(rect, Paint()..color = LosPalette.selected); painter.paint( @@ -2222,12 +2206,12 @@ class _LosProfilePainter extends CustomPainter { @override bool shouldRepaint(covariant _LosProfilePainter oldDelegate) { return oldDelegate.samples != samples || + oldDelegate.isImperial != isImperial || oldDelegate.distanceUnit != distanceUnit || oldDelegate.heightUnit != heightUnit || oldDelegate.badgeTextStyle != badgeTextStyle || - oldDelegate.terrainLabel != terrainLabel || - oldDelegate.losBeamLabel != losBeamLabel || - oldDelegate.radioHorizonLabel != radioHorizonLabel || + oldDelegate.endpointALabel != endpointALabel || + oldDelegate.endpointBLabel != endpointBLabel || oldDelegate.selectedLabel != selectedLabel || oldDelegate.selectedSampleIndex != selectedSampleIndex; } @@ -2309,3 +2293,50 @@ class _LegendEntry { const _LegendEntry(this.label, this.color); } + +/// Rename dialog that owns (and disposes) its text controller. +class _RenamePointDialog extends StatefulWidget { + final String initialLabel; + + const _RenamePointDialog({required this.initialLabel}); + + @override + State<_RenamePointDialog> createState() => _RenamePointDialogState(); +} + +class _RenamePointDialogState extends State<_RenamePointDialog> { + late final TextEditingController _controller = TextEditingController( + text: widget.initialLabel, + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(context.l10n.losRenameCustomPoint), + content: TextField( + controller: _controller, + decoration: InputDecoration( + border: const OutlineInputBorder(), + labelText: context.l10n.losPointName, + ), + autofocus: true, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(context.l10n.common_cancel), + ), + TextButton( + onPressed: () => Navigator.pop(context, _controller.text.trim()), + child: Text(context.l10n.common_save), + ), + ], + ); + } +} diff --git a/lib/screens/map_cache_screen.dart b/lib/screens/map_cache_screen.dart index cd2ae333..df954a2e 100644 --- a/lib/screens/map_cache_screen.dart +++ b/lib/screens/map_cache_screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; @@ -38,6 +40,11 @@ class _MapCacheScreenState extends State { bool _isLoadingCachedTiles = false; double _overlayZoom = 2.0; LatLngBounds? _visibleBounds; + MapTileDownloadCancelToken? _cancelToken; + // Pending camera update for the cached-tile overlay; applied after the + // camera settles instead of on every pan frame. + Timer? _positionDebounce; + MapCamera? _pendingCamera; @override void initState() { @@ -50,10 +57,59 @@ class _MapCacheScreenState extends State { @override void dispose() { + _positionDebounce?.cancel(); + _cancelToken?.cancel(); _mapController.dispose(); super.dispose(); } + bool get _useDarkOverlay => Theme.of(context).brightness == Brightness.dark; + + Color get _overlayPanelColor => _useDarkOverlay + ? MapPalette.panelDark + : Theme.of( + context, + ).colorScheme.surfaceContainerLow.withValues(alpha: 0.96); + + Color get _overlayBorderColor => _useDarkOverlay + ? MapPalette.border + : Theme.of(context).colorScheme.outlineVariant; + + Color get _overlayPrimaryTextColor => _useDarkOverlay + ? MapPalette.textPrimary + : Theme.of(context).colorScheme.onSurface; + + Color get _overlaySecondaryTextColor => _useDarkOverlay + ? MapPalette.textSecondary + : Theme.of(context).colorScheme.onSurfaceVariant; + + BoxDecoration get _overlayDecoration => BoxDecoration( + color: _overlayPanelColor, + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: _overlayBorderColor), + ); + + void _onCameraChanged(MapCamera camera) { + _pendingCamera = camera; + if (_positionDebounce?.isActive ?? false) return; + _positionDebounce = Timer(const Duration(milliseconds: 150), () { + final next = _pendingCamera; + if (!mounted || next == null) return; + final nextZoom = next.zoom; + final nextBounds = next.visibleBounds; + if (_overlayZoom != nextZoom || + _visibleBounds?.north != nextBounds.north || + _visibleBounds?.south != nextBounds.south || + _visibleBounds?.east != nextBounds.east || + _visibleBounds?.west != nextBounds.west) { + setState(() { + _overlayZoom = nextZoom; + _visibleBounds = nextBounds; + }); + } + }); + } + bool _isDesktopPlatform(TargetPlatform platform) { return platform == TargetPlatform.linux || platform == TargetPlatform.windows || @@ -84,11 +140,7 @@ class _MapCacheScreenState extends State { top: 12, left: 12, child: DecoratedBox( - decoration: BoxDecoration( - color: MeshPalette.bg1.withValues(alpha: 0.90), - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MeshPalette.line2), - ), + decoration: _overlayDecoration, child: ClipRRect( borderRadius: BorderRadius.circular(MeshRadii.md), child: Column( @@ -96,16 +148,19 @@ class _MapCacheScreenState extends State { children: [ IconButton( icon: const Icon(Icons.add), + color: _overlayPrimaryTextColor, tooltip: context.l10n.map_zoomIn, onPressed: () => _zoomMapBy(1), ), IconButton( icon: const Icon(Icons.remove), + color: _overlayPrimaryTextColor, tooltip: context.l10n.map_zoomOut, onPressed: () => _zoomMapBy(-1), ), IconButton( icon: const Icon(Icons.my_location), + color: _overlayPrimaryTextColor, tooltip: context.l10n.map_centerMap, onPressed: _resetMapView, ), @@ -217,6 +272,28 @@ class _MapCacheScreenState extends State { return; } + if (_estimatedTiles > MapTileCacheService.maxBulkDownloadTiles) { + await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(context.l10n.mapCache_tooManyTilesTitle), + content: Text( + context.l10n.mapCache_tooManyTiles( + _estimatedTiles, + MapTileCacheService.maxBulkDownloadTiles, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(context.l10n.common_ok), + ), + ], + ), + ); + return; + } + final confirmed = await showDialog( context: context, builder: (dialogContext) => AlertDialog( @@ -239,16 +316,19 @@ class _MapCacheScreenState extends State { if (confirmed != true || !mounted) return; + final cancelToken = MapTileDownloadCancelToken(); setState(() { _isDownloading = true; _completedTiles = 0; _failedTiles = 0; + _cancelToken = cancelToken; }); final result = await cacheService.downloadRegion( bounds: bounds, minZoom: _minZoom, maxZoom: _maxZoom, + cancelToken: cancelToken, onProgress: (progress) { if (!mounted) return; setState(() { @@ -262,11 +342,14 @@ class _MapCacheScreenState extends State { setState(() { _isDownloading = false; + _cancelToken = null; _completedTiles = result.downloaded + result.failed; _failedTiles = result.failed; }); - final message = result.failed > 0 + final message = result.cancelled + ? context.l10n.mapCache_downloadCancelled(result.downloaded) + : result.failed > 0 ? context.l10n.mapCache_cachedTilesWithFailed( result.downloaded, result.failed, @@ -323,12 +406,23 @@ class _MapCacheScreenState extends State { }); } - String _formatBytes(int bytes) { - if (bytes < 1024) return '$bytes B'; - if (bytes < 1024 * 1024) { - return '${(bytes / 1024).toStringAsFixed(1)} KB'; + void _cancelDownload() { + _cancelToken?.cancel(); + setState(() {}); + } + + String _formatBytes(int bytes, AppLocalizations l10n) { + const kb = 1024; + const mb = kb * 1024; + const gb = mb * 1024; + if (bytes < kb) return l10n.mapCache_sizeBytes('$bytes'); + if (bytes < mb) { + return l10n.mapCache_sizeKilobytes((bytes / kb).toStringAsFixed(1)); } - return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; + if (bytes < gb) { + return l10n.mapCache_sizeMegabytes((bytes / mb).toStringAsFixed(1)); + } + return l10n.mapCache_sizeGigabytes((bytes / gb).toStringAsFixed(2)); } @override @@ -354,7 +448,7 @@ class _MapCacheScreenState extends State { '${context.l10n.mapCache_summarySource(source.label)}\n' '${context.l10n.mapCache_summaryCachedTilesForSource(activeCachedTiles.length)}\n' '${context.l10n.mapCache_summaryCachedInSelection(cachedInSelection)}\n' - '${context.l10n.mapCache_summaryApproxCacheSize(_formatBytes(_cachedTileBytes))}'; + '${context.l10n.mapCache_summaryApproxCacheSize(_formatBytes(_cachedTileBytes, context.l10n))}'; final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; final isDesktop = _isDesktopPlatform(defaultTargetPlatform); @@ -392,20 +486,8 @@ class _MapCacheScreenState extends State { ) : const KeyboardOptions.disabled(), ), - onPositionChanged: (camera, hasGesture) { - final nextZoom = camera.zoom; - final nextBounds = camera.visibleBounds; - if (_overlayZoom != nextZoom || - _visibleBounds?.north != nextBounds.north || - _visibleBounds?.south != nextBounds.south || - _visibleBounds?.east != nextBounds.east || - _visibleBounds?.west != nextBounds.west) { - setState(() { - _overlayZoom = nextZoom; - _visibleBounds = nextBounds; - }); - } - }, + onPositionChanged: (camera, hasGesture) => + _onCameraChanged(camera), ), children: [ tileCache.buildTileLayer(context), @@ -415,8 +497,8 @@ class _MapCacheScreenState extends State { Polygon( points: _boundsToPolygon(selectedBounds), borderStrokeWidth: 2, - color: Colors.blue.withValues(alpha: 0.2), - borderColor: Colors.blue, + color: MapPalette.selected.withValues(alpha: 0.2), + borderColor: MapPalette.selected, ), ], ), @@ -428,12 +510,20 @@ class _MapCacheScreenState extends State { Positioned( top: 12, left: isDesktop ? 84 : 12, - child: Card( + child: DecoratedBox( + decoration: _overlayDecoration, child: Padding( - padding: const EdgeInsets.all(8), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 8, + ), child: Text( - 'Z: ${_overlayZoom.round()}:', - style: const TextStyle(fontSize: 12), + l10n.mapCache_zoomLevel(_overlayZoom.round()), + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: _overlayPrimaryTextColor, + ), ), ), ), @@ -441,24 +531,24 @@ class _MapCacheScreenState extends State { Positioned( top: 12, right: 12, - child: DecoratedBox( - decoration: BoxDecoration( - color: MeshPalette.bg1.withValues(alpha: 0.93), - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MeshPalette.line2), - ), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 6, - ), - child: Text( - selectedBounds == null - ? l10n.mapCache_noAreaSelected - : _formatBounds(selectedBounds, l10n), - style: MeshTheme.mono( - fontSize: 11, - color: MeshPalette.ink2, + left: isDesktop ? 200 : 130, + child: Align( + alignment: Alignment.topRight, + child: DecoratedBox( + decoration: _overlayDecoration, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + child: Text( + selectedBounds == null + ? l10n.mapCache_noAreaSelected + : _formatBounds(selectedBounds, l10n), + style: MeshTheme.mono( + fontSize: 13, + color: _overlaySecondaryTextColor, + ), ), ), ), @@ -474,158 +564,202 @@ class _MapCacheScreenState extends State { color: scheme.surfaceContainerLow, border: Border(top: BorderSide(color: scheme.outlineVariant)), ), - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - SectionHeader( - l10n.mapCache_cacheArea, - padding: const EdgeInsets.fromLTRB(0, 12, 0, 8), - ), - Row( - children: [ - Expanded( - child: ElevatedButton.icon( - icon: const Icon(Icons.crop_free), - label: Text(l10n.mapCache_useCurrentView), - onPressed: _isDownloading - ? null - : _setBoundsFromView, + // Cap the panel so the map keeps room in landscape; the controls + // scroll inside it. + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.5, + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + SectionHeader( + l10n.mapCache_cacheArea, + padding: const EdgeInsets.fromLTRB(0, 12, 0, 8), + ), + Row( + children: [ + Expanded( + child: ElevatedButton.icon( + icon: const Icon(Icons.crop_free), + label: Text(l10n.mapCache_useCurrentView), + onPressed: _isDownloading + ? null + : _setBoundsFromView, + ), ), + const SizedBox(width: 12), + TextButton( + onPressed: _isDownloading || selectedBounds == null + ? null + : _clearBounds, + child: Text(l10n.common_clear), + ), + ], + ), + const SizedBox(height: 12), + SectionHeader( + l10n.mapCache_zoomRange, + padding: const EdgeInsets.fromLTRB(0, 8, 0, 0), + ), + RangeSlider( + values: RangeValues( + _minZoom.toDouble(), + _maxZoom.toDouble(), ), - const SizedBox(width: 12), - TextButton( - onPressed: _isDownloading || selectedBounds == null - ? null - : _clearBounds, - child: Text(l10n.common_clear), - ), - ], - ), - const SizedBox(height: 12), - SectionHeader( - l10n.mapCache_zoomRange, - padding: const EdgeInsets.fromLTRB(0, 8, 0, 0), - ), - RangeSlider( - values: RangeValues( - _minZoom.toDouble(), - _maxZoom.toDouble(), + min: 3, + max: 18, + divisions: 15, + labels: RangeLabels('$_minZoom', '$_maxZoom'), + onChanged: _isDownloading + ? null + : (values) { + setState(() { + _minZoom = values.start.round(); + _maxZoom = values.end.round(); + }); + }, + onChangeEnd: _isDownloading + ? null + : (_) { + _saveZoomRange(); + }, ), - min: 3, - max: 18, - divisions: 15, - labels: RangeLabels('$_minZoom', '$_maxZoom'), - onChanged: _isDownloading - ? null - : (values) { - setState(() { - _minZoom = values.start.round(); - _maxZoom = values.end.round(); - }); - }, - onChangeEnd: _isDownloading - ? null - : (_) { - _saveZoomRange(); - }, - ), - Text( - l10n.mapCache_estimatedTiles(_estimatedTiles), - style: MeshTheme.mono( - fontSize: 12, - color: scheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 12), - TextFormField( - key: ValueKey( - '$cacheSummary|${activeCachedTiles.length}|$cachedInSelection|$_cachedTileBytes', - ), - initialValue: cacheSummary, - readOnly: true, - minLines: 4, - maxLines: 4, - decoration: InputDecoration( - labelText: _isLoadingCachedTiles - ? l10n.mapCache_cachedTilesLabel - : l10n.mapCache_cachedTileSummaryLabel, - border: const OutlineInputBorder(), - ), - ), - if (!source.allowsBulkDownload) ...[ - const SizedBox(height: 8), Text( - l10n.mapCache_bulkDownloadDisabledForSource( - source.label, - ), - style: MeshTheme.mono( - fontSize: 12, - color: MeshPalette.alert, - ), - ), - ], - if (_isDownloading) ...[ - const SizedBox(height: 8), - LinearProgressIndicator( - value: progressValue, - color: MeshPalette.blue, - backgroundColor: scheme.surfaceContainerHighest, - ), - const SizedBox(height: 4), - Text( - l10n.mapCache_downloadedTiles( - _completedTiles, - _estimatedTiles, - ), + l10n.mapCache_estimatedTiles(_estimatedTiles), style: MeshTheme.mono( fontSize: 12, color: scheme.onSurfaceVariant, ), ), - ], - const SizedBox(height: 12), - Row( - children: [ - Expanded( - child: ElevatedButton.icon( - icon: const Icon(Icons.download), - label: Text(l10n.mapCache_downloadTilesButton), - onPressed: - _isDownloading || - selectedBounds == null || - !source.allowsBulkDownload - ? null - : _startDownload, + const SizedBox(height: 12), + if (_estimatedTiles > + MapTileCacheService.maxBulkDownloadTiles) ...[ + const SizedBox(height: 4), + Text( + l10n.mapCache_tooManyTiles( + _estimatedTiles, + MapTileCacheService.maxBulkDownloadTiles, ), - ), - const SizedBox(width: 12), - OutlinedButton( - style: OutlinedButton.styleFrom( - foregroundColor: MeshPalette.alert, - side: const BorderSide( - color: MeshPalette.alertLine, - ), + style: TextStyle( + fontSize: 13, + color: MeshPalette.alert, ), - onPressed: _isDownloading ? null : _clearCache, - child: Text(l10n.mapCache_clearCacheButton), ), ], - ), - if (_failedTiles > 0 && !_isDownloading) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text( - l10n.mapCache_failedDownloads(_failedTiles), + const SizedBox(height: 12), + Text( + _isLoadingCachedTiles + ? l10n.mapCache_cachedTilesLabel + : l10n.mapCache_cachedTileSummaryLabel, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 4), + MeshCard( + margin: EdgeInsets.zero, + padding: const EdgeInsets.all(12), + child: SizedBox( + width: double.infinity, + child: SelectableText( + cacheSummary, + style: MeshTheme.mono( + fontSize: 13, + color: scheme.onSurface, + ), + ), + ), + ), + if (!source.allowsBulkDownload) ...[ + const SizedBox(height: 8), + Text( + l10n.mapCache_bulkDownloadDisabledForSource( + source.label, + ), style: MeshTheme.mono( fontSize: 12, color: MeshPalette.alert, ), ), + ], + if (_isDownloading) ...[ + const SizedBox(height: 8), + LinearProgressIndicator( + value: progressValue, + color: MeshPalette.blue, + backgroundColor: scheme.surfaceContainerHighest, + ), + const SizedBox(height: 4), + Text( + l10n.mapCache_downloadedTiles( + _completedTiles, + _estimatedTiles, + ), + style: MeshTheme.mono( + fontSize: 12, + color: scheme.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: _isDownloading + ? OutlinedButton.icon( + icon: const Icon( + Icons.stop_circle_outlined, + ), + label: Text(l10n.common_cancel), + onPressed: + (_cancelToken?.isCancelled ?? true) + ? null + : _cancelDownload, + ) + : ElevatedButton.icon( + icon: const Icon(Icons.download), + label: Text( + l10n.mapCache_downloadTilesButton, + ), + onPressed: + selectedBounds == null || + !source.allowsBulkDownload + ? null + : _startDownload, + ), + ), + const SizedBox(width: 12), + OutlinedButton( + style: OutlinedButton.styleFrom( + foregroundColor: MeshPalette.alert, + side: const BorderSide( + color: MeshPalette.alertLine, + ), + ), + onPressed: _isDownloading ? null : _clearCache, + child: Text(l10n.mapCache_clearCacheButton), + ), + ], ), - ], + if (_failedTiles > 0 && !_isDownloading) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + l10n.mapCache_failedDownloads(_failedTiles), + style: MeshTheme.mono( + fontSize: 12, + color: MeshPalette.alert, + ), + ), + ), + ], + ), ), ), ), diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 3efebd18..c6279c34 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -28,6 +28,7 @@ import '../utils/contact_search.dart'; import '../utils/disconnect_navigation_mixin.dart'; import '../utils/battery_utils.dart'; import '../utils/route_transitions.dart'; +import '../widgets/map_poi_cluster.dart'; import '../widgets/marker_label_dialog.dart'; import '../widgets/quick_switch_bar.dart'; import '../widgets/sync_progress_overlay.dart'; @@ -112,6 +113,12 @@ class _MapScreenState extends State with DisconnectNavigationMixin { List<_SharedMarker> _cachedSharedMarkers = const []; _NodeMarkersCacheKey? _nodeMarkersCacheKey; List _cachedNodeMarkers = const []; + // Online/recent status is derived from DateTime.now(); rebuild periodically + // so markers age even when the connector stays quiet. + Timer? _ageTimer; + // Camera computed from the visible points; only needed until the map has + // been positioned once. + ({LatLng center, double zoom})? _initialCamera; static const String _lastCameraKey = 'map_last_camera'; @@ -144,6 +151,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { @override void dispose() { + _ageTimer?.cancel(); _saveLastCamera(); _searchController.dispose(); _searchFocus.dispose(); @@ -174,7 +182,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Color get _overlayShadowColor => _useDarkOverlay ? MapPalette.markerShadow - : Colors.black.withValues(alpha: 0.18); + : MapPalette.markerShadow.withValues(alpha: 0.18); _NodeAge _ageOf(Contact contact) { final d = DateTime.now().difference(contact.lastSeen); @@ -205,6 +213,9 @@ class _MapScreenState extends State with DisconnectNavigationMixin { void initState() { super.initState(); _loadRemovedMarkers(); + _ageTimer = Timer.periodic(const Duration(seconds: 60), (_) { + if (mounted) setState(() {}); + }); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { context.read().getChannels(); @@ -266,6 +277,61 @@ class _MapScreenState extends State with DisconnectNavigationMixin { return zoom.clamp(4.0, 15.0); } + /// Centre and zoom that frame [allPoints], ignoring outliers more than two + /// standard deviations away. Returns null when there are no points. + ({LatLng center, double zoom})? _cameraForPoints(List allPoints) { + if (allPoints.isEmpty) return null; + if (allPoints.length < 3) { + double avgLat = 0.0; + double avgLon = 0.0; + for (final point in allPoints) { + avgLat += point.latitude; + avgLon += point.longitude; + } + return ( + center: LatLng(avgLat / allPoints.length, avgLon / allPoints.length), + zoom: 12.0, + ); + } + final latValues = allPoints.map((p) => p.latitude).toList(); + final lonValues = allPoints.map((p) => p.longitude).toList(); + + final meanLat = latValues.reduce((a, b) => a + b) / latValues.length; + final meanLon = lonValues.reduce((a, b) => a + b) / lonValues.length; + final latStdDev = _standardDeviation(latValues); + final lonStdDev = _standardDeviation(lonValues); + + final filteredPoints = allPoints + .where( + (p) => + (p.latitude - meanLat).abs() <= latStdDev * 2 && + (p.longitude - meanLon).abs() <= lonStdDev * 2, + ) + .toList(); + + if (filteredPoints.isEmpty) { + return ( + center: LatLng(meanLat, meanLon), + zoom: _zoomFromStdDev(latStdDev, lonStdDev), + ); + } + final filteredLatValues = filteredPoints.map((p) => p.latitude).toList(); + final filteredLonValues = filteredPoints.map((p) => p.longitude).toList(); + final avgLat = filteredLatValues.reduce((a, b) => a + b); + final avgLon = filteredLonValues.reduce((a, b) => a + b); + return ( + center: LatLng( + avgLat / filteredPoints.length, + avgLon / filteredPoints.length, + ), + // Use std deviation of filtered points for zoom + zoom: _zoomFromStdDev( + _standardDeviation(filteredLatValues), + _standardDeviation(filteredLonValues), + ), + ); + } + bool _isDesktopPlatform(TargetPlatform platform) { return platform == TargetPlatform.linux || platform == TargetPlatform.windows || @@ -282,8 +348,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Widget _buildControlRail( BuildContext context, { - required LatLng center, - required double zoom, + required ({LatLng center, double zoom}) Function() computeCamera, required MeshCoreConnector connector, }) { final hasSelf = @@ -326,7 +391,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { color: _overlayPrimaryTextColor, icon: const Icon(Icons.crop_free), tooltip: context.l10n.map_centerMap, - onPressed: () => _mapController.move(center, zoom), + onPressed: () { + final camera = computeCamera(); + _mapController.move(camera.center, camera.zoom); + }, ), if (hasSelf) IconButton( @@ -538,84 +606,32 @@ class _MapScreenState extends State with DisconnectNavigationMixin { } // Only the first frame's camera matters; afterwards reuse it instead - // of re-reading prefs on every rebuild. - final (center: fallbackCenter, zoom: fallbackZoom) = _hasInitializedMap - ? (_cachedFallbackCamera ??= _fallbackCamera(connector)) - : _fallbackCamera(connector); - LatLng center = fallbackCenter; - double initialZoom = fallbackZoom; - if (contactsWithLocation.isNotEmpty || sharedMarkers.isNotEmpty) { - final allPoints = [ - ...contactsWithLocation.map( - (c) => LatLng(c.latitude!, c.longitude!), - ), - ...sharedMarkers.map((m) => m.position), - ]; - if (allPoints.length >= 3) { - final latValues = allPoints.map((p) => p.latitude).toList(); - final lonValues = allPoints.map((p) => p.longitude).toList(); - - final meanLat = - latValues.reduce((a, b) => a + b) / latValues.length; - final meanLon = - lonValues.reduce((a, b) => a + b) / lonValues.length; - final latStdDev = _standardDeviation(latValues); - final lonStdDev = _standardDeviation(lonValues); - - final filteredPoints = allPoints - .where( - (p) => - (p.latitude - meanLat).abs() <= latStdDev * 2 && - (p.longitude - meanLon).abs() <= lonStdDev * 2, - ) - .toList(); - - if (filteredPoints.isNotEmpty) { - final filteredLatValues = filteredPoints - .map((p) => p.latitude) - .toList(); - final filteredLonValues = filteredPoints - .map((p) => p.longitude) - .toList(); - final avgLat = filteredLatValues.reduce((a, b) => a + b); - final avgLon = filteredLonValues.reduce((a, b) => a + b); - center = LatLng( - avgLat / filteredPoints.length, - avgLon / filteredPoints.length, - ); - // Use std deviation of filtered points for zoom - final filteredLatStdDev = _standardDeviation(filteredLatValues); - final filteredLonStdDev = _standardDeviation(filteredLonValues); - initialZoom = _zoomFromStdDev( - filteredLatStdDev, - filteredLonStdDev, - ); - } else { - center = LatLng(meanLat, meanLon); - initialZoom = _zoomFromStdDev(latStdDev, lonStdDev); - } - } else { - double avgLat = 0.0; - double avgLon = 0.0; - for (final point in allPoints) { - avgLat += point.latitude; - avgLon += point.longitude; - } - center = LatLng( - avgLat / allPoints.length, - avgLon / allPoints.length, - ); - initialZoom = 12.0; + // of re-reading prefs and re-running the spread statistics on every + // rebuild. The "center map" control recomputes on demand. + ({LatLng center, double zoom}) computeCamera() { + final fallback = _hasInitializedMap + ? (_cachedFallbackCamera ??= _fallbackCamera(connector)) + : _fallbackCamera(connector); + if (highlightPosition != null) { + return (center: highlightPosition, zoom: widget.highlightZoom); } + return _cameraForPoints([ + ...contactsWithLocation.map( + (c) => LatLng(c.latitude!, c.longitude!), + ), + ...sharedMarkers.map((m) => m.position), + ]) ?? + fallback; } - if (highlightPosition != null) { - center = highlightPosition; - initialZoom = widget.highlightZoom; - } + + final (center: center, zoom: initialZoom) = _hasInitializedMap + ? (_initialCamera ??= computeCamera()) + : computeCamera(); // Re center map after removed markers have loaded if (!_hasInitializedMap && _removedMarkersLoaded) { _hasInitializedMap = true; + _initialCamera = (center: center, zoom: initialZoom); _showNodeLabels = initialZoom >= _labelZoomThreshold; _zoom = initialZoom; WidgetsBinding.instance.addPostFrameCallback((_) { @@ -625,7 +641,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { }); } - final allowBack = !connector.isConnected; + // Opened as a detail screen (e.g. from a chat's location link): let the + // user go back. As a quick-switch root, keep the tab-like behaviour. + final isDetailScreen = !widget.hideBackButton; + final allowBack = isDetailScreen || !connector.isConnected; final visibleContacts = _filterContactsBySettings( contactsWithLocation, @@ -658,6 +677,9 @@ class _MapScreenState extends State with DisconnectNavigationMixin { title: AppBarTitle(context.l10n.map_title), centerTitle: true, automaticallyImplyLeading: false, + leading: isDetailScreen && Navigator.canPop(context) + ? BackButton(onPressed: () => Navigator.maybePop(context)) + : null, bottom: const SyncProgressAppBarBottom(), actions: [ PopupMenuButton( @@ -864,7 +886,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ), child: const Icon( Icons.location_on, - color: Colors.white, + color: MapPalette.markerOutline, size: 25, ), ), @@ -895,45 +917,20 @@ class _MapScreenState extends State with DisconnectNavigationMixin { showLabels: _showNodeLabels, selectedContact: selectedContact, ), - ...sharedMarkers.map(_buildSharedMarker), - if (connector.selfLatitude != null && - connector.selfLongitude != null) - Marker( - point: LatLng( - connector.selfLatitude!, - connector.selfLongitude!, - ), - width: 40, - height: 40, - child: IgnorePointer( - ignoring: true, - child: Container( - width: 36, - height: 36, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: MapPalette.panelDark, - border: Border.all( - color: MapPalette.markerOutline, - width: 2.5, - ), - boxShadow: [ - const BoxShadow( - color: MapPalette.markerShadow, - blurRadius: 8, - offset: Offset(0, 2), - ), - ], - ), - alignment: Alignment.center, - child: const Icon( - Icons.person_pin_circle, - color: MapPalette.selected, - size: 22, - ), - ), - ), - ), + ..._buildPoiAndSelfMarkers( + sharedMarkers, + selfPosition: + connector.selfLatitude != null && + connector.selfLongitude != null + ? LatLng( + connector.selfLatitude!, + connector.selfLongitude!, + ) + : null, + clusterPois: + !settings.mapShowOverlaps && + !_isBuildingPathTrace, + ), if (_showNodeLabels && connector.selfLatitude != null && connector.selfLongitude != null) @@ -951,8 +948,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { if (selectedContact == null) _buildControlRail( context, - center: center, - zoom: initialZoom, + computeCamera: computeCamera, connector: connector, ), if (!_isBuildingPathTrace) @@ -1097,10 +1093,17 @@ class _MapScreenState extends State with DisconnectNavigationMixin { final eligible = candidates .where((c) => !c.hasLocation && c.lastSeen.isAfter(cutoff)) .toList(); - for (final c in eligible) { - final key = c.publicKeyHex; - if (pathHistory.isCached(key) || _storedPaths.containsKey(key)) continue; - _storedPaths[key] = await pathHistory.readStoredPaths(key); + final toLoad = { + for (final c in eligible) + if (!pathHistory.isCached(c.publicKeyHex) && + !_storedPaths.containsKey(c.publicKeyHex)) + c.publicKeyHex, + }.toList(); + if (toLoad.isNotEmpty) { + final loaded = await Future.wait(toLoad.map(pathHistory.readStoredPaths)); + for (var i = 0; i < toLoad.length; i++) { + _storedPaths[toLoad[i]] = loaded[i]; + } } if (!mounted) { _guessInFlight = false; @@ -1454,46 +1457,56 @@ class _MapScreenState extends State with DisconnectNavigationMixin { point: LatLng(contact.latitude!, contact.longitude!), width: size, height: size, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onLongPress: () { - if (_isBuildingPathTrace) _showNodeInfo(context, contact); - }, - onSecondaryTap: () { - if (_isBuildingPathTrace) _showNodeInfo(context, contact); - }, - onTap: () => _isBuildingPathTrace - ? _addToPath(context, contact) - : _selectNode(contact), - child: Center( - child: dot && !selected - ? Container( - width: 15, - height: 15, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: baseColor, - border: Border.all( - color: MapPalette.markerOutline, - width: 2, - ), - boxShadow: const [ - BoxShadow( - color: MapPalette.markerShadow, - blurRadius: 6, - offset: Offset(0, 2), + child: Semantics( + button: true, + selected: selected, + label: context.l10n.map_nodeMarkerSemantics( + contact.name, + contact.typeLabel(context.l10n), + _ageLabel(age), + ), + excludeSemantics: true, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onLongPress: () { + if (_isBuildingPathTrace) _showNodeInfo(context, contact); + }, + onSecondaryTap: () { + if (_isBuildingPathTrace) _showNodeInfo(context, contact); + }, + onTap: () => _isBuildingPathTrace + ? _addToPath(context, contact) + : _selectNode(contact), + child: Center( + child: dot && !selected + ? Container( + width: 15, + height: 15, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: baseColor, + border: Border.all( + color: MapPalette.markerOutline, + width: 2, ), - ], + boxShadow: const [ + BoxShadow( + color: MapPalette.markerShadow, + blurRadius: 6, + offset: Offset(0, 2), + ), + ], + ), + ) + : _buildNodeMarkerWidget( + color: baseColor, + icon: _getNodeIcon(contact.type), + selected: selected, + stale: stale, + online: online, + batteryLow: batteryLow, ), - ) - : _buildNodeMarkerWidget( - color: baseColor, - icon: _getNodeIcon(contact.type), - selected: selected, - stale: stale, - online: online, - batteryLow: batteryLow, - ), + ), ), ), ); @@ -1544,9 +1557,9 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Text( '$count', style: MeshTheme.mono( - fontSize: count >= 100 ? 11.5 : 13.5, + fontSize: count >= 100 ? 13 : 15, fontWeight: FontWeight.w800, - color: Colors.white, + color: MapPalette.markerOutline, ), ), if (online > 0) @@ -1557,7 +1570,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { decoration: BoxDecoration( shape: BoxShape.circle, color: MapPalette.online, - border: Border.all(color: Colors.white, width: 1), + border: Border.all( + color: MapPalette.markerOutline, + width: 1, + ), ), ), ], @@ -1589,16 +1605,15 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Marker _buildNodeLabelMarker({required LatLng point, required String label}) { return Marker( point: point, - width: 120, - height: 24, + width: 140, + height: 26, alignment: Alignment.topCenter, child: IgnorePointer( child: Transform.translate( offset: const Offset(0, -20), - child: FittedBox( - fit: BoxFit.contain, + child: Center( child: Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), decoration: BoxDecoration( color: _overlayPanelColor, borderRadius: BorderRadius.circular(MeshRadii.xs), @@ -1617,10 +1632,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { maxLines: 1, overflow: TextOverflow.ellipsis, style: MeshTheme.mono( - fontSize: 10, + fontSize: 12, fontWeight: FontWeight.w700, color: _overlayPrimaryTextColor, - ), + ).copyWith(height: 1.15), ), ), ), @@ -1729,7 +1744,11 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ], ), alignment: Alignment.center, - child: Icon(icon, color: Colors.white, size: selected ? 22 : 19), + child: Icon( + icon, + color: MapPalette.markerOutline, + size: selected ? 22 : 19, + ), ), Positioned( right: selected ? -1 : -2, @@ -1744,7 +1763,11 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ), alignment: Alignment.center, child: batteryLow - ? const Icon(Icons.battery_alert, size: 10, color: Colors.white) + ? const Icon( + Icons.battery_alert, + size: 12, + color: MapPalette.markerOutline, + ) : null, ), ), @@ -1758,13 +1781,13 @@ class _MapScreenState extends State with DisconnectNavigationMixin { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(icon, size: 15, color: color), + Icon(icon, size: 18, color: color), const SizedBox(width: 8), Expanded( child: Text( label, style: TextStyle( - fontSize: 12, + fontSize: 14, fontWeight: FontWeight.w600, color: _overlaySecondaryTextColor, ), @@ -1884,24 +1907,22 @@ class _MapScreenState extends State with DisconnectNavigationMixin { clipBehavior: Clip.antiAlias, child: InkWell( onTap: () => setState(() => _statsExpanded = !_statsExpanded), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 11, - ), + child: Container( + constraints: const BoxConstraints(minHeight: 46), + padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( mainAxisSize: MainAxisSize.min, children: [ const Icon( Icons.hub, - size: 15, + size: 18, color: MapPalette.selected, ), const SizedBox(width: 6), Text( '$visibleCount', style: MeshTheme.mono( - fontSize: 13, + fontSize: 15, fontWeight: FontWeight.w700, color: _overlayPrimaryTextColor, ), @@ -2038,15 +2059,16 @@ class _MapScreenState extends State with DisconnectNavigationMixin { HapticFeedback.selectionClick(); onTap(); }, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), + child: Container( + constraints: const BoxConstraints(minHeight: 44), + padding: const EdgeInsets.symmetric(horizontal: 14), child: Row( mainAxisSize: MainAxisSize.min, children: [ if (selected) ...[ Icon( Icons.check, - size: 13, + size: 16, color: _overlayPrimaryTextColor, ), const SizedBox(width: 4), @@ -2054,7 +2076,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Text( label, style: TextStyle( - fontSize: 12.5, + fontSize: 14, fontWeight: FontWeight.w600, color: selected ? _overlayPrimaryTextColor @@ -2138,7 +2160,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Text( c.name, style: TextStyle( - fontSize: 13.5, + fontSize: 15, fontWeight: FontWeight.w600, color: _overlayPrimaryTextColor, ), @@ -2147,7 +2169,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Text( c.publicKeyHex.substring(0, 12), style: MeshTheme.mono( - fontSize: 10.5, + fontSize: 12, color: _overlaySecondaryTextColor, ), ), @@ -2165,7 +2187,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { context.l10n.map_noGps.toUpperCase(), style: MeshTheme.accentLabel( color: _overlayMutedTextColor, - fontSize: 8.5, + fontSize: 12, ), ), ], @@ -2221,7 +2243,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { }) { return Container( margin: const EdgeInsets.only(top: 6), - width: 230, + width: 250, padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), decoration: BoxDecoration( color: _overlayPanelColor, @@ -2299,17 +2321,14 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Expanded( child: Text( label, - style: TextStyle( - fontSize: 12.5, - color: _overlaySecondaryTextColor, - ), + style: TextStyle(fontSize: 14, color: _overlaySecondaryTextColor), overflow: TextOverflow.ellipsis, ), ), Text( '$value', style: MeshTheme.mono( - fontSize: 13, + fontSize: 14, fontWeight: FontWeight.w700, color: _overlayPrimaryTextColor, ), @@ -2392,7 +2411,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { StatusChip( label: _ageLabel(age), color: _ageColor(age), - fontSize: 9.5, + fontSize: 12, pulse: age == _NodeAge.online, ), const SizedBox(width: 6), @@ -2400,7 +2419,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { child: Text( contact.typeLabel(context.l10n), style: TextStyle( - fontSize: 11.5, + fontSize: 13, color: _overlaySecondaryTextColor, ), overflow: TextOverflow.ellipsis, @@ -2442,7 +2461,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { pathHashByteWidth: connector.pathHashByteWidth, ), ), - _miniMeta('ID', contact.publicKeyHex.substring(0, 12)), + _miniMeta( + context.l10n.map_nodeId, + contact.publicKeyHex.substring(0, 12), + ), if (pos != null) _miniMeta( context.l10n.map_location, @@ -2451,7 +2473,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ], ), const SizedBox(height: 10), - Row( + Wrap( + spacing: 8, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, children: [ ..._selectedNodeActions(context, contact, connector), TextButton( @@ -2465,7 +2490,10 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ? null : _selectedGuessPos, ), - child: Text(context.l10n.map_details), + child: Text( + context.l10n.map_details, + style: const TextStyle(fontSize: 14), + ), ), ], ), @@ -2485,16 +2513,13 @@ class _MapScreenState extends State with DisconnectNavigationMixin { label.toUpperCase(), style: MeshTheme.accentLabel( color: _overlayMutedTextColor, - fontSize: 8, + fontSize: 12, ), ), const SizedBox(height: 1), Text( value, - style: MeshTheme.mono( - fontSize: 11.5, - color: _overlayPrimaryTextColor, - ), + style: MeshTheme.mono(fontSize: 13, color: _overlayPrimaryTextColor), ), ], ); @@ -2506,17 +2531,14 @@ class _MapScreenState extends State with DisconnectNavigationMixin { MeshCoreConnector connector, ) { Widget action(String label, IconData icon, VoidCallback onPressed) { - return Padding( - padding: const EdgeInsets.only(right: 8), - child: FilledButton.icon( - style: FilledButton.styleFrom( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), - visualDensity: VisualDensity.compact, - ), - onPressed: onPressed, - icon: Icon(icon, size: 16), - label: Text(label, style: const TextStyle(fontSize: 12.5)), + return FilledButton.icon( + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + minimumSize: const Size(0, 44), ), + onPressed: onPressed, + icon: Icon(icon, size: 18), + label: Text(label, style: const TextStyle(fontSize: 14)), ); } @@ -2581,7 +2603,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { // Build a _SharedMarker per message (history empty), grouped by dedupe key. // Afterwards pick the latest per key and fill its history from older ones. final updatesByKey = >{}; - final selfName = connector.selfName ?? 'Me'; + final selfName = connector.selfName ?? context.l10n.chat_me; void addUpdate(_SharedMarker update) { (updatesByKey[update.id] ??= <_SharedMarker>[]).add(update); @@ -2675,32 +2697,31 @@ class _MapScreenState extends State with DisconnectNavigationMixin { return _cachedSharedMarkers; } + Color _sharedMarkerColor(_SharedMarker marker) => marker.isChannel + ? (marker.isPublicChannel ? MapPalette.cluster : MapPalette.router) + : MapPalette.shared; + Marker _buildSharedMarker(_SharedMarker marker) { - final markerColor = marker.isChannel - ? (marker.isPublicChannel ? MapPalette.cluster : MapPalette.router) - : MapPalette.shared; + // Square marker with the circle centred, so the pin sits exactly on its + // coordinate (the default Marker alignment is centre). return Marker( point: marker.position, - width: 60, - height: 60, - child: GestureDetector( - onTap: () async { - if (_removedMarkerIds.contains(marker.id)) { - setState(() { - _removedMarkerIds.remove(marker.id); - }); - await _markerService.saveRemovedIds(_removedMarkerIds); - } - _showMarkerInfo(marker); - }, - child: Column( - children: [ - Container( + width: 44, + height: 44, + child: Semantics( + button: true, + label: context.l10n.map_sharedMarkerSemantics(marker.label), + excludeSemantics: true, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _showMarkerInfo(marker), + child: Center( + child: Container( width: 36, height: 36, decoration: BoxDecoration( shape: BoxShape.circle, - color: markerColor, + color: _sharedMarkerColor(marker), border: Border.all(color: MapPalette.markerOutline, width: 2.5), boxShadow: const [ BoxShadow( @@ -2711,14 +2732,209 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ], ), alignment: Alignment.center, - child: const Icon(Icons.flag, color: Colors.white, size: 19), + child: const Icon( + Icons.flag, + color: MapPalette.markerOutline, + size: 19, + ), ), - ], + ), ), ), ); } + Marker _buildSelfMarker(LatLng position) { + return Marker( + point: position, + width: 40, + height: 40, + child: IgnorePointer( + child: Semantics( + label: context.l10n.pathTrace_you, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: MapPalette.panelDark, + border: Border.all(color: MapPalette.markerOutline, width: 2.5), + boxShadow: const [ + BoxShadow( + color: MapPalette.markerShadow, + blurRadius: 8, + offset: Offset(0, 2), + ), + ], + ), + alignment: Alignment.center, + child: const Icon( + Icons.person_pin_circle, + color: MapPalette.selected, + size: 22, + ), + ), + ), + ), + ); + } + + /// Shared POI markers plus the "You" marker. Outside overlaps/path-trace + /// mode, POIs falling into the same ~64px grid cell at the current zoom + /// (the same grid the node clusters use) collapse into one numbered marker. + /// The self position joins its cell, so POIs placed at or near the user's + /// position are not hidden under the "You" marker. + List _buildPoiAndSelfMarkers( + List<_SharedMarker> pois, { + required LatLng? selfPosition, + required bool clusterPois, + }) { + if (!clusterPois) { + return [ + ...pois.map(_buildSharedMarker), + if (selfPosition != null) _buildSelfMarker(selfPosition), + ]; + } + final cellDeg = mapGridCellDegrees(_zoom); + final cells = mapGridCluster(pois, (m) => m.position, cellDeg); + final selfCellKey = selfPosition == null + ? null + : mapGridCellKey(selfPosition, cellDeg); + final markers = []; + Marker? selfMarker; + cells.forEach((key, members) { + if (key == selfCellKey) { + selfMarker = _poiClusterMarker(members, selfPosition: selfPosition); + } else if (members.length == 1) { + markers.add(_buildSharedMarker(members.first)); + } else { + markers.add(_poiClusterMarker(members)); + } + }); + // Self is drawn last so it stays on top of nearby node markers. + if (selfPosition != null) { + markers.add(selfMarker ?? _buildSelfMarker(selfPosition)); + } + return markers; + } + + Marker _poiClusterMarker( + List<_SharedMarker> members, { + LatLng? selfPosition, + }) { + final count = members.length; + LatLng point; + if (selfPosition != null) { + point = selfPosition; + } else { + double lat = 0, lon = 0; + for (final m in members) { + lat += m.position.latitude; + lon += m.position.longitude; + } + point = LatLng(lat / count, lon / count); + } + final l10n = context.l10n; + return Marker( + point: point, + width: 48, + height: 48, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _showPoiClusterSheet(members, selfPosition: selfPosition), + child: Center( + child: PoiClusterMarker( + count: count, + includesSelf: selfPosition != null, + semanticLabel: selfPosition != null + ? l10n.map_youWithMarkers(count) + : l10n.map_poiClusterSemantics(count), + ), + ), + ), + ); + } + + void _showPoiClusterSheet( + List<_SharedMarker> members, { + LatLng? selfPosition, + }) { + HapticFeedback.selectionClick(); + showMeshSheet( + context, + builder: (sheetContext) { + final l10n = sheetContext.l10n; + final scheme = Theme.of(sheetContext).colorScheme; + return SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.7, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BottomSheetHeader( + title: selfPosition != null + ? l10n.map_youWithMarkers(members.length) + : l10n.map_poiClusterTitle(members.length), + ), + Flexible( + child: ListView( + shrinkWrap: true, + children: [ + if (selfPosition != null) + ListTile( + leading: const Icon( + Icons.person_pin_circle, + color: MapPalette.selected, + ), + title: Text(l10n.pathTrace_you), + subtitle: Text( + '${selfPosition.latitude.toStringAsFixed(5)}, ${selfPosition.longitude.toStringAsFixed(5)}', + style: MeshTheme.mono( + fontSize: 13, + color: scheme.onSurfaceVariant, + ), + ), + onTap: () { + Navigator.pop(sheetContext); + _mapController.move(selfPosition, max(_zoom, 16)); + }, + ), + for (final marker in members) + ListTile( + leading: Icon( + Icons.flag, + color: _sharedMarkerColor(marker), + ), + title: Text( + marker.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + '${marker.fromName} · ${_formatLastSeen(marker.timestamp)}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: const Icon(Icons.chevron_right), + onTap: () { + Navigator.pop(sheetContext); + _showMarkerInfo(marker); + }, + ), + ], + ), + ), + ], + ), + ), + ); + }, + ); + } + void _showRepeaterLogin(BuildContext context, Contact repeater) { showDialog( context: context, @@ -2974,6 +3190,22 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ), if (marker.flags.isNotEmpty) _buildInfoRow(context.l10n.map_flags, marker.flags), + const SizedBox(height: 12), + Text( + context.l10n.map_markerHideHint, + style: TextStyle( + fontSize: 13, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 4), + Text( + context.l10n.map_markerRemoveHint, + style: TextStyle( + fontSize: 13, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), actions: [ @@ -2991,14 +3223,8 @@ class _MapScreenState extends State with DisconnectNavigationMixin { foregroundColor: Theme.of(context).colorScheme.error, ), onPressed: () async { - setState(() { - _hiddenMarkerIds.add(marker.id); - _removedMarkerIds.add(marker.id); - }); - await _markerService.saveRemovedIds(_removedMarkerIds); - if (dialogContext.mounted) { - Navigator.pop(dialogContext); - } + Navigator.pop(dialogContext); + await _removeMarkerWithUndo(marker); }, child: Text(context.l10n.common_remove), ), @@ -3011,6 +3237,47 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } + Future _removeMarkerWithUndo(_SharedMarker marker) async { + final previous = Set.from(_removedMarkerIds); + final wasHidden = _hiddenMarkerIds.contains(marker.id); + setState(() { + _hiddenMarkerIds.add(marker.id); + _removedMarkerIds = {...previous, marker.id}; + }); + await _markerService.saveRemovedIds(_removedMarkerIds); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.map_markerRemoved), + action: SnackBarAction( + label: context.l10n.common_undo, + onPressed: () async { + if (!mounted) return; + setState(() { + if (!wasHidden) _hiddenMarkerIds.remove(marker.id); + _removedMarkerIds = Set.from(previous); + }); + await _markerService.saveRemovedIds(_removedMarkerIds); + }, + ), + ); + } + + Future _restoreRemovedMarkers() async { + final count = _removedMarkerIds.length; + if (count == 0) return; + setState(() { + _hiddenMarkerIds.removeAll(_removedMarkerIds); + _removedMarkerIds = {}; + }); + await _markerService.saveRemovedIds(_removedMarkerIds); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.map_markersRestored(count)), + ); + } + Widget _buildInfoRow(String label, String value) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), @@ -3081,18 +3348,9 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ListTile( leading: const Icon(Icons.my_location), title: Text(context.l10n.map_setAsMyLocation), - onTap: () async { - final messenger = ScaffoldMessenger.of(context); - final successMsg = context.l10n.settings_locationUpdated; + onTap: () { Navigator.pop(sheetContext); - if (!connector.isConnected) return; - await connector.setNodeLocation( - lat: position.latitude, - lon: position.longitude, - ); - await connector.refreshDeviceInfo(); - if (!mounted) return; - messenger.showSnackBar(SnackBar(content: Text(successMsg))); + _confirmAndSetMyLocation(connector, position); }, ), ListTile( @@ -3106,6 +3364,72 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } + Future _confirmAndSetMyLocation( + MeshCoreConnector connector, + LatLng position, + ) async { + if (!connector.isConnected) return; + final l10n = context.l10n; + final latText = position.latitude.toStringAsFixed(6); + final lonText = position.longitude.toStringAsFixed(6); + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(l10n.map_setLocationConfirmTitle), + content: Text(l10n.map_setLocationConfirmBody(latText, lonText)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(l10n.map_setLocationAction), + ), + ], + ), + ); + if (confirmed != true || !mounted || !connector.isConnected) return; + + // The firmware stores coordinates as int32 micro-degrees. + bool matches() { + final lat = connector.selfLatitude; + final lon = connector.selfLongitude; + return lat != null && + lon != null && + (lat - position.latitude).abs() < 2e-6 && + (lon - position.longitude).abs() < 2e-6; + } + + var ok = false; + try { + await connector.setNodeLocation( + lat: position.latitude, + lon: position.longitude, + ); + await connector.refreshDeviceInfo(); + // Self info arrives asynchronously after the query; wait for it. + final deadline = DateTime.now().add(const Duration(seconds: 6)); + while (mounted && connector.isConnected) { + if (matches()) { + ok = true; + break; + } + if (DateTime.now().isAfter(deadline)) break; + await Future.delayed(const Duration(milliseconds: 250)); + } + } catch (e) { + debugPrint('Set node location failed: $e'); + } + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text( + ok ? l10n.map_locationSetSuccess : l10n.map_locationSetFailed, + ), + ); + } + Future _shareMarker({ required BuildContext context, required MeshCoreConnector connector, @@ -3435,7 +3759,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { trailing: Text( _getTimeFilterLabel(settings.mapTimeFilterHours), style: MeshTheme.mono( - fontSize: 11, + fontSize: 13, color: scheme.onSurfaceVariant, ), ), @@ -3485,6 +3809,22 @@ class _MapScreenState extends State with DisconnectNavigationMixin { onChanged: (value) => service.setMapShowMarkers(value), ), + ListTile( + leading: const Icon(Icons.restore), + title: Text( + sheetContext.l10n.map_restoreRemovedMarkers, + ), + subtitle: Text( + sheetContext.l10n.map_restoreRemovedMarkersSubtitle( + _removedMarkerIds.length, + ), + ), + enabled: _removedMarkerIds.isNotEmpty, + onTap: () async { + await _restoreRemovedMarkers(); + setSheetState(() {}); + }, + ), SwitchListTile( title: Text(sheetContext.l10n.map_clusterNodes), subtitle: Text( diff --git a/lib/screens/neighbors_screen.dart b/lib/screens/neighbors_screen.dart index c3537948..51bef191 100644 --- a/lib/screens/neighbors_screen.dart +++ b/lib/screens/neighbors_screen.dart @@ -14,6 +14,9 @@ import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/routing_sheet.dart'; import '../helpers/snack_bar_builder.dart'; +import '../l10n/app_localizations.dart'; +import '../widgets/repeater_login_dialog.dart'; +import 'repeater_hub_screen.dart'; class NeighborsScreen extends StatefulWidget { final Contact repeater; @@ -100,22 +103,22 @@ class _NeighborsScreenState extends State { }); } - String fmtDuration(double seconds) { + static String fmtDuration(AppLocalizations l10n, double seconds) { if (seconds < 60) { - return '${seconds.toStringAsFixed(1)}s'; + return l10n.neighbors_durationSeconds(seconds.toStringAsFixed(1)); } final int m = (seconds ~/ 60).toInt(); final double s = seconds - (60 * m); if (m < 60) { - return '${m}m ${s.toStringAsFixed(0)}s'; + return l10n.neighbors_durationMinutes(m, s.toStringAsFixed(0)); } final int h = m ~/ 60; final int m2 = m % 60; - return '${h}h ${m2}m'; + return l10n.neighbors_durationHours(h, m2); } static List> parseNeighborsData( @@ -184,11 +187,6 @@ class _NeighborsScreenState extends State { _loadNeighbors(offset: parsedNeighbors.length); return; } - showDismissibleSnackBar( - context, - content: Text(context.l10n.neighbors_receivedData), - backgroundColor: Theme.of(context).colorScheme.tertiary, - ); setState(() { _isLoading = false; _isLoaded = true; @@ -343,7 +341,22 @@ class _NeighborsScreenState extends State { child: ListView( padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [ - if (!_isLoaded && + // First request still in flight: show progress, not "no data". + if (_isLoading && _parsedNeighbors == null) + Padding( + padding: const EdgeInsets.symmetric(vertical: 64), + child: Column( + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 16), + Text( + l10n.common_loading, + style: const TextStyle(fontSize: 16), + ), + ], + ), + ) + else if (!_isLoaded && !_hasData && (_parsedNeighbors == null || _parsedNeighbors!.isEmpty)) EmptyState(icon: Icons.wifi_find, title: l10n.neighbors_noData), @@ -391,12 +404,15 @@ class _NeighborsScreenState extends State { final snrColor = MeshTheme.snrColor(snr, blocked: false); final heardLabel = l10n.neighbors_heardAgo( - fmtDuration(lastHeardSeconds + 0.0), + fmtDuration(l10n, lastHeardSeconds + 0.0), ); + // Only repeaters saved on the radio can be logged into. + final canOpen = contact != null && contact.isActive; return MeshCard( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), margin: const EdgeInsets.symmetric(vertical: 4), + onTap: canOpen ? () => _openNeighbor(contact) : null, child: Row( children: [ AvatarCircle( @@ -426,7 +442,7 @@ class _NeighborsScreenState extends State { maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( - fontSize: 12, + fontSize: 13, color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), @@ -443,15 +459,43 @@ class _NeighborsScreenState extends State { Text( '${snr.toStringAsFixed(1)} dB', style: MeshTheme.mono( - fontSize: 11, + fontSize: 13, fontWeight: FontWeight.w600, color: snrColor, ), ), ], ), + if (canOpen) ...[ + const SizedBox(width: 4), + Icon(Icons.chevron_right, size: 24, color: scheme.onSurfaceVariant), + ], ], ), ); } + + /// Opens a resolved neighbor the same way the contacts list does: + /// repeaters go through the login dialog to the repeater hub. + void _openNeighbor(Contact contact) { + showDialog( + context: context, + builder: (dialogContext) => RepeaterLoginDialog( + repeater: contact, + onLogin: (password, isAdmin) { + if (!mounted) return; + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RepeaterHubScreen( + repeater: contact, + password: password, + isAdmin: isAdmin, + ), + ), + ); + }, + ), + ); + } } diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index d0401364..f0bee80e 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -18,6 +18,8 @@ import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/services/map_tile_cache_service.dart'; import 'package:meshcore_open/services/path_history_service.dart'; import 'package:meshcore_open/utils/app_logger.dart'; +import 'package:meshcore_open/helpers/snack_bar_builder.dart'; +import 'package:meshcore_open/widgets/path_map_scaffold.dart'; import 'package:meshcore_open/widgets/path_map_ui.dart'; import 'package:meshcore_open/widgets/snr_indicator.dart'; import 'package:provider/provider.dart'; @@ -80,9 +82,9 @@ class PathTraceMapScreen extends StatefulWidget { class _PathTraceMapScreenState extends State with SingleTickerProviderStateMixin { - static const double _labelZoomThreshold = 8.5; - static const double _mapMinZoom = 2.0; - static const double _mapMaxZoom = 18.0; + static const double _labelZoomThreshold = kPathMapLabelZoomThreshold; + // Used when the radio never acknowledges the trace request. + static const Duration _sendAckTimeout = Duration(seconds: 15); //miles to meters conversion for filtering out repeaters that are too far from the last known GPS hop to be a likely match, to avoid false matches that throw off the inferred positions of other hops in the path static const double _maxRepeaterMatchDistanceMeters = 40 * 1609.344; @@ -130,6 +132,10 @@ class _PathTraceMapScreenState extends State bool _animationEnabled = true; bool _followPacket = false; + // Hop-prefix -> contact lookups, invalidated when the contact list changes. + final Map _hopContactCache = {}; + int? _hopContactCacheSignature; + String _formatPathPrefixes(Uint8List pathBytes, [int? hashByteWidth]) { return PathHelper.splitPathBytes( pathBytes, @@ -235,15 +241,12 @@ class _PathTraceMapScreenState extends State /// Keeps the camera centered on the packet while the follow lock is on. void _followPacketCamera() { - if (!_followPacket || - !_animationEnabled || - !_playback.started || - !_playback.hasPath || - !mounted || - !_hasData) { - return; - } - _mapController.move(_playback.position, _mapController.camera.zoom); + if (!mounted) return; + followPacketCamera( + _mapController, + _playback, + enabled: _followPacket && _animationEnabled && _hasData, + ); } void _toggleFollowPacket() { @@ -253,72 +256,12 @@ class _PathTraceMapScreenState extends State _followPacketCamera(); } - bool _isDesktopPlatform(TargetPlatform platform) { - return platform == TargetPlatform.linux || - platform == TargetPlatform.windows || - platform == TargetPlatform.macOS; - } - - void _zoomMapBy(double delta) { - final camera = _mapController.camera; - final nextZoom = (camera.zoom + delta) - .clamp(_mapMinZoom, _mapMaxZoom) - .toDouble(); - _mapController.move(camera.center, nextZoom); - } - void _resetMapView() { - final bounds = _bounds; - if (bounds != null) { - _mapController.fitCamera( - CameraFit.bounds( - bounds: bounds, - padding: const EdgeInsets.all(64), - maxZoom: 16, - ), - ); - return; - } - final center = _initialCenter; - if (center != null) { - _mapController.move(center, _initialZoom); - } - } - - Widget _buildDesktopMapControls() { - return Positioned( - top: 16, - left: 16, - child: DecoratedBox( - decoration: BoxDecoration( - color: MeshPalette.bg1.withValues(alpha: 0.90), - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MeshPalette.line2), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(MeshRadii.md), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - icon: const Icon(Icons.add), - tooltip: context.l10n.map_zoomIn, - onPressed: () => _zoomMapBy(1), - ), - IconButton( - icon: const Icon(Icons.remove), - tooltip: context.l10n.map_zoomOut, - onPressed: () => _zoomMapBy(-1), - ), - IconButton( - icon: const Icon(Icons.my_location), - tooltip: context.l10n.map_centerMap, - onPressed: _resetMapView, - ), - ], - ), - ), - ), + resetMapView( + _mapController, + bounds: _bounds, + center: _initialCenter, + zoom: _initialZoom, ); } @@ -469,7 +412,37 @@ class _PathTraceMapScreenState extends State payload: tracePayload, ); _awaitingTraceSent = true; - connector.sendFrame(frame); + _timeoutTimer?.cancel(); + // Fallback in case RESP_CODE_SENT / RESP_CODE_ERR never arrives; the + // RESP_CODE_SENT handler replaces it with the radio's own timeout. + _timeoutTimer = Timer(_sendAckTimeout, () { + if (!mounted || !_awaitingTraceSent) return; + _awaitingTraceSent = false; + setState(() { + _isLoading = false; + _failed2Loaded = true; + }); + }); + try { + await connector.sendFrame(frame); + } catch (e) { + _awaitingTraceSent = false; + _timeoutTimer?.cancel(); + appLogger.error( + 'Failed to send path trace: $e', + tag: 'PathTraceMapScreen', + ); + if (!mounted) return; + setState(() { + _isLoading = false; + _failed2Loaded = true; + }); + showDismissibleSnackBar( + context, + content: Text(context.l10n.pathTrace_sendFailed(e.toString())), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } } void _setupFrameListener() { @@ -725,7 +698,8 @@ class _PathTraceMapScreenState extends State _targetContactIsGuessed = targetGuessed; _points = []; - _points.add(LatLng(connector.selfLatitude!, connector.selfLongitude!)); + final selfPoint = plausibleSelfPoint(connector); + if (selfPoint != null) _points.add(selfPoint); String hopLast = ''; String hopLastLast = ''; for (final hop in _traceData!.pathData) { @@ -753,7 +727,7 @@ class _PathTraceMapScreenState extends State Polyline( points: _points, strokeWidth: 4, - color: Colors.blueAccent, + color: kPrimaryPathColor, ), ] : []; @@ -801,16 +775,31 @@ class _PathTraceMapScreenState extends State } Contact? _contactForHop(Uint8List hop, MeshCoreConnector connector) { - final traced = _traceData?.pathContacts[_hopKey(hop)]; + final hopKey = _hopKey(hop); + final traced = _traceData?.pathContacts[hopKey]; if (traced != null) return traced; - for (final c in connector.allContactsUnfiltered) { - if (c.type != advTypeChat && - c.publicKey.length >= hop.length && - listEquals(c.publicKey.sublist(0, hop.length), hop)) { - return c; + _hopContactCacheSignature ??= _refreshHopContactCache(connector); + return _hopContactCache.putIfAbsent(hopKey, () { + for (final c in connector.allContactsUnfiltered) { + if (c.type != advTypeChat && + c.publicKey.length >= hop.length && + listEquals(c.publicKey.sublist(0, hop.length), hop)) { + return c; + } } + return null; + }); + } + + /// Drops cached hop -> contact lookups when the contact list changed; + /// called once per build so per-hop lookups stay cheap. + int _refreshHopContactCache(MeshCoreConnector connector) { + final signature = contactListSignature(connector.allContactsUnfiltered); + if (signature != _hopContactCacheSignature) { + _hopContactCache.clear(); + _hopContactCacheSignature = signature; } - return null; + return signature; } LatLng? _inferredPositionForHop(Uint8List hop, MeshCoreConnector connector) { @@ -842,6 +831,7 @@ class _PathTraceMapScreenState extends State /// Rebuilds the renderable paths: the traced path as primary plus up to /// four distinct alternates from the target contact's path history. void _rebuildDisplayPaths(MeshCoreConnector connector) { + _refreshHopContactCache(connector); final paths = []; final primary = _buildDisplayPath( id: 'primary', @@ -900,15 +890,14 @@ class _PathTraceMapScreenState extends State required MeshCoreConnector connector, PathRecord? record, }) { - final selfLat = connector.selfLatitude; - final selfLon = connector.selfLongitude; - if (selfLat == null || selfLon == null) return null; - - final points = [LatLng(selfLat, selfLon)]; - final labels = [context.l10n.pathTrace_you]; - final confirmed = [true]; - final hopOrdinals = [-1]; - final gapBefore = [false]; + // Without a GPS fix for the local radio the path starts at the first + // located hop instead of a bogus "You" at 0,0. + final selfPoint = plausibleSelfPoint(connector); + final points = [?selfPoint]; + final labels = [if (selfPoint != null) context.l10n.pathTrace_you]; + final confirmed = [if (selfPoint != null) true]; + final hopOrdinals = [if (selfPoint != null) -1]; + final gapBefore = [if (selfPoint != null) false]; int gpsConfirmedHops = 0; int unresolvedHops = 0; bool pendingGap = false; @@ -1004,18 +993,7 @@ class _PathTraceMapScreenState extends State /// actually changed, so unrelated path-history updates don't reset a /// running animation. void _syncPlaybackToSelection() { - final points = _selectedPath?.points ?? const []; - if (points.length == _playback.points.length) { - var same = true; - for (var i = 0; i < points.length; i++) { - if (points[i] != _playback.points[i]) { - same = false; - break; - } - } - if (same) return; - } - _playback.setPath(points); + syncPlaybackPath(_playback, _selectedPath?.points ?? const []); } void _selectPath(DisplayPath path) { @@ -1047,6 +1025,7 @@ class _PathTraceMapScreenState extends State Widget build(BuildContext context) { return Consumer( builder: (context, connector, _) { + if (_hasData) _refreshHopContactCache(connector); final settings = context.watch().settings; final isImperial = settings.unitSystem == UnitSystem.imperial; final tileCache = context.read(); @@ -1092,8 +1071,12 @@ class _PathTraceMapScreenState extends State ), if (_hasData) _buildMapPathTrace(context, tileCache, _targetContact), - if (_hasData && _isDesktopPlatform(defaultTargetPlatform)) - _buildDesktopMapControls(), + if (_hasData && isDesktopMapPlatform()) + PathMapDesktopControls( + onZoomIn: () => zoomMapBy(_mapController, 1), + onZoomOut: () => zoomMapBy(_mapController, -1), + onReset: _resetMapView, + ), if (_hasData && _displayPaths.length > 1) PathViewModeToggle( mode: _viewMode, @@ -1202,7 +1185,7 @@ class _PathTraceMapScreenState extends State ), ); if (showLabels) { - markers.add(_buildNodeLabelMarker(point: point, label: fullLabel)); + markers.add(buildPathNodeLabelMarker(point: point, label: fullLabel)); } hopLastLast = hopLast; hopLast = hopKey; @@ -1219,10 +1202,8 @@ class _PathTraceMapScreenState extends State required bool showLabels, required Contact? target, }) { - final selfLat = context.read().selfLatitude; - final selfLon = context.read().selfLongitude; - if (selfLat != null && selfLon != null) { - final selfPoint = LatLng(selfLat, selfLon); + final selfPoint = plausibleSelfPoint(context.read()); + if (selfPoint != null) { markers.add( Marker( point: selfPoint, @@ -1247,12 +1228,16 @@ class _PathTraceMapScreenState extends State ], ), alignment: Alignment.center, - child: Text( - context.l10n.pathTrace_you, - style: MeshTheme.mono( - fontSize: 9, - fontWeight: FontWeight.w700, - color: MeshPalette.blue, + padding: const EdgeInsets.all(3), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + context.l10n.pathTrace_you, + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w700, + color: MeshPalette.blue, + ), ), ), ), @@ -1261,7 +1246,7 @@ class _PathTraceMapScreenState extends State ); if (showLabels) { markers.add( - _buildNodeLabelMarker( + buildPathNodeLabelMarker( point: selfPoint, label: context.l10n.pathTrace_you, ), @@ -1315,7 +1300,7 @@ class _PathTraceMapScreenState extends State ); if (showLabels) { markers.add( - _buildNodeLabelMarker( + buildPathNodeLabelMarker( point: targetPos, label: isGuessed ? '~$targetName' : targetName, ), @@ -1388,12 +1373,16 @@ class _PathTraceMapScreenState extends State ], ), alignment: Alignment.center, - child: Text( - hasGps ? label : '~$label', - style: MeshTheme.mono( - fontSize: 10, - fontWeight: FontWeight.w700, - color: baseColor, + padding: const EdgeInsets.all(2), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + hasGps ? label : '~$label', + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w700, + color: baseColor, + ), ), ), ), @@ -1401,24 +1390,7 @@ class _PathTraceMapScreenState extends State Positioned( top: 0, right: 0, - child: Container( - width: 17, - height: 17, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: MeshPalette.bg1, - border: Border.all(color: MeshPalette.line3), - ), - alignment: Alignment.center, - child: Text( - '${paths.length}', - style: MeshTheme.mono( - fontSize: 9, - fontWeight: FontWeight.w700, - color: MeshPalette.ink, - ), - ), - ), + child: PathSharedCountBadge(count: paths.length), ), ], ), @@ -1427,7 +1399,7 @@ class _PathTraceMapScreenState extends State ); if (showLabels) { markers.add( - _buildNodeLabelMarker( + buildPathNodeLabelMarker( point: point, label: contact?.name ?? '~$label', ), @@ -1455,42 +1427,6 @@ class _PathTraceMapScreenState extends State ); } - Marker _buildNodeLabelMarker({required LatLng point, required String label}) { - return Marker( - point: point, - width: 120, - height: 24, - alignment: Alignment.topCenter, - child: IgnorePointer( - child: Transform.translate( - offset: const Offset(0, -20), - child: FittedBox( - fit: BoxFit.contain, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: MeshPalette.bg.withValues(alpha: 0.82), - borderRadius: BorderRadius.circular(MeshRadii.xs), - border: Border.all(color: MeshPalette.line, width: 0.5), - ), - alignment: Alignment.center, - child: Text( - label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: MeshTheme.mono( - fontSize: 10, - fontWeight: FontWeight.w500, - color: MeshPalette.ink2, - ), - ), - ), - ), - ), - ), - ); - } - String formatDirectionText(PathTraceData pathTraceData, int index) { if (pathTraceData.pathData.isEmpty) { return context.l10n.pathTrace_you; @@ -1554,35 +1490,13 @@ class _PathTraceMapScreenState extends State MapTileCacheService tileCache, Contact? target, ) { - final isDesktop = _isDesktopPlatform(defaultTargetPlatform); return FlutterMap( key: _mapKey, mapController: _mapController, - options: MapOptions( - interactionOptions: InteractionOptions( - flags: ~InteractiveFlag.rotate, - scrollWheelVelocity: isDesktop ? 0.012 : 0.005, - cursorKeyboardRotationOptions: - CursorKeyboardRotationOptions.disabled(), - keyboardOptions: isDesktop - ? const KeyboardOptions( - enableArrowKeysPanning: true, - enableWASDPanning: true, - enableRFZooming: true, - ) - : const KeyboardOptions.disabled(), - ), + options: buildPathMapOptions( initialCenter: _initialCenter!, initialZoom: _initialZoom, - initialCameraFit: _bounds == null - ? null - : CameraFit.bounds( - bounds: _bounds!, - padding: const EdgeInsets.all(64), - maxZoom: 16, - ), - minZoom: _mapMinZoom, - maxZoom: _mapMaxZoom, + bounds: _bounds, onPositionChanged: (camera, hasGesture) { if (!mounted) return; // A manual pan/zoom releases the follow lock. @@ -1674,118 +1588,49 @@ class _PathTraceMapScreenState extends State final l10n = context.l10n; final selected = _selectedPath; final combined = _viewMode == PathViewMode.combined; - final maxHeight = - MediaQuery.of(context).size.height * (combined ? 0.45 : 0.35); + final connector = context.read(); + final hopRows = combined + ? (selected?.totalTransmissions ?? 0) + : pathTraceData.pathData.length + 1; - double cardHeight; - if (_panelCollapsed) { - cardHeight = 128; - } else { - final summaryHeight = combined ? 34.0 + _displayPaths.length * 36.0 : 0; - final hopRows = combined - ? (selected?.totalTransmissions ?? 0) - : pathTraceData.pathData.length + 1; - final estimatedHeight = 132.0 + summaryHeight + hopRows * 56.0; - cardHeight = max(176.0, min(maxHeight, estimatedHeight)); - } - - return Positioned( - left: 16, - right: 16, - bottom: 16, - child: SizedBox( - height: cardHeight, - child: DecoratedBox( - decoration: BoxDecoration( - color: MeshPalette.bg1.withValues(alpha: 0.95), - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MeshPalette.line2), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(MeshRadii.md), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(12, 8, 4, 0), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '${l10n.channelPath_repeaterHops} ${formatDistance(selected?.distanceMeters ?? _pathDistanceMeters, isImperial: isImperial)}', - style: MeshTheme.mono( - fontWeight: FontWeight.w600, - fontSize: 13, - color: MeshPalette.ink, - ), - ), - const SizedBox(height: 4), - PathMiniLegend(combined: combined), - ], - ), - ), - IconButton( - visualDensity: VisualDensity.compact, - icon: Icon( - _panelCollapsed - ? Icons.expand_less - : Icons.expand_more, - size: 20, - ), - tooltip: _panelCollapsed - ? l10n.pathMap_expandPanel - : l10n.pathMap_collapsePanel, - onPressed: () => - setState(() => _panelCollapsed = !_panelCollapsed), - ), - ], - ), - ), - PathAnimationControls( - playback: _playback, - selected: selected, - animationEnabled: _animationEnabled, - onToggleAnimation: () => setState(() { - _animationEnabled = !_animationEnabled; - if (!_animationEnabled) _playback.stop(); - }), - followEnabled: _followPacket, - onToggleFollow: _toggleFollowPacket, - ), - if (!_panelCollapsed) ...[ - if (selected != null && selected.unresolvedHops > 0) - Padding( - padding: const EdgeInsets.fromLTRB(12, 0, 12, 4), - child: Text( - l10n.pathMap_partialAnimation(selected.unresolvedHops), - style: TextStyle( - fontSize: 10.5, - color: MeshPalette.warn, - ), - ), - ), - if (combined) - PathSummaryList( - paths: _displayPaths, - selectedId: _selectedPathId, - hiddenIds: _hiddenPathIds, - isImperial: isImperial, - onSelect: _selectPath, - onToggleVisibility: _togglePathVisibility, - onShowAll: () => setState(_hiddenPathIds.clear), - ), - const Divider(height: 1), - Expanded(child: _buildHopList(pathTraceData, selected)), - ], - ], - ), - ), + return PathMapBottomPanel( + header: Text( + '${l10n.channelPath_repeaterHops} ${formatDistance(selected?.distanceMeters ?? _pathDistanceMeters, isImperial: isImperial, l10n: l10n)}', + style: MeshTheme.mono( + fontWeight: FontWeight.w600, + fontSize: 13, + color: MeshPalette.ink, ), ), + combined: combined, + showInferredLegend: true, + collapsed: _panelCollapsed, + onToggleCollapsed: () => + setState(() => _panelCollapsed = !_panelCollapsed), + playback: _playback, + selected: selected, + animationEnabled: _animationEnabled, + onToggleAnimation: () => setState(() { + _animationEnabled = !_animationEnabled; + if (!_animationEnabled) _playback.stop(); + }), + followEnabled: _followPacket, + onToggleFollow: _toggleFollowPacket, + showNoSelfGpsNote: plausibleSelfPoint(connector) == null, + pathCount: _displayPaths.length, + hopRowCount: hopRows, + summary: combined + ? PathSummaryList( + paths: _displayPaths, + selectedId: _selectedPathId, + hiddenIds: _hiddenPathIds, + isImperial: isImperial, + onSelect: _selectPath, + onToggleVisibility: _togglePathVisibility, + onShowAll: () => setState(_hiddenPathIds.clear), + ) + : null, + hopList: _buildHopList(pathTraceData, selected), ); } @@ -1836,9 +1681,12 @@ class _PathTraceMapScreenState extends State tileColor: index == highlightRow ? kPrimaryPathColor.withValues(alpha: 0.14) : null, - leading: index >= pathTraceData.snrData.length / 2 - ? Icon(Icons.call_received) - : Icon(Icons.call_made), + leading: Icon( + index >= pathTraceData.snrData.length / 2 + ? Icons.call_received + : Icons.call_made, + color: MeshPalette.ink2, + ), title: Text( formatDirectionText(pathTraceData, index), style: MeshTheme.mono(fontSize: 13, color: MeshPalette.ink), @@ -1853,7 +1701,7 @@ class _PathTraceMapScreenState extends State Icon(snrUi.icon, color: snrUi.color, size: 18.0), Text( snrUi.text, - style: MeshTheme.mono(fontSize: 10, color: snrUi.color), + style: MeshTheme.mono(fontSize: 12, color: snrUi.color), ), ], ), @@ -1919,7 +1767,7 @@ class _PathTraceMapScreenState extends State Icon(snrUi.icon, color: snrUi.color, size: 18.0), Text( snrUi.text, - style: MeshTheme.mono(fontSize: 10, color: snrUi.color), + style: MeshTheme.mono(fontSize: 12, color: snrUi.color), ), ], ); @@ -1946,7 +1794,7 @@ class _PathTraceMapScreenState extends State child: Text( '${index + 1}', style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, fontWeight: FontWeight.w700, color: path.color, ), @@ -1958,7 +1806,7 @@ class _PathTraceMapScreenState extends State ), subtitle: Text( subtitle, - style: MeshTheme.mono(fontSize: 11, color: MeshPalette.ink3), + style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3), ), trailing: trailing, ); diff --git a/lib/screens/region_management_screen.dart b/lib/screens/region_management_screen.dart index 06cc092f..ec81471b 100644 --- a/lib/screens/region_management_screen.dart +++ b/lib/screens/region_management_screen.dart @@ -36,6 +36,22 @@ class _RegionManagementScreenState extends State { List _regions = []; bool _isFetchingRegions = false; + /// Completed when the user cancels an in-progress fetch; pending discovery + /// and region requests resolve immediately with no results. + Completer? _fetchCancel; + + /// Drives the fetch progress dialog: null while discovering, otherwise + /// (current repeater, total repeaters). + final ValueNotifier<(int, int)?> _fetchProgress = ValueNotifier(null); + + @override + void dispose() { + final cancel = _fetchCancel; + if (cancel != null && !cancel.isCompleted) cancel.complete(); + _fetchProgress.dispose(); + super.dispose(); + } + @override void initState() { super.initState(); @@ -114,6 +130,9 @@ class _RegionManagementScreenState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + // Keep the app default visible so "No region (unscoped)" can be + // chosen before any region is added. + _buildDefaultRegionTile(context), // The radio may hold a default region set by firmware or another // client even when this app's list is empty; keep it clearable. _buildRadioDefaultRegionTile(context), @@ -245,52 +264,105 @@ class _RegionManagementScreenState extends State { } } - void _showAddRegionDialog(BuildContext context) { - final l10n = context.l10n; - final controller = TextEditingController(); - showDialog( + Future _showAddRegionDialog(BuildContext context) async { + final region = await showDialog( context: context, - builder: (context) => AlertDialog( - title: Text(l10n.settings_regionName), - content: TextField( - controller: controller, - autofocus: true, - textInputAction: TextInputAction.send, - onSubmitted: (_) => _handleAddRegion(controller.text, context), - decoration: InputDecoration( - hintText: l10n.settings_regionNameHint, - border: const OutlineInputBorder(), - ), - inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp("[a-z0-9-]")), - ], - maxLength: 30, - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_cancel), - ), - TextButton( - onPressed: () => _handleAddRegion(controller.text, context), - child: Text(l10n.common_add), - ), - ], - ), + builder: (_) => const _AddRegionDialog(), ); + if (region == null || !mounted) return; + _handleAddRegion(region); } Future _showFetchRegionsDialog() async { if (_isFetchingRegions) return; + final l10n = context.l10n; + final connector = context.read(); + + if (!connector.isConnected) { + showDismissibleSnackBar( + context, + content: Text(l10n.settings_notConnectedError), + ); + return; + } + final knownRepeaters = connector.contacts + .where((contact) => contact.type == advTypeRepeater) + .toList(); + if (knownRepeaters.isEmpty) { + await _showFetchMessage(l10n.settings_regionFetchNoRepeaters); + return; + } setState(() { _isFetchingRegions = true; }); + final cancel = Completer(); + _fetchCancel = cancel; + _fetchProgress.value = null; - Set fetchedRegions = {}; + BuildContext? progressContext; + unawaited( + showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) { + progressContext = dialogContext; + return PopScope( + canPop: false, + child: AlertDialog( + title: Text(l10n.settings_regionFetchRegions), + content: ValueListenableBuilder<(int, int)?>( + valueListenable: _fetchProgress, + builder: (context, progress, _) => Row( + children: [ + const SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 3), + ), + const SizedBox(width: 16), + Expanded( + child: Text( + progress == null + ? l10n.settings_regionFetchDiscovering + : l10n.settings_regionFetchProgress( + progress.$1, + progress.$2, + ), + style: Theme.of(context).textTheme.bodyLarge, + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () { + if (!cancel.isCompleted) cancel.complete(); + progressContext = null; + Navigator.pop(dialogContext); + }, + child: Text(l10n.common_cancel), + ), + ], + ), + ); + }, + ), + ); + + _RegionFetchResult result; try { - fetchedRegions = await _fetchRegionsFromRepeaters(); + result = await _fetchRegionsFromRepeaters(connector, cancel); } finally { + if (_fetchCancel == cancel) _fetchCancel = null; + // A fetch that fails instantly can finish before the progress dialog + // has built; let it build so it can be closed. + if (progressContext == null && !cancel.isCompleted) { + await WidgetsBinding.instance.endOfFrame; + } + final dialog = progressContext; + if (dialog != null && dialog.mounted) Navigator.pop(dialog); if (mounted) { setState(() { _isFetchingRegions = false; @@ -299,8 +371,12 @@ class _RegionManagementScreenState extends State { } if (!mounted) return; - final l10n = context.l10n; - final sortedRegions = fetchedRegions.toList()..sort(); + if (cancel.isCompleted && result.regions.isEmpty) return; + if (!cancel.isCompleted && result.askedRepeaters == 0) { + await _showFetchMessage(l10n.settings_regionFetchNoneResponded); + return; + } + final sortedRegions = result.regions.toList()..sort(); await showDialog( context: context, builder: (dialogContext) => AlertDialog( @@ -345,9 +421,13 @@ class _RegionManagementScreenState extends State { : null, onPressed: () { if (alreadyExists) { - _showDialogSnackBar( - context, - l10n.settings_regionFetchRegionsAlreadyExists, + // Screen context: the root + // ScaffoldMessenger, not the dialog's. + showDismissibleSnackBar( + this.context, + content: Text( + l10n.settings_regionFetchRegionsAlreadyExists, + ), ); return; } @@ -376,54 +456,46 @@ class _RegionManagementScreenState extends State { ); } - void _showDialogSnackBar(BuildContext context, String message) { - final overlay = Overlay.maybeOf(context); - if (overlay == null) return; - - final theme = Theme.of(context); - final entry = OverlayEntry( - builder: (context) => Positioned( - left: 16, - right: 16, - bottom: 32, - child: SafeArea( - child: Material( - color: theme.colorScheme.inverseSurface, - elevation: 6, - borderRadius: BorderRadius.circular(4), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Text( - message, - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onInverseSurface, - ), - ), - ), + Future _showFetchMessage(String message) { + final l10n = context.l10n; + return showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(l10n.settings_regionFetchRegions), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(l10n.common_close), ), - ), + ], ), ); - - overlay.insert(entry); - Timer(const Duration(seconds: 3), entry.remove); } - Future> _fetchRegionsFromRepeaters() async { - final connector = context.read(); - final repeaters = await _discoverNearbyRepeaters(connector); + Future<_RegionFetchResult> _fetchRegionsFromRepeaters( + MeshCoreConnector connector, + Completer cancel, + ) async { + final repeaters = await _discoverNearbyRepeaters(connector, cancel); final regions = {}; + var asked = 0; for (final repeater in repeaters) { - if (!mounted || !connector.isConnected) break; - regions.addAll(await _requestRegionsFromRepeater(connector, repeater)); + if (!mounted || !connector.isConnected || cancel.isCompleted) break; + asked++; + _fetchProgress.value = (asked, repeaters.length); + regions.addAll( + await _requestRegionsFromRepeater(connector, repeater, cancel), + ); } - return regions; + return _RegionFetchResult(regions: regions, askedRepeaters: asked); } Future> _discoverNearbyRepeaters( MeshCoreConnector connector, + Completer cancel, ) async { final repeaters = connector.contacts .where((contact) => contact.type == advTypeRepeater) @@ -469,9 +541,12 @@ class _RegionManagementScreenState extends State { } }); + unawaited(cancel.future.then((_) => complete())); + try { final payload = buildDiscoveryRequestPayload(tag, prefixOnly: true); await connector.sendFrame(buildSendControlDataFrame(payload)); + if (completer.isCompleted) return []; timeout = Timer(const Duration(seconds: 10), complete); final prefixes = await completer.future; return repeaters.where((contact) { @@ -488,6 +563,7 @@ class _RegionManagementScreenState extends State { Future> _requestRegionsFromRepeater( MeshCoreConnector connector, Contact repeater, + Completer cancel, ) async { StreamSubscription? subscription; Timer? timeout; @@ -509,6 +585,8 @@ class _RegionManagementScreenState extends State { timeout = Timer(duration, () => complete({})); } + unawaited(cancel.future.then((_) => complete({}))); + try { final replyPath = Uint8List(0); const replyHopCount = 0; @@ -561,28 +639,27 @@ class _RegionManagementScreenState extends State { pathHashWidth: connector.pathHashByteWidth, ); await connector.sendFrame(frame); - final regions = await completer.future; - if (pathChangedForRequest && connector.isConnected) { - await _restoreRepeaterPath( - connector, - repeater, - originalPathLength, - originalPath, - ); - } - return regions; + return await completer.future; } catch (_) { - timeout?.cancel(); - subscription?.cancel(); - if (pathChangedForRequest && connector.isConnected) { - await _restoreRepeaterPath( - connector, - repeater, - originalPathLength, - originalPath, - ); - } return {}; + } finally { + timeout?.cancel(); + await subscription?.cancel(); + // Always put the user's route back, whatever happened above. (The + // connector ignores path writes while disconnected, so nothing can be + // restored if the link dropped mid-request.) + if (pathChangedForRequest) { + try { + await _restoreRepeaterPath( + connector, + repeater, + originalPathLength, + originalPath, + ); + } catch (_) { + // Best effort; the original path is still in the contact store. + } + } } } @@ -616,9 +693,11 @@ class _RegionManagementScreenState extends State { .toSet(); } - void _handleAddRegion(Region region, BuildContext context) { - Navigator.pop(context); - _regionStore.addRegion(region); + void _handleAddRegion(Region region) { + // An empty name would collide with the '' "none" dropdown entry. + final trimmed = region.trim(); + if (trimmed.isEmpty) return; + _regionStore.addRegion(trimmed); _loadRegions(); } @@ -686,3 +765,73 @@ class _RegionManagementScreenState extends State { ); } } + +class _RegionFetchResult { + final Set regions; + final int askedRepeaters; + + const _RegionFetchResult({ + required this.regions, + required this.askedRepeaters, + }); +} + +/// Region-name entry. Owns (and disposes) its controller and only enables +/// Add once the trimmed name is non-empty; pops with that name. +class _AddRegionDialog extends StatefulWidget { + const _AddRegionDialog(); + + @override + State<_AddRegionDialog> createState() => _AddRegionDialogState(); +} + +class _AddRegionDialogState extends State<_AddRegionDialog> { + final TextEditingController _controller = TextEditingController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _submit() { + final name = _controller.text.trim(); + if (name.isEmpty) return; + Navigator.pop(context, name); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AlertDialog( + title: Text(l10n.settings_regionName), + content: TextField( + controller: _controller, + autofocus: true, + textInputAction: TextInputAction.send, + onSubmitted: (_) => _submit(), + decoration: InputDecoration( + hintText: l10n.settings_regionNameHint, + border: const OutlineInputBorder(), + ), + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp("[a-z0-9-]")), + ], + maxLength: 30, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + ListenableBuilder( + listenable: _controller, + builder: (context, _) => TextButton( + onPressed: _controller.text.trim().isEmpty ? null : _submit, + child: Text(l10n.common_add), + ), + ), + ], + ); + } +} diff --git a/lib/screens/repeater_cli_screen.dart b/lib/screens/repeater_cli_screen.dart index f45563a8..da479275 100644 --- a/lib/screens/repeater_cli_screen.dart +++ b/lib/screens/repeater_cli_screen.dart @@ -2,12 +2,15 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; +import 'package:share_plus/share_plus.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../theme/mesh_theme.dart'; +import '../widgets/confirm_clear_dialog.dart'; import '../widgets/debug_frame_viewer.dart'; +import '../widgets/radio_disconnected_banner.dart'; import '../services/repeater_command_service.dart'; import '../widgets/routing_sheet.dart'; import '../helpers/snack_bar_builder.dart'; @@ -144,10 +147,12 @@ class _RepeaterCliScreenState extends State { _historyIndex = -1; _commandFocusNode.requestFocus(); - if (showDebug && mounted) { + if (showDebug && mounted && _commandService != null) { + // Preview the exact framed text the service sends (`XX|` prefix and + // clock-sync rewrite), not the bare command. final frame = buildSendCliCommandFrame( widget.repeater.publicKey, - command, + _commandService!.previewFramedCommand(command), ); DebugFrameViewer.showFrameDebug( context, @@ -302,6 +307,50 @@ class _RepeaterCliScreenState extends State { }); } + Future _confirmClearHistory() async { + final l10n = context.l10n; + final confirmed = await showConfirmClearDialog( + context, + title: l10n.repeater_clearHistory, + message: l10n.repeater_cliClearHistoryConfirm, + ); + if (confirmed && mounted) _clearHistory(); + } + + String _transcriptText() { + return _commandHistory + .map( + (entry) => entry['type'] == 'command' + ? '> ${entry['text']}' + : (entry['text'] ?? ''), + ) + .join('\n'); + } + + Future _copyTranscript() async { + if (_commandHistory.isEmpty) return; + await Clipboard.setData(ClipboardData(text: _transcriptText())); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.repeater_cliTranscriptCopied), + ); + } + + Future _shareTranscript() async { + if (_commandHistory.isEmpty) return; + final box = context.findRenderObject() as RenderBox?; + await SharePlus.instance.share( + ShareParams( + text: _transcriptText(), + subject: '${context.l10n.repeater_cliTitle} - ${widget.repeater.name}', + sharePositionOrigin: box == null + ? null + : box.localToGlobal(Offset.zero) & box.size, + ), + ); + } + String _quickCommandLabel(String key) { final l10n = context.l10n; switch (key) { @@ -335,11 +384,15 @@ class _RepeaterCliScreenState extends State { final connector = context.watch(); final repeater = _resolveRepeater(connector); final isFloodMode = repeater.pathOverride == -1; + final connected = connector.isConnected; + final accent = scheme.primary; + final hasHistory = _commandHistory.isNotEmpty; return Scaffold( - backgroundColor: MeshPalette.bg, + backgroundColor: scheme.surfaceContainerLowest, appBar: AppBar( - backgroundColor: MeshPalette.bg1, + backgroundColor: scheme.surfaceContainer, + foregroundColor: scheme.onSurface, title: Text(l10n.repeater_cliTitle), centerTitle: true, actions: [ @@ -357,25 +410,53 @@ class _RepeaterCliScreenState extends State { IconButton( icon: const Icon(Icons.clear_all), tooltip: l10n.repeater_clearHistory, - onPressed: _commandHistory.isEmpty ? null : _clearHistory, + onPressed: hasHistory ? _confirmClearHistory : null, ), PopupMenuButton( icon: const Icon(Icons.more_vert), onSelected: (value) { - if (value == 'debug') { - if (_commandController.text.trim().isNotEmpty) { - _sendCommand(showDebug: true); - } else { - showDismissibleSnackBar( - context, - content: Text(l10n.repeater_enterCommandFirst), - ); - } + switch (value) { + case 'debug': + if (_commandController.text.trim().isNotEmpty) { + _sendCommand(showDebug: true); + } else { + showDismissibleSnackBar( + context, + content: Text(l10n.repeater_enterCommandFirst), + ); + } + case 'copy': + _copyTranscript(); + case 'share': + _shareTranscript(); } }, itemBuilder: (context) => [ + PopupMenuItem( + value: 'copy', + enabled: hasHistory, + child: Row( + children: [ + const Icon(Icons.copy), + const SizedBox(width: 8), + Text(l10n.repeater_cliCopyTranscript), + ], + ), + ), + PopupMenuItem( + value: 'share', + enabled: hasHistory, + child: Row( + children: [ + const Icon(Icons.share), + const SizedBox(width: 8), + Text(l10n.repeater_cliShareTranscript), + ], + ), + ), PopupMenuItem( value: 'debug', + enabled: connected, child: Row( children: [ const Icon(Icons.bug_report), @@ -390,9 +471,10 @@ class _RepeaterCliScreenState extends State { ), body: Column( children: [ + const RadioDisconnectedBanner(), // Quick commands bar Container( - color: MeshPalette.bg1, + color: scheme.surfaceContainer, padding: const EdgeInsets.fromLTRB(8, 6, 8, 6), child: SingleChildScrollView( scrollDirection: Axis.horizontal, @@ -405,15 +487,14 @@ class _RepeaterCliScreenState extends State { label: Text( label, style: MeshTheme.mono( - fontSize: 11, + fontSize: 13, fontWeight: FontWeight.w600, - color: MeshPalette.blue, + color: accent, ), ), - backgroundColor: MeshPalette.blueBg, - side: const BorderSide(color: MeshPalette.blueLine), - visualDensity: VisualDensity.compact, - onPressed: _regionLoadActive + backgroundColor: accent.withValues(alpha: 0.12), + side: BorderSide(color: accent.withValues(alpha: 0.5)), + onPressed: _regionLoadActive || !connected ? null : () => _useQuickCommand(cmd['command']!), ), @@ -422,7 +503,7 @@ class _RepeaterCliScreenState extends State { ), ), ), - Divider(height: 1, color: MeshPalette.line), + Divider(height: 1, color: scheme.outlineVariant), // Output area Expanded( @@ -431,11 +512,11 @@ class _RepeaterCliScreenState extends State { : _buildCommandHistory(), ), - Divider(height: 1, color: MeshPalette.line), + Divider(height: 1, color: scheme.outlineVariant), // Command input Container( - color: MeshPalette.bg1, + color: scheme.surfaceContainer, padding: const EdgeInsets.fromLTRB(8, 8, 8, 8), child: SafeArea( child: Row( @@ -443,22 +524,20 @@ class _RepeaterCliScreenState extends State { IconButton( icon: Icon( Icons.arrow_upward, - size: 18, + size: 22, color: scheme.onSurfaceVariant, ), tooltip: l10n.repeater_previousCommand, onPressed: () => _navigateHistory(true), - visualDensity: VisualDensity.compact, ), IconButton( icon: Icon( Icons.arrow_downward, - size: 18, + size: 22, color: scheme.onSurfaceVariant, ), tooltip: l10n.repeater_nextCommand, onPressed: () => _navigateHistory(false), - visualDensity: VisualDensity.compact, ), const SizedBox(width: 4), Expanded( @@ -466,73 +545,61 @@ class _RepeaterCliScreenState extends State { controller: _commandController, focusNode: _commandFocusNode, style: MeshTheme.mono( - fontSize: 13, - color: MeshPalette.ink, + fontSize: 15, + color: scheme.onSurface, ), decoration: InputDecoration( hintText: _regionLoadActive ? context.l10n.repeater_cliRegionLoadHint : context.l10n.repeater_enterCommandHint, hintStyle: MeshTheme.mono( - fontSize: 13, - color: MeshPalette.ink4, + fontSize: 15, + color: scheme.onSurfaceVariant, ), prefixText: _regionLoadActive ? '' : '> ', prefixStyle: MeshTheme.mono( - fontSize: 13, - color: MeshPalette.blue, + fontSize: 15, + color: accent, fontWeight: FontWeight.w700, ), filled: true, - fillColor: MeshPalette.bg2, + fillColor: scheme.surfaceContainerHigh, contentPadding: const EdgeInsets.symmetric( horizontal: 12, - vertical: 10, + vertical: 12, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(MeshRadii.pill), - borderSide: const BorderSide( - color: MeshPalette.line2, - ), + borderSide: BorderSide(color: scheme.outline), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(MeshRadii.pill), - borderSide: const BorderSide( - color: MeshPalette.line2, - ), + borderSide: BorderSide(color: scheme.outline), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(MeshRadii.pill), - borderSide: const BorderSide( - color: MeshPalette.blue, - width: 1.5, - ), + borderSide: BorderSide(color: accent, width: 1.5), ), ), textInputAction: TextInputAction.send, - onSubmitted: (_) => _sendCommand(), + onSubmitted: (_) { + if (connected) _sendCommand(); + }, ), ), const SizedBox(width: 6), - Material( - color: MeshPalette.blue.withValues(alpha: 0.15), - shape: const CircleBorder( - side: BorderSide(color: MeshPalette.blueLine), - ), - child: InkWell( - customBorder: const CircleBorder(), - onTap: () { - HapticFeedback.lightImpact(); - _sendCommand(); - }, - child: const Padding( - padding: EdgeInsets.all(10), - child: Icon( - Icons.send, - size: 18, - color: MeshPalette.blue, - ), - ), + SizedBox( + width: 48, + height: 48, + child: IconButton.filledTonal( + tooltip: l10n.repeater_cliSend, + icon: const Icon(Icons.send, size: 24), + onPressed: connected + ? () { + HapticFeedback.lightImpact(); + _sendCommand(); + } + : null, ), ), ], @@ -546,27 +613,38 @@ class _RepeaterCliScreenState extends State { Widget _buildEmptyState() { final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.terminal, size: 48, color: MeshPalette.ink4), - const SizedBox(height: 12), - Text( - l10n.repeater_noCommandsSent, - style: MeshTheme.mono(fontSize: 13, color: MeshPalette.ink3), - ), - const SizedBox(height: 4), - Text( - l10n.repeater_typeCommandOrUseQuick, - style: const TextStyle(fontSize: 12, color: MeshPalette.ink4), - ), - ], + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.terminal, size: 48, color: scheme.onSurfaceVariant), + const SizedBox(height: 12), + Text( + l10n.repeater_noCommandsSent, + textAlign: TextAlign.center, + style: MeshTheme.mono(fontSize: 15, color: scheme.onSurface), + ), + const SizedBox(height: 4), + Text( + l10n.repeater_typeCommandOrUseQuick, + textAlign: TextAlign.center, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ], + ), ), ); } Widget _buildCommandHistory() { + final scheme = Theme.of(context).colorScheme; + final accent = scheme.primary; return ListView.builder( controller: _scrollController, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), @@ -576,7 +654,7 @@ class _RepeaterCliScreenState extends State { final isCommand = entry['type'] == 'command'; return Padding( - padding: const EdgeInsets.only(bottom: 2), + padding: const EdgeInsets.only(bottom: 4), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -586,9 +664,9 @@ class _RepeaterCliScreenState extends State { child: Text( isCommand ? '>' : ' ', style: MeshTheme.mono( - fontSize: 12, + fontSize: 14, fontWeight: FontWeight.w700, - color: isCommand ? MeshPalette.blue : MeshPalette.ink3, + color: isCommand ? accent : scheme.onSurfaceVariant, ), ), ), @@ -597,8 +675,8 @@ class _RepeaterCliScreenState extends State { child: SelectableText( entry['text']!, style: MeshTheme.mono( - fontSize: 12.5, - color: isCommand ? MeshPalette.blue : MeshPalette.ink, + fontSize: 14, + color: isCommand ? accent : scheme.onSurface, ), ), ), @@ -1151,120 +1229,207 @@ class _RepeaterCliScreenState extends State { ), ]; - showDialog( + final sections = <_CommandHelpSection>[ + _CommandHelpSection(l10n.repeater_general, generalCommands), + _CommandHelpSection(l10n.repeater_getCategory, getCommands), + _CommandHelpSection(l10n.repeater_settingsCategory, settingsCommands), + _CommandHelpSection(l10n.repeater_powerMgmt, powerMgmtCommands), + _CommandHelpSection(l10n.repeater_sensors, sensorCommands), + _CommandHelpSection( + l10n.repeater_bridge, + bridgeCommands, + note: l10n.repeater_bridgeNote, + ), + _CommandHelpSection(l10n.repeater_logging, loggingCommands), + _CommandHelpSection( + l10n.repeater_neighborsRepeaterOnly, + neighborCommands, + ), + _CommandHelpSection( + l10n.repeater_regionManagementRepeaterOnly, + regionCommands, + note: l10n.repeater_regionNote, + ), + _CommandHelpSection( + l10n.repeater_gpsManagement, + gpsCommands, + note: l10n.repeater_gpsNote, + ), + ]; + + showModalBottomSheet( context: context, - builder: (context) => AlertDialog( - title: Text(l10n.repeater_commandsListTitle), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - l10n.repeater_commandsListNote, - style: const TextStyle(fontSize: 13), + isScrollControlled: true, + useSafeArea: true, + showDragHandle: true, + builder: (sheetContext) => + _CommandHelpSheet(sections: sections, onSelect: _applyHelpCommand), + ); + } +} + +class _CommandHelpSection { + final String title; + final List<_CommandHelpEntry> commands; + final String? note; + const _CommandHelpSection(this.title, this.commands, {this.note}); +} + +/// Searchable, lazily built list of CLI commands. +class _CommandHelpSheet extends StatefulWidget { + final List<_CommandHelpSection> sections; + final ValueChanged onSelect; + + const _CommandHelpSheet({required this.sections, required this.onSelect}); + + @override + State<_CommandHelpSheet> createState() => _CommandHelpSheetState(); +} + +class _CommandHelpSheetState extends State<_CommandHelpSheet> { + final TextEditingController _searchController = TextEditingController(); + String _query = ''; + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + /// Section headers ([_CommandHelpSection]) interleaved with their matching + /// [_CommandHelpEntry] rows. + List _rows() { + final q = _query.trim().toLowerCase(); + final rows = []; + for (final section in widget.sections) { + final matches = q.isEmpty + ? section.commands + : section.commands + .where( + (e) => + e.command.toLowerCase().contains(q) || + e.description.toLowerCase().contains(q), + ) + .toList(); + if (matches.isEmpty) continue; + rows.add(section); + rows.addAll(matches); + } + return rows; + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + final rows = _rows(); + return Padding( + padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom), + child: DraggableScrollableSheet( + expand: false, + initialChildSize: 0.85, + minChildSize: 0.4, + maxChildSize: 1, + builder: (context, scrollController) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.repeater_commandsListTitle, + style: textTheme.titleLarge, + ), + const SizedBox(height: 4), + Text( + l10n.repeater_commandsListNote, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 12), + TextField( + controller: _searchController, + decoration: InputDecoration( + prefixIcon: const Icon(Icons.search), + hintText: l10n.repeater_cliSearchCommands, + suffixIcon: _query.isEmpty + ? null + : IconButton( + icon: const Icon(Icons.clear), + tooltip: l10n.common_clearSearch, + onPressed: () { + _searchController.clear(); + setState(() => _query = ''); + }, + ), + ), + onChanged: (value) => setState(() => _query = value), + ), + ], ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_general, - generalCommands, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_getCategory, - getCommands, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_settingsCategory, - settingsCommands, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_powerMgmt, - powerMgmtCommands, - ), - const SizedBox(height: 16), - _buildHelpSection(context, l10n.repeater_sensors, sensorCommands), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_bridge, - bridgeCommands, - note: l10n.repeater_bridgeNote, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_logging, - loggingCommands, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_neighborsRepeaterOnly, - neighborCommands, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_regionManagementRepeaterOnly, - regionCommands, - note: l10n.repeater_regionNote, - ), - const SizedBox(height: 16), - _buildHelpSection( - context, - l10n.repeater_gpsManagement, - gpsCommands, - note: l10n.repeater_gpsNote, - ), - ], - ), + ), + Expanded( + child: rows.isEmpty + ? Center( + child: Text( + l10n.repeater_cliNoMatchingCommands, + style: textTheme.bodyLarge?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ) + : ListView.builder( + controller: scrollController, + padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), + itemCount: rows.length, + itemBuilder: (context, index) { + final row = rows[index]; + if (row is _CommandHelpSection) { + return _buildHeader(row, isFirst: index == 0); + } + return _buildCommandCard(row as _CommandHelpEntry); + }, + ), + ), + ], ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_close), + ), + ); + } + + Widget _buildHeader(_CommandHelpSection section, {required bool isFirst}) { + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + return Padding( + padding: EdgeInsets.only(top: isFirst ? 4 : 16, bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + section.title, + style: textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), ), + if (section.note != null) ...[ + const SizedBox(height: 4), + Text( + section.note!, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ], ], ), ); } - Widget _buildHelpSection( - BuildContext context, - String title, - List<_CommandHelpEntry> commands, { - String? note, - }) { - final scheme = Theme.of(context).colorScheme; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15), - ), - if (note != null) ...[ - const SizedBox(height: 4), - Text( - note, - style: TextStyle(fontSize: 11, color: scheme.onSurfaceVariant), - ), - ], - const SizedBox(height: 8), - ...commands.map((entry) => _buildHelpCommandCard(context, entry)), - ], - ); - } - - Widget _buildHelpCommandCard(BuildContext context, _CommandHelpEntry entry) { + Widget _buildCommandCard(_CommandHelpEntry entry) { final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; return Card( elevation: 0, margin: const EdgeInsets.only(bottom: 6), @@ -1275,24 +1440,26 @@ class _RepeaterCliScreenState extends State { ), child: InkWell( borderRadius: BorderRadius.circular(MeshRadii.sm), - onTap: () => _applyHelpCommand(entry.command), + onTap: () => widget.onSelect(entry.command), child: Padding( - padding: const EdgeInsets.all(10), + padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( entry.command, style: MeshTheme.mono( - fontSize: 12, + fontSize: 14, fontWeight: FontWeight.w600, - color: MeshPalette.blue, + color: scheme.primary, ), ), const SizedBox(height: 4), Text( entry.description, - style: TextStyle(fontSize: 12, color: scheme.onSurfaceVariant), + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), ), ], ), diff --git a/lib/screens/repeater_hub_screen.dart b/lib/screens/repeater_hub_screen.dart index 324cd231..bac25d48 100644 --- a/lib/screens/repeater_hub_screen.dart +++ b/lib/screens/repeater_hub_screen.dart @@ -9,6 +9,7 @@ import '../l10n/contact_localization.dart'; import '../services/app_settings_service.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/radio_disconnected_banner.dart'; import 'repeater_status_screen.dart'; import 'repeater_cli_screen.dart'; import 'repeater_settings_screen.dart'; @@ -51,6 +52,7 @@ class RepeaterHubScreen extends StatelessWidget { child: ListView( padding: const EdgeInsets.only(bottom: 24), children: [ + const RadioDisconnectedBanner(), // ── Identity card ───────────────────────────────────────────── Padding( padding: const EdgeInsets.fromLTRB(16, 20, 16, 4), @@ -81,7 +83,7 @@ class RepeaterHubScreen extends StatelessWidget { Text( repeater.shortPubKeyHex, style: MeshTheme.mono( - fontSize: 11, + fontSize: 13, color: scheme.onSurfaceVariant, ), ), @@ -100,7 +102,7 @@ class RepeaterHubScreen extends StatelessWidget { children: [ Icon( Icons.location_on, - size: 12, + size: 16, color: scheme.onSurfaceVariant, ), const SizedBox(width: 3), @@ -109,7 +111,7 @@ class RepeaterHubScreen extends StatelessWidget { '${repeater.latitude?.toStringAsFixed(4)}, ' '${repeater.longitude?.toStringAsFixed(4)}', style: MeshTheme.mono( - fontSize: 10, + fontSize: 13, color: scheme.onSurfaceVariant, ), overflow: TextOverflow.ellipsis, @@ -308,6 +310,7 @@ class _HubActionTile extends StatelessWidget { @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; return ListEntrance( index: index, child: Semantics( @@ -334,16 +337,14 @@ class _HubActionTile extends StatelessWidget { children: [ Text( title, - style: const TextStyle( + style: textTheme.titleMedium?.copyWith( fontWeight: FontWeight.w600, - fontSize: 15, ), ), const SizedBox(height: 2), Text( subtitle, - style: TextStyle( - fontSize: 12.5, + style: textTheme.bodyMedium?.copyWith( color: scheme.onSurfaceVariant, ), ), diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index b7c6aae8..a277e4c6 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -12,6 +12,7 @@ import '../services/repeater_command_service.dart'; import '../services/storage_service.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/radio_disconnected_banner.dart'; import '../widgets/routing_sheet.dart'; import '../utils/keys.dart'; import '../helpers/snack_bar_builder.dart'; @@ -204,6 +205,10 @@ class _RepeaterSettingsScreenState extends State { static const int _maxNameBytes = 31; static const int _maxOwnerInfoBytes = 119; static const int _maxAgcResetInterval = 255 * 4; + // PRV_KEY_SIZE is 64 bytes (expanded Ed25519 key), i.e. 128 hex chars; + // firmware `set prv.key` rejects anything else. + static const int _prvKeyHexLength = 128; + static final RegExp _prvKeyPattern = RegExp(r'^[0-9a-fA-F]{128}$'); @override void initState() { @@ -212,6 +217,24 @@ class _RepeaterSettingsScreenState extends State { _commandService = RepeaterCommandService(connector); _setupMessageListener(); _loadSettings(); + // Fetch current values on open instead of showing disabled fields. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final connector = Provider.of(context, listen: false); + if (connector.isConnected) _refreshAll(); + }); + } + + /// Returns true when the radio is connected; otherwise tells the user. + bool _ensureConnected() { + final connector = Provider.of(context, listen: false); + if (connector.isConnected) return true; + showDismissibleSnackBar( + context, + content: Text(context.l10n.repeater_radioDisconnected), + backgroundColor: Theme.of(context).colorScheme.error, + ); + return false; } @override @@ -474,6 +497,7 @@ class _RepeaterSettingsScreenState extends State { required ValueSetter setRefreshing, }) async { if (_commandService == null) return; + if (!_loadingAll && !_ensureConnected()) return; final l10n = context.l10n; setState(() => setRefreshing(true)); @@ -702,8 +726,16 @@ class _RepeaterSettingsScreenState extends State { /// Send a one-shot CLI action (advert / clock sync / etc.) and surface the /// firmware's reply via snackbar. Not part of the dirty-field save flow. - Future _runAction(String command, String label) async { + /// + /// With [replyOptional] (e.g. `reboot`, which restarts without answering) a + /// timeout means the command went out; it is reported as sent, not failed. + Future _runAction( + String command, + String label, { + bool replyOptional = false, + }) async { if (_commandService == null) return; + if (!_ensureConnected()) return; final connector = Provider.of(context, listen: false); final repeater = _resolveRepeater(connector); final l10n = context.l10n; @@ -729,6 +761,13 @@ class _RepeaterSettingsScreenState extends State { ); } catch (e) { if (!mounted) return; + if (replyOptional && e.toString().contains('Command timeout')) { + showDismissibleSnackBar( + context, + content: Text(l10n.repeater_actionSentNoReply(label)), + ); + return; + } showDismissibleSnackBar( context, content: Text(l10n.repeater_actionFailed(label, e.toString())), @@ -741,6 +780,7 @@ class _RepeaterSettingsScreenState extends State { Future _refreshAll() async { if (_loadingAll) return; + if (!_ensureConnected()) return; final sections = Function()>[ _refreshBasicSettings, _refreshRadioSettings, @@ -883,10 +923,10 @@ class _RepeaterSettingsScreenState extends State { ); if (_dirtyFields.contains(_SettingField.name) && - _nameController.text.isNotEmpty) { + _nameController.text.trim().isNotEmpty) { pending.add(( field: _SettingField.name, - command: 'set name ${_nameController.text}', + command: 'set name ${_nameController.text.trim()}', )); } @@ -916,16 +956,28 @@ class _RepeaterSettingsScreenState extends State { if (freq == null || freq < 150 || freq > 2500) { reject(_SettingField.radio, l10n.repeater_frequencyInvalid); } else if (bwKHz < 7.8 || bwKHz > 500) { - reject(_SettingField.radio, '${l10n.repeater_bandwidth}: $bwKHz'); + reject( + _SettingField.radio, + l10n.repeater_invalidSettingValue( + l10n.repeater_bandwidth, + '$bwKHz', + ), + ); } else if (_spreadingFactor! < 5 || _spreadingFactor! > 12) { reject( _SettingField.radio, - '${l10n.repeater_spreadingFactor}: $_spreadingFactor', + l10n.repeater_invalidSettingValue( + l10n.repeater_spreadingFactor, + '$_spreadingFactor', + ), ); } else if (_codingRate! < 5 || _codingRate! > 8) { reject( _SettingField.radio, - '${l10n.repeater_codingRate}: $_codingRate', + l10n.repeater_invalidSettingValue( + l10n.repeater_codingRate, + '$_codingRate', + ), ); } else { pending.add(( @@ -944,8 +996,11 @@ class _RepeaterSettingsScreenState extends State { dbm > _maxRepeaterTxPower) { reject( _SettingField.txPower, - '${l10n.repeater_txPower}: ${_txPowerController.text.trim()} ' - '($_minRepeaterTxPower-$_maxRepeaterTxPower dBm)', + l10n.repeater_txPowerOutOfRange( + _txPowerController.text.trim(), + _minRepeaterTxPower, + _maxRepeaterTxPower, + ), ); } else { pending.add((field: _SettingField.txPower, command: 'set tx $dbm')); @@ -962,7 +1017,10 @@ class _RepeaterSettingsScreenState extends State { } else { reject( _SettingField.lat, - '${l10n.repeater_latitude}: ${_latController.text.trim()}', + l10n.repeater_invalidSettingValue( + l10n.repeater_latitude, + _latController.text.trim(), + ), ); } } @@ -976,7 +1034,10 @@ class _RepeaterSettingsScreenState extends State { } else { reject( _SettingField.lon, - '${l10n.repeater_longitude}: ${_lonController.text.trim()}', + l10n.repeater_invalidSettingValue( + l10n.repeater_longitude, + _lonController.text.trim(), + ), ); } } @@ -1053,8 +1114,13 @@ class _RepeaterSettingsScreenState extends State { } if (_dirtyFields.contains(_SettingField.prvKey)) { final v = _prvKeyController.text.trim(); - if (v != "") { + if (_prvKeyPattern.hasMatch(v)) { pending.add((field: _SettingField.prvKey, command: 'set prv.key $v')); + } else if (v.isNotEmpty) { + reject( + _SettingField.prvKey, + l10n.repeater_prvKeyLengthError(_prvKeyHexLength), + ); } } if (_dirtyFields.contains(_SettingField.txDelay) && @@ -1068,7 +1134,10 @@ class _RepeaterSettingsScreenState extends State { } else { reject( _SettingField.txDelay, - '${l10n.repeater_txDelay}: ${_txDelayController.text.trim()}', + l10n.repeater_invalidSettingValue( + l10n.repeater_txDelay, + _txDelayController.text.trim(), + ), ); } } @@ -1085,8 +1154,10 @@ class _RepeaterSettingsScreenState extends State { } else { reject( _SettingField.directTxDelay, - '${l10n.repeater_directTxDelay}: ' - '${_directTxDelayController.text.trim()}', + l10n.repeater_invalidSettingValue( + l10n.repeater_directTxDelay, + _directTxDelayController.text.trim(), + ), ); } } @@ -1101,7 +1172,10 @@ class _RepeaterSettingsScreenState extends State { } else { reject( _SettingField.intThresh, - '${l10n.repeater_intThresh}: ${_intThreshController.text.trim()}', + l10n.repeater_invalidSettingValue( + l10n.repeater_intThresh, + _intThreshController.text.trim(), + ), ); } } @@ -1244,6 +1318,7 @@ class _RepeaterSettingsScreenState extends State { prefix, _searchChunkTime, ); + if (!mounted) return; if (keys == null) { // Ran out of time; schedule another attempt. Timer.run(_searchForKeyPair); @@ -1283,83 +1358,139 @@ class _RepeaterSettingsScreenState extends State { final connector = context.watch(); final repeater = _resolveRepeater(connector); final isFloodMode = repeater.pathOverride == -1; + final connected = connector.isConnected; - return Scaffold( - appBar: AppBar( - title: Text(l10n.repeater_settingsTitle), - centerTitle: true, - actions: [ - IconButton( - icon: Icon(isFloodMode ? Icons.waves : Icons.route), - tooltip: l10n.repeater_routingMode, - onPressed: () => - ContactRoutingSheet.show(context, contact: repeater), - ), - IconButton( - icon: const Icon(Icons.refresh), - tooltip: l10n.repeater_refreshAll, - onPressed: _loadingAll || _isLoading ? null : _refreshAll, - ), - if (_hasChanges) - TextButton.icon( - onPressed: _isLoading || _loadingAll ? null : _saveSettings, - icon: const Icon(Icons.save), - label: Text(l10n.common_save), + return PopScope( + canPop: !_hasChanges, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _confirmDiscardChanges(); + }, + child: Scaffold( + appBar: AppBar( + title: Text(l10n.repeater_settingsTitle), + centerTitle: true, + actions: [ + IconButton( + icon: Icon(isFloodMode ? Icons.waves : Icons.route), + tooltip: l10n.repeater_routingMode, + onPressed: () => + ContactRoutingSheet.show(context, contact: repeater), ), - ], - bottom: _loadingAll - ? PreferredSize( - preferredSize: const Size.fromHeight(4), - child: LinearProgressIndicator(value: _loadAllProgress), - ) - : null, - ), - body: SafeArea( - top: false, - child: _isLoading && _nameController.text.isEmpty - ? const Center(child: CircularProgressIndicator()) - : ListView( - padding: const EdgeInsets.only(bottom: 32), - children: [ - if (_loadedKeys.isEmpty && !_loadingAll) - Padding( - padding: const EdgeInsets.only(top: 16), - child: MeshCard( - child: Row( - children: [ - const Icon(Icons.info_outline, size: 20), - const SizedBox(width: 12), - Expanded( - child: Text( - context.l10n.repeater_settingsNotLoaded, + IconButton( + icon: const Icon(Icons.refresh), + tooltip: l10n.repeater_refreshAll, + onPressed: _loadingAll || _isLoading || !connected + ? null + : _refreshAll, + ), + if (_hasChanges) + TextButton.icon( + onPressed: _isLoading || _loadingAll || !connected + ? null + : _saveSettings, + icon: const Icon(Icons.save), + label: Text(l10n.common_save), + ), + ], + bottom: _loadingAll + ? PreferredSize( + preferredSize: const Size.fromHeight(4), + child: LinearProgressIndicator(value: _loadAllProgress), + ) + : null, + ), + body: SafeArea( + top: false, + child: _isLoading && _nameController.text.isEmpty + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.only(bottom: 32), + children: [ + const RadioDisconnectedBanner(), + if (_loadedKeys.isEmpty && !_loadingAll) + Padding( + padding: const EdgeInsets.only(top: 16), + child: MeshCard( + child: Row( + children: [ + const Icon(Icons.info_outline, size: 20), + const SizedBox(width: 12), + Expanded( + child: Text( + context.l10n.repeater_settingsNotLoaded, + ), ), - ), - TextButton( - onPressed: _isLoading ? null : _refreshAll, - child: Text(context.l10n.repeater_refreshAll), - ), - ], + TextButton( + onPressed: _isLoading || !connected + ? null + : _refreshAll, + child: Text(context.l10n.repeater_refreshAll), + ), + ], + ), ), ), - ), - _buildBasicSettingsCard(), - _buildRadioSettingsCard(), - _buildLocationSettingsCard(), - _buildFeatureTogglesCard(), - _buildNetworkHealthCard(), - _buildAdvertisementSettingsCard(), - _buildOwnerInfoCard(), - _buildActionsCard(), - _buildAdvancedCard(), - _buildKeysCard(), - const SizedBox(height: 16), - _buildDangerZoneCard(), - ], - ), + _buildBasicSettingsCard(), + _buildRadioSettingsCard(), + _buildLocationSettingsCard(), + _buildFeatureTogglesCard(), + _buildNetworkHealthCard(), + _buildAdvertisementSettingsCard(), + _buildOwnerInfoCard(), + _buildActionsCard(), + _buildAdvancedCard(), + _buildKeysCard(), + const SizedBox(height: 16), + _buildDangerZoneCard(), + ], + ), + ), ), ); } + Future _confirmDiscardChanges() async { + final l10n = context.l10n; + final choice = await showDialog( + context: context, + builder: (dialogContext) { + final canSave = + !_isLoading && + !_loadingAll && + dialogContext.read().isConnected; + return AlertDialog( + title: Text(l10n.repeater_unsavedChangesTitle), + content: Text(l10n.repeater_unsavedChangesMessage), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(l10n.common_cancel), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, 'discard'), + style: TextButton.styleFrom( + foregroundColor: Theme.of(dialogContext).colorScheme.error, + ), + child: Text(l10n.repeater_discardChanges), + ), + FilledButton( + onPressed: canSave + ? () => Navigator.pop(dialogContext, 'save') + : null, + child: Text(l10n.common_save), + ), + ], + ); + }, + ); + if (!mounted || choice == null) return; + if (choice == 'save') { + await _saveSettings(); + if (!mounted || _hasChanges) return; + } + Navigator.of(context).pop(); + } + Widget _buildBasicSettingsCard() { final l10n = context.l10n; final refreshButton = _refreshingBasic @@ -1824,10 +1955,14 @@ class _RepeaterSettingsScreenState extends State { ], ), Slider( - value: _advertInterval.clamp(60, 240).toDouble(), - min: 60, - max: 240, - divisions: 18, + // Widen the range to include an out-of-range firmware value + // so the knob matches the subtitle. + value: _advertSliderValue.toDouble(), + min: _advertSliderMin.toDouble(), + max: _advertSliderMax.toDouble(), + divisions: (_advertSliderMax - _advertSliderMin) % 10 == 0 + ? (_advertSliderMax - _advertSliderMin) ~/ 10 + : null, label: l10n.repeater_localAdvertIntervalMinutes( _advertInterval, ), @@ -1887,10 +2022,10 @@ class _RepeaterSettingsScreenState extends State { ], ), Slider( - value: _floodAdvertInterval.clamp(3, 168).toDouble(), - min: 3, - max: 168, - divisions: 165, + value: _floodAdvertSliderValue.toDouble(), + min: _floodAdvertSliderMin.toDouble(), + max: _floodAdvertSliderMax.toDouble(), + divisions: _floodAdvertSliderMax - _floodAdvertSliderMin, label: l10n.repeater_floodAdvertIntervalHours( _floodAdvertInterval, ), @@ -1952,6 +2087,23 @@ class _RepeaterSettingsScreenState extends State { ); } + // Slider bounds: the normal UI range, widened to include a non-zero value + // the firmware reported outside it. A disabled (0) value parks the knob at + // the minimum. + int get _advertSliderMin => + _advertInterval > 0 && _advertInterval < 60 ? _advertInterval : 60; + int get _advertSliderMax => _advertInterval > 240 ? _advertInterval : 240; + int get _advertSliderValue => + _advertInterval.clamp(_advertSliderMin, _advertSliderMax); + int get _floodAdvertSliderMin => + _floodAdvertInterval > 0 && _floodAdvertInterval < 3 + ? _floodAdvertInterval + : 3; + int get _floodAdvertSliderMax => + _floodAdvertInterval > 168 ? _floodAdvertInterval : 168; + int get _floodAdvertSliderValue => + _floodAdvertInterval.clamp(_floodAdvertSliderMin, _floodAdvertSliderMax); + Widget _buildNetworkHealthCard() { final l10n = context.l10n; return Column( @@ -2100,6 +2252,8 @@ class _RepeaterSettingsScreenState extends State { Widget _buildActionsCard() { final l10n = context.l10n; + final canAct = + !_runningAction && context.watch().isConnected; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -2112,8 +2266,8 @@ class _RepeaterSettingsScreenState extends State { leading: const Icon(Icons.podcasts), title: Text(l10n.repeater_sendAdvert), subtitle: Text(l10n.repeater_sendAdvertSubtitle), - enabled: !_runningAction, - onTap: _runningAction + enabled: canAct, + onTap: !canAct ? null : () => _runAction('advert', l10n.repeater_sendAdvert), contentPadding: EdgeInsets.zero, @@ -2122,8 +2276,8 @@ class _RepeaterSettingsScreenState extends State { leading: const Icon(Icons.cell_tower), title: Text(l10n.repeater_sendAdvertZeroHop), subtitle: Text(l10n.repeater_sendAdvertZeroHopSubtitle), - enabled: !_runningAction, - onTap: _runningAction + enabled: canAct, + onTap: !canAct ? null : () => _runAction( 'advert.zerohop', @@ -2135,8 +2289,8 @@ class _RepeaterSettingsScreenState extends State { leading: const Icon(Icons.access_time), title: Text(l10n.repeater_clockSync), subtitle: Text(l10n.repeater_clockSyncSubtitle), - enabled: !_runningAction, - onTap: _runningAction + enabled: canAct, + onTap: !canAct ? null : () => _runAction('clock sync', l10n.repeater_clockSync), contentPadding: EdgeInsets.zero, @@ -2351,6 +2505,7 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _prvKeyController, + maxLength: _prvKeyHexLength, inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("[0-9a-fA-F]")), ], @@ -2358,6 +2513,12 @@ class _RepeaterSettingsScreenState extends State { labelText: l10n.repeater_prvKey, helperText: l10n.repeater_prvKeyHelper, helperMaxLines: 3, + errorText: + _prvKeyController.text.isNotEmpty && + !_prvKeyPattern.hasMatch(_prvKeyController.text) + ? l10n.repeater_prvKeyLengthError(_prvKeyHexLength) + : null, + errorMaxLines: 3, border: const OutlineInputBorder(), ), onChanged: (_) { @@ -2365,6 +2526,8 @@ class _RepeaterSettingsScreenState extends State { if (_prvKeyController.text.isNotEmpty) { _markChanged(_SettingField.prvKey); } + // Refresh the inline length error. + setState(() {}); }, ), ), @@ -2456,6 +2619,8 @@ class _RepeaterSettingsScreenState extends State { Widget _buildDangerZoneCard() { final l10n = context.l10n; + final canAct = + !_runningAction && context.watch().isConnected; return MeshCard( color: MeshPalette.alertBg, borderColor: MeshPalette.alertLine, @@ -2488,29 +2653,28 @@ class _RepeaterSettingsScreenState extends State { l10n.repeater_rebootRepeaterSubtitle, style: const TextStyle(color: MeshPalette.warnDim), ), + enabled: canAct, onTap: () => _confirmAction( l10n.repeater_rebootRepeater, l10n.repeater_rebootRepeaterConfirm, - () => _sendDangerCommand('reboot'), + () => _runAction( + 'reboot', + l10n.repeater_rebootRepeater, + replyOptional: true, + ), + isDestructive: true, ), contentPadding: EdgeInsets.zero, ), - // Regenerate identity key - hidden until fully implemented + // Erase is serial-console only in firmware; shown disabled with + // an explanation rather than behind a confirm that does nothing. ListTile( - leading: const Icon(Icons.delete_forever, color: MeshPalette.alert), - title: Text( - l10n.repeater_eraseFileSystem, - style: const TextStyle(color: MeshPalette.alert), - ), + enabled: false, + leading: const Icon(Icons.delete_forever), + title: Text(l10n.repeater_eraseFileSystem), subtitle: Text( - l10n.repeater_eraseFileSystemSubtitle, - style: const TextStyle(color: MeshPalette.warnDim), - ), - onTap: () => _confirmAction( - l10n.repeater_eraseFileSystem, - l10n.repeater_eraseFileSystemConfirm, - () => _sendDangerCommand('erase'), - isDestructive: true, + '${l10n.repeater_eraseFileSystemSubtitle}\n' + '${l10n.repeater_eraseSerialOnly}', ), contentPadding: EdgeInsets.zero, ), @@ -2519,54 +2683,6 @@ class _RepeaterSettingsScreenState extends State { ); } - Future _sendDangerCommand(String command) async { - final l10n = context.l10n; - final connector = Provider.of(context, listen: false); - final repeater = _resolveRepeater(connector); - - if (command == 'erase') { - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(l10n.repeater_eraseSerialOnly), - ); - } - return; - } - - try { - final selection = await connector.preparePathForContactSend(repeater); - final timestampSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000; - connector.trackRepeaterAck( - contact: repeater, - selection: selection, - text: command, - timestampSeconds: timestampSeconds, - ); - final frame = buildSendCliCommandFrame( - repeater.publicKey, - command, - timestampSeconds: timestampSeconds, - ); - await connector.sendFrame(frame); - - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(l10n.repeater_commandSent(command)), - ); - } - } catch (e) { - if (mounted) { - showDismissibleSnackBar( - context, - content: Text(l10n.repeater_errorSendingCommand(e.toString())), - backgroundColor: Theme.of(context).colorScheme.error, - ); - } - } - } - void _confirmAction( String title, String message, diff --git a/lib/screens/repeater_status_screen.dart b/lib/screens/repeater_status_screen.dart index a3661a18..5faf8708 100644 --- a/lib/screens/repeater_status_screen.dart +++ b/lib/screens/repeater_status_screen.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; @@ -14,8 +15,8 @@ import '../services/repeater_command_service.dart'; import '../theme/mesh_theme.dart'; import '../utils/battery_utils.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/radio_disconnected_banner.dart'; import '../widgets/routing_sheet.dart'; -import '../helpers/snack_bar_builder.dart'; class RepeaterStatusScreen extends StatefulWidget { final Contact repeater; @@ -60,6 +61,7 @@ class _RepeaterStatusScreenState extends State { int? _dupDirect; double? _chanUtil; PathSelection? _pendingStatusSelection; + String? _loadError; @override void initState() { @@ -116,7 +118,16 @@ class _RepeaterStatusScreenState extends State { if (parsed == null) return; if (!_matchesRepeaterPrefix(parsed.senderPrefix)) return; _commandService?.handleResponse(widget.repeater, parsed.text); - _parseStatusResponse(parsed.text); + // Only a reply that actually carried status fields ends the request; + // any other text from this repeater (e.g. a CLI reply) is ignored here. + if (!_parseStatusResponse(parsed.text)) return; + _statusTimeout?.cancel(); + if (mounted) { + setState(() { + _isLoading = false; + _loadError = null; + }); + } _recordStatusResult(true); } @@ -132,6 +143,7 @@ class _RepeaterStatusScreenState extends State { final rxAirSecs = stats.rxAirSecs; setState(() { _isLoading = false; + _loadError = null; _batteryMv = stats.batteryMv; _queueLen = stats.queueLen; _noiseFloor = stats.noiseFloor; @@ -177,8 +189,10 @@ class _RepeaterStatusScreenState extends State { return true; } - void _parseStatusResponse(String response) { + /// Applies a JSON status reply. Returns true if any status field was set. + bool _parseStatusResponse(String response) { final trimmed = response.trim(); + var applied = false; if (trimmed.startsWith('{') && trimmed.endsWith('}')) { try { final data = jsonDecode(trimmed) as Map; @@ -187,6 +201,7 @@ class _RepeaterStatusScreenState extends State { _uptimeSecs = _asInt(data['uptime_secs']); _queueLen = _asInt(data['queue_len']); _debugFlags = _asInt(data['errors']); + applied = true; final batteryMv = _batteryMv; if (batteryMv != null) { final connector = Provider.of( @@ -205,6 +220,7 @@ class _RepeaterStatusScreenState extends State { _lastSnr = _asDouble(data['last_snr']); _txAirSecs = _asInt(data['tx_air_secs']); _rxAirSecs = _asInt(data['rx_air_secs']); + applied = true; } else if (data.containsKey('recv') || data.containsKey('sent')) { _packetsRecv = _asInt(data['recv']); _packetsSent = _asInt(data['sent']); @@ -214,17 +230,30 @@ class _RepeaterStatusScreenState extends State { _directRx = _asInt(data['direct_rx']); _dupFlood = _asInt(data['dup_flood']); _dupDirect = _asInt(data['dup_direct']); + applied = true; } } catch (_) {} } - if (mounted) setState(() {}); + if (applied && mounted) setState(() {}); + return applied; } + bool get _hasAnyStatus => + _batteryMv != null || + _uptimeSecs != null || + _queueLen != null || + _lastRssi != null || + _noiseFloor != null || + _txAirSecs != null || + _packetsSent != null || + _packetsRecv != null; + Future _loadStatus() async { if (_commandService == null) return; setState(() { _isLoading = true; + _loadError = null; _pendingStatusSelection = null; _batteryMv = null; _uptimeSecs = null; @@ -269,22 +298,18 @@ class _RepeaterStatusScreenState extends State { _statusTimeout?.cancel(); _statusTimeout = Timer(Duration(milliseconds: timeoutMs), () { if (!mounted) return; - setState(() => _isLoading = false); - showDismissibleSnackBar( - context, - content: Text(context.l10n.repeater_statusRequestTimeout), - backgroundColor: Theme.of(context).colorScheme.error, - ); + setState(() { + _isLoading = false; + _loadError = context.l10n.repeater_statusRequestTimeout; + }); _recordStatusResult(false); }); } catch (e) { if (mounted) { - setState(() => _isLoading = false); - showDismissibleSnackBar( - context, - content: Text(context.l10n.repeater_errorLoadingStatus(e.toString())), - backgroundColor: Theme.of(context).colorScheme.error, - ); + setState(() { + _isLoading = false; + _loadError = context.l10n.repeater_errorLoadingStatus(e.toString()); + }); } _recordStatusResult(false); } @@ -338,11 +363,8 @@ class _RepeaterStatusScreenState extends State { final connector = Provider.of(context, listen: false); final dt = connector.repeaterClockAtLogin(widget.repeater.publicKey); if (dt == null) return '—'; - final local = dt.toLocal(); - final date = '${local.day}/${local.month}/${local.year}'; - final time = - '${local.hour.toString().padLeft(2, '0')}:${local.minute.toString().padLeft(2, '0')}'; - return '$date $time'; + final locale = Localizations.localeOf(context).toLanguageTag(); + return DateFormat.yMd(locale).add_Hm().format(dt.toLocal()); } String _formatDuration(int? seconds) { @@ -412,6 +434,7 @@ class _RepeaterStatusScreenState extends State { final connector = context.watch(); final repeater = _resolveRepeater(connector); final isFloodMode = repeater.pathOverride == -1; + final canRefresh = !_isLoading && connector.isConnected; return Scaffold( appBar: AppBar( @@ -432,18 +455,25 @@ class _RepeaterStatusScreenState extends State { child: CircularProgressIndicator(strokeWidth: 2), ) : const Icon(Icons.refresh), - onPressed: _isLoading ? null : _loadStatus, + onPressed: canRefresh ? _loadStatus : null, tooltip: l10n.repeater_refresh, ), ], ), body: SafeArea( top: false, - child: RefreshIndicator( - onRefresh: _loadStatus, - child: _isLoading && _batteryMv == null - ? const Center(child: CircularProgressIndicator()) - : _buildBody(l10n, repeater.name), + child: Column( + children: [ + const RadioDisconnectedBanner(), + Expanded( + child: RefreshIndicator( + onRefresh: connector.isConnected ? _loadStatus : () async {}, + child: _isLoading && !_hasAnyStatus + ? const Center(child: CircularProgressIndicator()) + : _buildBody(l10n, repeater.name), + ), + ), + ], ), ), ); @@ -451,9 +481,21 @@ class _RepeaterStatusScreenState extends State { Widget _buildBody(dynamic l10n, String name) { final scheme = Theme.of(context).colorScheme; + final error = _loadError; + if (error != null && !_hasAnyStatus) { + return ListView( + padding: const EdgeInsets.only(top: 16, bottom: 24), + children: [_buildErrorCard(error)], + ); + } return ListView( padding: const EdgeInsets.only(bottom: 24), children: [ + if (error != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: _buildErrorCard(error), + ), // ── System ───────────────────────────────────────────────────────── SectionHeader(l10n.repeater_systemInformation), Padding( @@ -502,7 +544,7 @@ class _RepeaterStatusScreenState extends State { _StatItem( icon: Icons.signal_cellular_alt, label: l10n.repeater_lastRssi, - value: _formatValue(_lastRssi, suffix: ' dB'), + value: _formatValue(_lastRssi, suffix: ' dBm'), color: MeshPalette.blue, ), _StatItem( @@ -514,7 +556,7 @@ class _RepeaterStatusScreenState extends State { _StatItem( icon: Icons.noise_control_off, label: l10n.repeater_noiseFloor, - value: _formatValue(_noiseFloor, suffix: ' dB'), + value: _formatValue(_noiseFloor, suffix: ' dBm'), color: scheme.onSurfaceVariant, ), _StatItem( @@ -596,6 +638,49 @@ class _RepeaterStatusScreenState extends State { ); } + Widget _buildErrorCard(String message) { + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + final connected = context.watch().isConnected; + return MeshCard( + color: scheme.errorContainer, + borderColor: scheme.error, + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.error_outline, + size: 24, + color: scheme.onErrorContainer, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + message, + style: textTheme.bodyLarge?.copyWith( + color: scheme.onErrorContainer, + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Align( + alignment: AlignmentDirectional.centerEnd, + child: FilledButton.icon( + onPressed: _isLoading || !connected ? null : _loadStatus, + icon: const Icon(Icons.refresh), + label: Text(context.l10n.common_retry), + ), + ), + ], + ), + ); + } + Color _batteryColor() { final connector = context.watch(); final batteryMv = diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart index 9b9b1e33..a1ecbed3 100644 --- a/lib/screens/scanner_screen.dart +++ b/lib/screens/scanner_screen.dart @@ -42,6 +42,8 @@ class _ScannerScreenState extends State { _connector = Provider.of(context, listen: false); _connectionListener = () { + // ModalRoute.of needs a live element, so bail out before touching it. + if (!mounted) return; final isCurrentRoute = ModalRoute.of(context)?.isCurrent ?? true; if (_connector.state == MeshCoreConnectionState.disconnected) { _changedNavigation = false; @@ -53,11 +55,9 @@ class _ScannerScreenState extends State { isCurrentRoute && !_changedNavigation) { _changedNavigation = true; - if (mounted) { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => const ChannelsScreen()), - ); - } + Navigator.of( + context, + ).push(MaterialPageRoute(builder: (context) => const ChannelsScreen())); } }; @@ -448,16 +448,13 @@ class _BluetoothOffBanner extends StatelessWidget { style: TextStyle( color: scheme.error, fontWeight: FontWeight.w600, - fontSize: 13.5, + fontSize: 15, ), ), const SizedBox(height: 2), Text( context.l10n.scanner_bluetoothOffMessage, - style: TextStyle( - color: scheme.error.withValues(alpha: 0.8), - fontSize: 12, - ), + style: TextStyle(color: scheme.error, fontSize: 14), ), ], ), diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 5b0e0384..4656e8a4 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,4 +1,3 @@ -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:meshcore_open/utils/gpx_export.dart'; @@ -9,14 +8,14 @@ import 'package:package_info_plus/package_info_plus.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../l10n/l10n.dart'; -import '../models/radio_settings.dart'; import '../services/app_settings_service.dart'; -import '../services/app_debug_log_service.dart'; import '../theme/mesh_theme.dart'; import '../widgets/app_bar.dart'; import '../helpers/snack_bar_builder.dart'; import '../helpers/utf8_length_limiter.dart'; +import '../widgets/mesh_nav_tile.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/radio_settings_dialog.dart'; import 'app_settings_screen.dart'; import 'app_debug_log_screen.dart'; import 'ble_debug_log_screen.dart'; @@ -26,30 +25,9 @@ import '../widgets/sync_progress_overlay.dart'; import 'region_management_screen.dart'; import '../utils/share_origin.dart'; -/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others) -/// to the UI enum range (always 5-8). -int _toUiCodingRate(int deviceCr) { - return deviceCr <= 4 ? deviceCr + 4 : deviceCr; -} - -const Set _defaultRepeatFreqsKHz = {433000, 869495, 918000}; - -/// Whether the firmware accepts [freqKHz] for off-grid client repeat, using -/// the ranges from CMD_GET_ALLOWED_REPEAT_FREQ when known. -bool _isAllowedRepeatFreqKHz(MeshCoreConnector connector, int freqKHz) { - final ranges = connector.allowedRepeatFreqRanges; - if (ranges == null || ranges.isEmpty) { - return _defaultRepeatFreqsKHz.contains(freqKHz); - } - return ranges.any((r) => freqKHz >= r.lowKHz && freqKHz <= r.highKHz); -} - /// Companion firmware version that added CMD_SET_PATH_HASH_MODE (v1.14.0). const int _minFirmwareVerCodeForPathHashMode = 10; -/// Lowest TX power companion firmware accepts (CMD_SET_RADIO_TX_POWER). -const int _minTxPowerDbm = -9; - class SettingsScreen extends StatefulWidget { const SettingsScreen({super.key}); @@ -91,131 +69,147 @@ class _SettingsScreenState extends State { ), body: SafeArea( top: false, - child: Consumer( - builder: (context, connector, child) { - return ListView( - padding: const EdgeInsets.fromLTRB(0, 8, 0, 24), - children: [ - // IDENTITY section - SectionHeader(l10n.settings_deviceInfo), - MeshCard( - padding: EdgeInsets.zero, - child: _buildIdentityCardContent(context, connector), + // Each card selects only the connector fields it renders, so the + // frequent unrelated connector notifications (frames, contacts, + // messages) do not rebuild the whole settings list. + child: ListView( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 24), + children: [ + // IDENTITY section + SectionHeader(l10n.settings_deviceInfo), + MeshCard( + padding: EdgeInsets.zero, + child: _selectConnector( + (c) => ( + c.deviceDisplayName, + c.isConnected, + c.deviceIdLabel, + c.batteryPercent, + c.batteryMillivolts, + c.manufacturerName, + c.firmwareVersionString, + c.selfName, + c.selfPublicKey == null ? null : c.selfPublicKeyHex, + c.contacts.length, + c.channels.length, ), + _buildIdentityCardContent, + ), + ), - // NODE section - SectionHeader(l10n.settings_nodeSettings), - MeshCard( - padding: EdgeInsets.zero, - child: _buildNodeCardContent(context, connector), + // NODE section + SectionHeader(l10n.settings_nodeSettings), + MeshCard( + padding: EdgeInsets.zero, + child: _selectConnector( + (c) => ( + c.isConnected, + c.selfName, + c.supportsCompanionRadioStats, + c.firmwareVerCode, + c.pathHashByteWidth, ), + _buildNodeCardContent, + ), + ), - // LOCATION section - SectionHeader(l10n.settings_location), - MeshCard( - padding: EdgeInsets.zero, - child: _buildLocationCardContent(context, connector), - ), + // LOCATION section + SectionHeader(l10n.settings_location), + MeshCard( + padding: EdgeInsets.zero, + child: _selectConnector( + (c) => c.isConnected, + _buildLocationCardContent, + ), + ), - // APP SETTINGS - SectionHeader(l10n.settings_appSettings), - MeshCard( - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (_) => const AppSettingsScreen(), - ), - ), - child: _buildNavTileContent( - context, - icon: Icons.settings_outlined, - title: l10n.settings_appSettings, - subtitle: l10n.settings_appSettingsSubtitle, - ), + // APP SETTINGS + SectionHeader(l10n.settings_appSettings), + MeshCard( + padding: EdgeInsets.zero, + child: MeshNavTile( + icon: Icons.settings_outlined, + title: l10n.settings_appSettings, + subtitle: l10n.settings_appSettingsSubtitle, + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const AppSettingsScreen()), ), + ), + ), - // ACTIONS section - SectionHeader(l10n.settings_actions), - MeshCard( - padding: EdgeInsets.zero, - child: _buildActionsCardContent(context, connector), - ), + // ACTIONS section + SectionHeader(l10n.settings_actions), + MeshCard( + padding: EdgeInsets.zero, + child: _selectConnector( + (c) => c.isConnected, + _buildActionsCardContent, + ), + ), - // EXPORT section - SectionHeader(l10n.settings_gpxExportRepeaters), - MeshCard( - padding: EdgeInsets.zero, - child: _buildExportCardContent(context, connector), - ), + // EXPORT section + SectionHeader(l10n.settings_gpxExportRepeaters), + MeshCard( + padding: EdgeInsets.zero, + child: _buildExportCardContent( + context, + context.read(), + ), + ), - // DEBUG section - SectionHeader(l10n.settings_debug), - MeshCard( - padding: EdgeInsets.zero, - child: _buildDebugCardContent(context), - ), + // DEBUG section + SectionHeader(l10n.settings_debug), + MeshCard( + padding: EdgeInsets.zero, + child: _buildDebugCardContent(context), + ), - // ABOUT - SectionHeader(l10n.settings_about), - MeshCard( - onTap: () => _showAbout(context), - child: _buildNavTileContent( - context, - icon: Icons.info_outline, - title: l10n.settings_about, - subtitle: l10n.settings_aboutVersion( - _appVersion.isEmpty ? l10n.common_loading : _appVersion, - ), - showChevron: false, - ), + // ABOUT + SectionHeader(l10n.settings_about), + MeshCard( + padding: EdgeInsets.zero, + child: MeshNavTile( + icon: Icons.info_outline, + title: l10n.settings_about, + subtitle: l10n.settings_aboutVersion( + _appVersion.isEmpty ? l10n.common_loading : _appVersion, ), - ], - ); - }, + showChevron: false, + onTap: () => _showAbout(context), + ), + ), + ], ), ), ); } - Widget _buildNavTileContent( - BuildContext context, { - required IconData icon, - required String title, - required String subtitle, - bool showChevron = true, - }) { - final scheme = Theme.of(context).colorScheme; - final textTheme = Theme.of(context).textTheme; - return Row( - children: [ - Icon(icon, size: 20, color: scheme.onSurfaceVariant), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 2), - Text( - subtitle, - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - if (showChevron) - Icon(Icons.chevron_right, color: scheme.onSurfaceVariant, size: 16), - ], + /// Rebuilds [builder] only when [selector]'s value changes (records compare + /// field by field) or when this screen itself rebuilds. + Widget _selectConnector( + T Function(MeshCoreConnector connector) selector, + Widget Function(BuildContext context, MeshCoreConnector connector) builder, + ) { + return Selector( + selector: (_, connector) => selector(connector), + builder: (context, _, _) => + builder(context, context.read()), ); } + /// Guards a radio command: returns false (after telling the user) when the + /// radio is not connected, because the connector silently ignores commands + /// sent while disconnected and a success message would be a lie. + bool _ensureConnected(BuildContext context, MeshCoreConnector connector) { + if (connector.isConnected) return true; + showDismissibleSnackBar( + context, + content: Text(context.l10n.settings_notConnectedError), + ); + return false; + } + Widget _buildIdentityCardContent( BuildContext context, MeshCoreConnector connector, @@ -348,6 +342,12 @@ class _SettingsScreenState extends State { label: label, value: publicKeyHex, mono: true, + semanticsHint: context.l10n.settings_publicKeyCopyHint, + trailing: Icon( + Icons.copy_outlined, + size: 20, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), onTap: () => _copyPublicKey(context, publicKeyHex), ); } @@ -368,12 +368,14 @@ class _SettingsScreenState extends State { bool mono = false, Widget? leading, Color? valueColor, + Widget? trailing, + String? semanticsHint, VoidCallback? onTap, }) { final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; - final content = Padding( + Widget content = Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -383,7 +385,7 @@ class _SettingsScreenState extends State { if (leading != null) ...[leading, const SizedBox(width: 6)], Text( label, - style: textTheme.bodySmall?.copyWith( + style: textTheme.bodyMedium?.copyWith( color: scheme.onSurfaceVariant, fontWeight: FontWeight.w500, ), @@ -395,14 +397,14 @@ class _SettingsScreenState extends State { ? Text( value, style: MeshTheme.mono( - fontSize: 13, + fontSize: 15, fontWeight: FontWeight.w500, color: valueColor ?? scheme.onSurface, ), ) : Text( value, - style: textTheme.bodyMedium?.copyWith( + style: textTheme.bodyLarge?.copyWith( fontWeight: FontWeight.w500, color: valueColor, ), @@ -411,11 +413,25 @@ class _SettingsScreenState extends State { ), ); + if (trailing != null) { + content = Row( + children: [ + Expanded(child: content), + const SizedBox(width: 8), + trailing, + ], + ); + } + if (onTap != null) { - return InkWell( - borderRadius: BorderRadius.circular(MeshRadii.xs), - onTap: onTap, - child: content, + return Semantics( + button: true, + hint: semanticsHint, + child: InkWell( + borderRadius: BorderRadius.circular(MeshRadii.xs), + onTap: onTap, + child: content, + ), ); } return content; @@ -462,10 +478,23 @@ class _SettingsScreenState extends State { return _infoRow( context, + semanticsHint: millivolts != null + ? l10n.settings_batteryToggleHint + : null, label: l10n.settings_infoBattery, value: displayValue, - leading: Icon(icon, size: 14, color: iconColor), + leading: Icon(icon, size: 20, color: iconColor), valueColor: valueColor, + trailing: millivolts != null + ? Tooltip( + message: l10n.settings_batteryToggleHint, + child: Icon( + Icons.swap_horiz, + size: 20, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ) + : null, onTap: millivolts != null ? () { setState(() { @@ -481,38 +510,41 @@ class _SettingsScreenState extends State { MeshCoreConnector connector, ) { final l10n = context.l10n; + final connected = connector.isConnected; + final offline = l10n.settings_requiresConnection; return Column( children: [ - _tappableTile( - context, + MeshNavTile( icon: Icons.person_outline, title: l10n.settings_nodeName, - subtitle: connector.selfName ?? l10n.settings_nodeNameNotSet, - onTap: () => _editNodeName(context, connector), + subtitle: connected + ? connector.selfName ?? l10n.settings_nodeNameNotSet + : offline, + onTap: connected ? () => _editNodeName(context, connector) : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.radio, title: l10n.settings_radioSettings, - subtitle: l10n.settings_radioSettingsSubtitle, - onTap: () => _showRadioSettings(context, connector), + subtitle: connected ? l10n.settings_radioSettingsSubtitle : offline, + onTap: connected + ? () => _showRadioSettings(context, connector) + : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.landscape, title: l10n.settings_regionSettings, subtitle: l10n.settings_regionSettingsSubtitle, onTap: () => pushRegionManagementScreen(context), ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.sensors_outlined, title: l10n.radioStats_settingsTile, - subtitle: - connector.isConnected && !connector.supportsCompanionRadioStats + subtitle: !connected + ? offline + : !connector.supportsCompanionRadioStats ? l10n.settings_requiresFirmware('v1.10') : l10n.radioStats_settingsSubtitle, onTap: connector.isConnected && connector.supportsCompanionRadioStats @@ -520,24 +552,22 @@ class _SettingsScreenState extends State { : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.thermostat_outlined, title: l10n.contact_telemetry, - subtitle: l10n.repeater_telemetrySubtitle, + subtitle: connected ? l10n.repeater_telemetrySubtitle : offline, onTap: connector.isConnected ? () => pushSelfTelemetryScreen(context) : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.route_outlined, title: l10n.repeater_pathHashMode, - subtitle: - connector.isConnected && - (connector.firmwareVerCode ?? 0) < - _minFirmwareVerCodeForPathHashMode + subtitle: !connected + ? offline + : (connector.firmwareVerCode ?? 0) < + _minFirmwareVerCodeForPathHashMode ? l10n.settings_requiresFirmware('v1.14') : _pathHashModeSubtitle(context, connector.pathHashByteWidth), onTap: @@ -566,30 +596,31 @@ class _SettingsScreenState extends State { MeshCoreConnector connector, ) { final l10n = context.l10n; + final connected = connector.isConnected; + final offline = l10n.settings_requiresConnection; return Column( children: [ - _tappableTile( - context, + MeshNavTile( icon: Icons.location_on_outlined, title: l10n.settings_location, - subtitle: l10n.settings_locationSubtitle, - onTap: () => _editLocation(context, connector), + subtitle: connected ? l10n.settings_locationSubtitle : offline, + onTap: connected ? () => _editLocation(context, connector) : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.group_add_outlined, title: l10n.settings_contactSettings, - subtitle: l10n.settings_contactSettingsSubtitle, - onTap: () => _editAutoAddConfig(context, connector), + subtitle: connected ? l10n.settings_contactSettingsSubtitle : offline, + onTap: connected + ? () => _editAutoAddConfig(context, connector) + : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.visibility_off_outlined, title: l10n.settings_privacy, - subtitle: l10n.settings_privacySubtitle, - onTap: () => _privacySettings(context, connector), + subtitle: connected ? l10n.settings_privacySubtitle : offline, + onTap: connected ? () => _privacySettings(context, connector) : null, ), ], ); @@ -600,36 +631,34 @@ class _SettingsScreenState extends State { MeshCoreConnector connector, ) { final l10n = context.l10n; + final connected = connector.isConnected; + final offline = l10n.settings_requiresConnection; return Column( children: [ - _tappableTile( - context, + MeshNavTile( icon: Icons.sync, title: l10n.settings_syncTime, - subtitle: l10n.settings_syncTimeSubtitle, - onTap: () => _syncTime(context, connector), + subtitle: connected ? l10n.settings_syncTimeSubtitle : offline, + onTap: connected ? () => _syncTime(context, connector) : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.refresh, title: l10n.settings_refreshContacts, - subtitle: l10n.settings_refreshContactsSubtitle, - onTap: () => connector.getContacts(), + subtitle: connected ? l10n.settings_refreshContactsSubtitle : offline, + onTap: connected ? () => connector.getContacts() : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.restart_alt, title: l10n.settings_rebootDevice, - subtitle: l10n.settings_rebootDeviceSubtitle, + subtitle: connected ? l10n.settings_rebootDeviceSubtitle : offline, titleColor: MeshPalette.warn, iconColor: MeshPalette.warn, - onTap: () => _confirmReboot(context, connector), + onTap: connected ? () => _confirmReboot(context, connector) : null, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.delete_outline, title: l10n.settings_deleteAllPaths, subtitle: l10n.settings_deleteAllPathsSubtitle, @@ -648,8 +677,7 @@ class _SettingsScreenState extends State { final l10n = context.l10n; return Column( children: [ - _tappableTile( - context, + MeshNavTile( icon: Icons.download_outlined, title: l10n.settings_gpxExportRepeaters, subtitle: l10n.settings_gpxExportRepeatersSubtitle, @@ -667,8 +695,7 @@ class _SettingsScreenState extends State { }, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.download_outlined, title: l10n.settings_gpxExportContacts, subtitle: l10n.settings_gpxExportContactsSubtitle, @@ -686,8 +713,7 @@ class _SettingsScreenState extends State { }, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.download_outlined, title: l10n.settings_gpxExportAll, subtitle: l10n.settings_gpxExportAllSubtitle, @@ -712,8 +738,7 @@ class _SettingsScreenState extends State { final l10n = context.l10n; return Column( children: [ - _tappableTile( - context, + MeshNavTile( icon: Icons.bluetooth_outlined, title: l10n.settings_companionDebugLog, subtitle: l10n.settings_companionDebugLogSubtitle, @@ -727,8 +752,7 @@ class _SettingsScreenState extends State { }, ), const Divider(height: 1, indent: 16), - _tappableTile( - context, + MeshNavTile( icon: Icons.code_outlined, title: l10n.settings_appDebugLog, subtitle: l10n.settings_appDebugLogSubtitle, @@ -745,112 +769,38 @@ class _SettingsScreenState extends State { ); } - Widget _tappableTile( - BuildContext context, { - required IconData icon, - required String title, - required String subtitle, - VoidCallback? onTap, - Color? titleColor, - Color? iconColor, - }) { - final scheme = Theme.of(context).colorScheme; - final textTheme = Theme.of(context).textTheme; - final effectiveIconColor = iconColor ?? scheme.onSurfaceVariant; - - return InkWell( - onTap: onTap, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Icon(icon, size: 20, color: effectiveIconColor), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - color: titleColor, - ), - ), - const SizedBox(height: 2), - Text( - subtitle, - style: textTheme.bodySmall?.copyWith( - color: titleColor != null - ? titleColor.withValues(alpha: 0.7) - : scheme.onSurfaceVariant, - ), - ), - ], - ), - ), - Icon(Icons.chevron_right, color: scheme.onSurfaceVariant, size: 16), - ], - ), - ), - ); - } - - void _editNodeName(BuildContext context, MeshCoreConnector connector) { + Future _editNodeName( + BuildContext context, + MeshCoreConnector connector, + ) async { final l10n = context.l10n; - // The dialog's own context is gone after it pops, so report back - // through the screen's context. - final screenContext = context; - final controller = TextEditingController(text: connector.selfName ?? ''); - showDialog( + final name = await showDialog( context: context, - builder: (context) => AlertDialog( - title: Text(l10n.settings_nodeName), - content: TextField( - controller: controller, - decoration: InputDecoration( - hintText: l10n.settings_nodeNameHint, - border: const OutlineInputBorder(), - ), - inputFormatters: const [ - Utf8LengthLimitingTextInputFormatter(maxRadioNameBytes), - ], - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_cancel), - ), - ListenableBuilder( - listenable: controller, - builder: (context, _) { - final name = controller.text.trim(); - return TextButton( - onPressed: name.isEmpty - ? null - : () async { - Navigator.pop(context); - await connector.setNodeName(name); - await connector.refreshDeviceInfo(); - if (!screenContext.mounted) return; - showDismissibleSnackBar( - screenContext, - content: Text(l10n.settings_nodeNameUpdated), - ); - }, - child: Text(l10n.common_save), - ); - }, - ), - ], - ), + builder: (_) => _NodeNameDialog(initialName: connector.selfName ?? ''), ); + if (name == null || !context.mounted) return; + if (!_ensureConnected(context, connector)) return; + try { + await connector.setNodeName(name); + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_nodeNameUpdated), + ); + } catch (e) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + } } void _showRadioSettings(BuildContext context, MeshCoreConnector connector) { showDialog( context: context, - builder: (context) => _RadioSettingsDialog(connector: connector), + builder: (context) => RadioSettingsDialog(connector: connector), ); } @@ -895,7 +845,7 @@ class _SettingsScreenState extends State { const SizedBox(height: 12), Text( l10n.settings_pathHashModeHelper, - style: Theme.of(builderContext).textTheme.bodySmall, + style: Theme.of(builderContext).textTheme.bodyMedium, ), ], ), @@ -907,6 +857,7 @@ class _SettingsScreenState extends State { FilledButton( onPressed: () async { Navigator.pop(dialogContext); + if (!_ensureConnected(context, connector)) return; try { await connector.setPathHashMode(selectedMode); await connector.refreshDeviceInfo(); @@ -931,192 +882,90 @@ class _SettingsScreenState extends State { ); } - void _editLocation(BuildContext context, MeshCoreConnector connector) { + Future _editLocation( + BuildContext context, + MeshCoreConnector connector, + ) async { final l10n = context.l10n; final settingsService = context.read(); - final latController = TextEditingController(); - final lonController = TextEditingController(); - final intervalController = TextEditingController(); - latController.text = connector.selfLatitude?.toStringAsFixed(6) ?? ''; - lonController.text = connector.selfLongitude?.toStringAsFixed(6) ?? ''; // Safe access to custom vars - may be null before device responds final customVars = connector.currentCustomVars ?? {}; final bool hasGPS = customVars.containsKey("gps"); final bool initialGPSEnabled = customVars["gps"] == "1"; - bool isGPSEnabled = initialGPSEnabled; - final currentInterval = settingsService.resolvedGpsIntervalSeconds( - customVars, - ); - intervalController.text = currentInterval.toString(); - - String? intervalError; - String? locationError; - - showDialog( + final edit = await showDialog<_LocationEdit>( context: context, - builder: (dialogContext) => StatefulBuilder( - builder: (builderContext, setDialogState) => AlertDialog( - title: Text(l10n.settings_location), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: latController, - decoration: InputDecoration( - labelText: l10n.settings_latitude, - border: const OutlineInputBorder(), - ), - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - signed: true, - ), - ), - const SizedBox(height: 16), - TextField( - controller: lonController, - onChanged: (_) { - if (locationError != null) { - setDialogState(() => locationError = null); - } - }, - decoration: InputDecoration( - labelText: l10n.settings_longitude, - border: const OutlineInputBorder(), - errorText: locationError, - errorMaxLines: 2, - ), - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - signed: true, - ), - ), - if (hasGPS) ...[ - const SizedBox(height: 16), - TextField( - controller: intervalController, - onChanged: (_) { - if (intervalError != null) { - setDialogState(() => intervalError = null); - } - }, - decoration: InputDecoration( - labelText: l10n.settings_locationIntervalSec, - border: const OutlineInputBorder(), - errorText: intervalError, - ), - keyboardType: const TextInputType.numberWithOptions( - decimal: false, - signed: false, - ), - ), - const SizedBox(height: 16), - FeatureToggleRow( - title: l10n.settings_locationGPSEnable, - subtitle: l10n.settings_locationGPSEnableSubtitle, - value: isGPSEnabled, - // Applied on Save so Cancel leaves the device untouched. - onChanged: (value) => - setDialogState(() => isGPSEnabled = value), - ), - ], - ], - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(l10n.common_cancel), - ), - TextButton( - onPressed: () async { - // Validate every field before closing so a typo doesn't - // discard the input or leave half the changes applied. - int? interval; - if (hasGPS) { - final intervalText = intervalController.text.trim(); - if (intervalText.isNotEmpty) { - interval = int.tryParse(intervalText); - if (interval == null || - interval < 60 || - interval >= 86400) { - setDialogState(() { - intervalError = l10n.settings_locationIntervalInvalid; - }); - return; - } - } - } - - final latText = latController.text.trim(); - final lonText = lonController.text.trim(); - double? lat; - double? lon; - if (latText.isNotEmpty || lonText.isNotEmpty) { - lat = latText.isNotEmpty - ? double.tryParse(latText) - : connector.selfLatitude; - lon = lonText.isNotEmpty - ? double.tryParse(lonText) - : connector.selfLongitude; - if (lat == null || lon == null) { - setDialogState(() { - locationError = l10n.settings_locationBothRequired; - }); - return; - } - if (lat < -90 || lat > 90 || lon < -180 || lon > 180) { - setDialogState(() { - locationError = l10n.settings_locationInvalid; - }); - return; - } - } - - Navigator.pop(dialogContext); - - var changed = false; - if (hasGPS && isGPSEnabled != initialGPSEnabled) { - await connector.setCustomVar( - isGPSEnabled ? "gps:1" : "gps:0", - ); - changed = true; - } - if (interval != null) { - await settingsService.setGpsIntervalSeconds( - interval, - writeToDevice: (value) => - connector.setCustomVar("gps_interval:$value"), - ); - changed = true; - } - if (lat != null && lon != null) { - await connector.setNodeLocation(lat: lat, lon: lon); - changed = true; - } - if (!changed) return; - await connector.refreshDeviceInfo(); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.settings_locationUpdated), - ); - }, - child: Text(l10n.common_save), - ), - ], + builder: (_) => _LocationDialog( + latitude: connector.selfLatitude, + longitude: connector.selfLongitude, + hasGPS: hasGPS, + initialGPSEnabled: initialGPSEnabled, + initialIntervalSeconds: settingsService.resolvedGpsIntervalSeconds( + customVars, ), ), ); + if (edit == null || !edit.hasChanges || !context.mounted) return; + if (!_ensureConnected(context, connector)) return; + + try { + final gpsEnabled = edit.gpsEnabled; + if (gpsEnabled != null) { + await connector.setCustomVar(gpsEnabled ? "gps:1" : "gps:0"); + } + final interval = edit.intervalSeconds; + if (interval != null) { + await settingsService.setGpsIntervalSeconds( + interval, + writeToDevice: (value) => + connector.setCustomVar("gps_interval:$value"), + ); + } + final lat = edit.latitude; + final lon = edit.longitude; + if (lat != null && lon != null) { + await connector.setNodeLocation(lat: lat, lon: lon); + } + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + edit.clearsLocation + ? l10n.settings_locationCleared + : l10n.settings_locationUpdated, + ), + ); + } catch (e) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + } } - void _syncTime(BuildContext context, MeshCoreConnector connector) { + Future _syncTime( + BuildContext context, + MeshCoreConnector connector, + ) async { final l10n = context.l10n; - connector.syncTime(); - showDismissibleSnackBar( - context, - content: Text(l10n.settings_timeSynchronized), - ); + if (!_ensureConnected(context, connector)) return; + try { + await connector.syncTime(); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_timeSynchronized), + ); + } catch (e) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + } } void _confirmDeleteAllPaths( @@ -1151,6 +1000,7 @@ class _SettingsScreenState extends State { void _confirmReboot(BuildContext context, MeshCoreConnector connector) { final l10n = context.l10n; + final screenContext = context; showDialog( context: context, builder: (context) => AlertDialog( @@ -1164,6 +1014,7 @@ class _SettingsScreenState extends State { TextButton( onPressed: () { Navigator.pop(context); + if (!_ensureConnected(screenContext, connector)) return; connector.rebootDevice(); }, child: Text( @@ -1239,6 +1090,8 @@ class _SettingsScreenState extends State { void _editAutoAddConfig(BuildContext context, MeshCoreConnector connector) { final l10n = context.l10n; + // The dialog's context is gone once it pops; report through the screen. + final screenContext = context; bool autoAddChat = false; bool autoAddRepeater = false; bool autoAddRoomServer = false; @@ -1335,16 +1188,17 @@ class _SettingsScreenState extends State { onPressed: saving ? null : () async { + if (!_ensureConnected(context, connector)) return; setDialogState(() => saving = true); - _sendSettings( - connector, - autoAddChat, - autoAddRepeater, - autoAddRoomServer, - autoAddSensor, - overwriteOldest, - ); try { + await _sendSettings( + connector, + autoAddChat, + autoAddRepeater, + autoAddRoomServer, + autoAddSensor, + overwriteOldest, + ); await appSettingsService .setEvictDiscoveredContactsEnabled( evictDiscoveredContactsEnabled, @@ -1363,6 +1217,10 @@ class _SettingsScreenState extends State { } if (!context.mounted) return; Navigator.pop(context); + showDismissibleSnackBar( + screenContext, + content: Text(l10n.settings_contactSettingsSaved), + ); }, child: Text(l10n.common_save), ), @@ -1372,7 +1230,7 @@ class _SettingsScreenState extends State { ); } - void _sendSettings( + Future _sendSettings( MeshCoreConnector connector, bool autoAddChat, bool autoAddRepeater, @@ -1524,7 +1382,7 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { const SizedBox(height: 8), Text( l10n.settings_telemetryPerContactHint, - style: Theme.of(context).textTheme.bodySmall, + style: Theme.of(context).textTheme.bodyMedium, ), ], ), @@ -1537,22 +1395,37 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { TextButton( onPressed: () async { Navigator.pop(dialogContext); - await connector.setTelemetryModeBase( - telemetryMode, - telemetryLocMode, - telemetryEnvMode, - advertLocPolicy ? 1 : 0, - multiAcks, - ); - await settingsService.setAutoSendZeroHopAdvertOnGpsUpdate( - autoZeroHopAdvertOnGpsUpdate, - ); - await connector.refreshDeviceInfo(); - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.settings_telemetryModeUpdated), - ); + if (!connector.isConnected) { + showDismissibleSnackBar( + context, + content: Text(l10n.settings_notConnectedError), + ); + return; + } + try { + await connector.setTelemetryModeBase( + telemetryMode, + telemetryLocMode, + telemetryEnvMode, + advertLocPolicy ? 1 : 0, + multiAcks, + ); + await settingsService.setAutoSendZeroHopAdvertOnGpsUpdate( + autoZeroHopAdvertOnGpsUpdate, + ); + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_telemetryModeUpdated), + ); + } catch (e) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + } }, child: Text(l10n.common_save), ), @@ -1562,669 +1435,298 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { ); } -class _RadioSettingsDialog extends StatefulWidget { - final MeshCoreConnector connector; +/// Node-name editor. Owns (and disposes) its controller; pops with the +/// trimmed name on Save, or null on Cancel. +class _NodeNameDialog extends StatefulWidget { + final String initialName; - const _RadioSettingsDialog({required this.connector}); + const _NodeNameDialog({required this.initialName}); @override - State<_RadioSettingsDialog> createState() => _RadioSettingsDialogState(); + State<_NodeNameDialog> createState() => _NodeNameDialogState(); } -class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { - final _frequencyController = TextEditingController(); - LoRaBandwidth _bandwidth = LoRaBandwidth.bw125; - LoRaSpreadingFactor _spreadingFactor = LoRaSpreadingFactor.sf7; - LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5; - final _txPowerController = TextEditingController(text: '20'); - bool _clientRepeat = false; - int? _selectedPresetIndex; - _RadioSettingsSnapshot? _lastNonRepeatSnapshot; - String? _frequencyError; - String? _txPowerError; - - AppDebugLogService get _appLog => - Provider.of(context, listen: false); - - @override - void initState() { - super.initState(); - - // Populate with current settings if available - if (widget.connector.currentFreqHz != null) { - _frequencyController.text = (widget.connector.currentFreqHz! / 1000.0) - .toStringAsFixed(3); - } else { - _frequencyController.text = '915.0'; - } - - if (widget.connector.currentBwHz != null) { - // Find matching bandwidth enum - final bwValue = widget.connector.currentBwHz!; - for (var bw in LoRaBandwidth.values) { - if (bw.hz == bwValue) { - _bandwidth = bw; - break; - } - } - } - - if (widget.connector.currentSf != null) { - // Find matching spreading factor enum - final sfValue = widget.connector.currentSf!; - for (var sf in LoRaSpreadingFactor.values) { - if (sf.value == sfValue) { - _spreadingFactor = sf; - break; - } - } - } - - if (widget.connector.currentCr != null) { - // Find matching coding rate enum - final crValue = _toUiCodingRate(widget.connector.currentCr!); - for (var cr in LoRaCodingRate.values) { - if (cr.value == crValue) { - _codingRate = cr; - break; - } - } - } - - if (widget.connector.currentTxPower != null) { - _txPowerController.text = widget.connector.currentTxPower.toString(); - } - - _clientRepeat = widget.connector.clientRepeat ?? false; - _selectedPresetIndex = _findMatchingPresetIndex(); - if (_clientRepeat) { - _lastNonRepeatSnapshot = - _sessionRememberedNonRepeatSnapshot() ?? - _inferNonRepeatSnapshotForRepeatEnabled(); - _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( - _lastNonRepeatSnapshot!, - ); - } else { - _lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection(); - } - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) return; - _logRadioSettingsState('Dialog initialized'); - }); - } +class _NodeNameDialogState extends State<_NodeNameDialog> { + late final TextEditingController _controller = TextEditingController( + text: widget.initialName, + ); @override void dispose() { - _frequencyController.dispose(); - _txPowerController.dispose(); + _controller.dispose(); super.dispose(); } - void _applyPreset(int index) { - setState(() { - _applyPresetState(index); - }); - _logRadioSettingsState( - 'Applied preset ${RadioSettings.presets[index].$1} (#$index)', - ); - } - - int? _findMatchingPresetIndex() { - return _findMatchingPresetIndexForSnapshot(_currentSnapshot()); - } - - int? _findMatchingPresetIndexForSnapshot(_RadioSettingsSnapshot snapshot) { - for (final i in _visiblePresetIndexes()) { - final preset = RadioSettings.presets[i].$2; - if (preset.frequencyHz == snapshot.frequencyHz && - preset.bandwidth == snapshot.bandwidth && - preset.spreadingFactor == snapshot.spreadingFactor && - preset.codingRate == snapshot.codingRate) { - return i; - } - } - return null; - } - - Iterable _visiblePresetIndexes() sync* { - for (var i = 0; i < RadioSettings.presets.length; i++) { - if (_isOffGridPresetIndex(i)) { - continue; - } - yield i; - } - } - - _RadioSettingsSnapshot _currentSnapshot() { - final frequencyMHz = double.tryParse(_frequencyController.text) ?? 915.0; - final txPowerDbm = int.tryParse(_txPowerController.text) ?? 20; - return _RadioSettingsSnapshot( - frequencyMHz: frequencyMHz, - bandwidth: _bandwidth, - spreadingFactor: _spreadingFactor, - codingRate: _codingRate, - txPowerDbm: txPowerDbm, - ); - } - - bool _isOffGridPresetIndex(int? index) { - if (index == null) return false; - return RadioSettings.presets[index].$1.startsWith('Off-Grid '); - } - - double _offGridFrequencyForBaseFrequency(double baseFrequencyMHz) { - final baseKHz = (baseFrequencyMHz * 1000).round(); - final ranges = widget.connector.allowedRepeatFreqRanges; - final candidates = ranges == null || ranges.isEmpty - ? _defaultRepeatFreqsKHz - : {for (final r in ranges) baseKHz.clamp(r.lowKHz, r.highKHz)}; - final closestKHz = candidates.reduce( - (a, b) => (a - baseKHz).abs() <= (b - baseKHz).abs() ? a : b, - ); - return closestKHz / 1000.0; - } - - double _normalFrequencyForBand(double frequencyMHz) { - if (frequencyMHz < 500) return 433.650; - if (frequencyMHz < 900) return 869.432; - return 915.8; - } - - _RadioSettingsSnapshot _fallbackNonRepeatSnapshot( - double currentFrequencyMHz, - ) { - return _RadioSettingsSnapshot( - frequencyMHz: _normalFrequencyForBand(currentFrequencyMHz), - bandwidth: _bandwidth, - spreadingFactor: _spreadingFactor, - codingRate: _codingRate, - txPowerDbm: int.tryParse(_txPowerController.text) ?? 20, - ); - } - - _RadioSettingsSnapshot _nonRepeatSnapshotForCurrentSelection() { - final current = _currentSnapshot(); - if (!_isOffGridPresetIndex(_selectedPresetIndex)) { - return current; - } - return _fallbackNonRepeatSnapshot(current.frequencyMHz); - } - - _RadioSettingsSnapshot? _sessionRememberedNonRepeatSnapshot() { - final snapshot = widget.connector.rememberedNonRepeatRadioState; - if (snapshot == null) return null; - return _RadioSettingsSnapshot.fromMeshCoreSnapshot(snapshot); - } - - _RadioSettingsSnapshot _inferNonRepeatSnapshotForRepeatEnabled() { - final current = _currentSnapshot(); - for (final i in _visiblePresetIndexes()) { - final preset = RadioSettings.presets[i].$2; - final offGridFreqHz = - (_offGridFrequencyForBaseFrequency(preset.frequencyMHz) * 1000) - .round(); - if (offGridFreqHz == current.frequencyHz && - preset.bandwidth == current.bandwidth && - preset.spreadingFactor == current.spreadingFactor && - preset.codingRate == current.codingRate) { - return _RadioSettingsSnapshot( - frequencyMHz: preset.frequencyMHz, - bandwidth: preset.bandwidth, - spreadingFactor: preset.spreadingFactor, - codingRate: preset.codingRate, - txPowerDbm: current.txPowerDbm, - ); - } - } - return _fallbackNonRepeatSnapshot(current.frequencyMHz); - } - - void _applySnapshot(_RadioSettingsSnapshot snapshot) { - _frequencyController.text = snapshot.frequencyMHz.toStringAsFixed(3); - _bandwidth = snapshot.bandwidth; - _spreadingFactor = snapshot.spreadingFactor; - _codingRate = snapshot.codingRate; - _txPowerController.text = snapshot.txPowerDbm.toString(); - } - - void _applyPresetState(int index) { - final preset = RadioSettings.presets[index].$2; - final baseSnapshot = _RadioSettingsSnapshot( - frequencyMHz: preset.frequencyMHz, - bandwidth: preset.bandwidth, - spreadingFactor: preset.spreadingFactor, - codingRate: preset.codingRate, - txPowerDbm: preset.txPowerDbm, - ); - final frequencyMHz = _clientRepeat - ? _offGridFrequencyForBaseFrequency(baseSnapshot.frequencyMHz) - : baseSnapshot.frequencyMHz; - _frequencyController.text = frequencyMHz.toString(); - _bandwidth = preset.bandwidth; - _spreadingFactor = preset.spreadingFactor; - _codingRate = preset.codingRate; - _txPowerController.text = preset.txPowerDbm.toString(); - _selectedPresetIndex = index; - _lastNonRepeatSnapshot = baseSnapshot; - } - - void _syncPresetSelection() { - final previousPresetIndex = _selectedPresetIndex; - final previousLastNonRepeat = _lastNonRepeatSnapshot; - if (_clientRepeat) { - final baseSnapshot = - previousLastNonRepeat ?? _inferNonRepeatSnapshotForRepeatEnabled(); - if (_bandwidth != baseSnapshot.bandwidth || - _spreadingFactor != baseSnapshot.spreadingFactor || - _codingRate != baseSnapshot.codingRate || - (int.tryParse(_txPowerController.text) ?? 20) != - baseSnapshot.txPowerDbm) { - _lastNonRepeatSnapshot = _RadioSettingsSnapshot( - frequencyMHz: baseSnapshot.frequencyMHz, - bandwidth: _bandwidth, - spreadingFactor: _spreadingFactor, - codingRate: _codingRate, - txPowerDbm: int.tryParse(_txPowerController.text) ?? 20, - ); - } - _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( - _lastNonRepeatSnapshot ?? baseSnapshot, - ); - if (previousPresetIndex != _selectedPresetIndex || - previousLastNonRepeat != _lastNonRepeatSnapshot) { - _logRadioSettingsState( - 'Preset match updated while repeat enabled: ${_presetLabel(previousPresetIndex)} -> ${_presetLabel(_selectedPresetIndex)}', - ); - } - return; - } - _lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection(); - _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( - _lastNonRepeatSnapshot!, - ); - if (previousPresetIndex != _selectedPresetIndex || - previousLastNonRepeat != _lastNonRepeatSnapshot) { - _logRadioSettingsState( - 'Preset sync updated state from ${_presetLabel(previousPresetIndex)} to ${_presetLabel(_selectedPresetIndex)}', - ); - } - } - - void _handleManualSettingsChanged(String source) { - _logRadioSettingsState('Manual settings edit: $source'); - setState(() { - _validateFields(); - _syncPresetSelection(); - }); - } - - void _validateFields() { - final l10n = context.l10n; - final freqMHz = double.tryParse(_frequencyController.text); - _frequencyError = (freqMHz == null || freqMHz < 150 || freqMHz > 2500) - ? l10n.settings_frequencyInvalid - : null; - - final maxTxPower = widget.connector.maxTxPower ?? 22; - final txPower = int.tryParse(_txPowerController.text); - _txPowerError = - (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) - ? '${l10n.settings_txPowerInvalid} ($_minTxPowerDbm-$maxTxPower dBm)' - : null; - } - - void _handleClientRepeatChanged(bool enabled) { - _logRadioSettingsState( - 'Off-grid repeat toggle requested: $_clientRepeat -> $enabled', - ); - setState(() { - final currentSnapshot = _currentSnapshot(); - if (enabled) { - if (!_clientRepeat) { - _syncPresetSelection(); - } - final baseSnapshot = _lastNonRepeatSnapshot ?? currentSnapshot; - _clientRepeat = true; - _frequencyController.text = _offGridFrequencyForBaseFrequency( - baseSnapshot.frequencyMHz, - ).toStringAsFixed(3); - return; - } - - _clientRepeat = false; - _applySnapshot( - _lastNonRepeatSnapshot ?? - _fallbackNonRepeatSnapshot(currentSnapshot.frequencyMHz), - ); - _syncPresetSelection(); - }); - _logRadioSettingsState('Off-grid repeat toggle applied'); - } - - Future _saveSettings() async { - final l10n = context.l10n; - final freqMHz = double.tryParse(_frequencyController.text); - final txPower = int.tryParse(_txPowerController.text); - - if (freqMHz == null || freqMHz < 150 || freqMHz > 2500) { - showDismissibleSnackBar( - context, - content: Text(l10n.settings_frequencyInvalid), - ); - return; - } - - final maxTxPower = widget.connector.maxTxPower ?? 22; - if (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) { - showDismissibleSnackBar( - context, - content: Text( - '${l10n.settings_txPowerInvalid} ($_minTxPowerDbm-$maxTxPower dBm)', - ), - ); - return; - } - - final freqHz = (freqMHz * 1000).round(); - final bwHz = _bandwidth.hz; - final sf = _spreadingFactor.value; - final cr = _codingRate.value; - - // if the client repeat isnt null then we know its supported - //otherwise we leave it out of the frame to avoid accidentally enabling - final knownRepeat = widget.connector.clientRepeat != null; - - if (knownRepeat) { - if (_clientRepeat && !_isAllowedRepeatFreqKHz(widget.connector, freqHz)) { - showDismissibleSnackBar( - context, - content: Text(l10n.settings_clientRepeatFreqWarning), - ); - return; - } - } - - try { - _logRadioSettingsState('Saving radio settings'); - final accepted = await widget.connector.setRadioParams( - freqHz, - bwHz, - sf, - cr, - clientRepeat: knownRepeat ? _clientRepeat : null, - ); - if (!accepted) { - _logRadioSettingsState('Radio rejected requested settings'); - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.settings_radioSettingsNotApplied), - ); - return; - } - await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); - final selfInfo = widget.connector.receivedFrames - .firstWhere((f) => f.isNotEmpty && f[0] == respCodeSelfInfo) - .timeout(const Duration(seconds: 5)); - await widget.connector.refreshDeviceInfo(); - final applied = await selfInfo.then( - (_) => _deviceMatches( - freqHz: freqHz, - bwHz: bwHz, - sf: sf, - cr: cr, - txPower: txPower, - clientRepeat: knownRepeat ? _clientRepeat : null, - ), - onError: (_) => true, - ); - if (!applied) { - _logRadioSettingsState('Radio did not apply requested settings'); - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.settings_radioSettingsNotApplied), - ); - return; - } - final rememberedSnapshot = _clientRepeat - ? _lastNonRepeatSnapshot - : _currentSnapshot(); - if (rememberedSnapshot != null) { - widget.connector.rememberNonRepeatRadioState( - rememberedSnapshot.toMeshCoreSnapshot(), - ); - } - - if (!mounted) return; - _logRadioSettingsState('Radio settings saved successfully'); - showDismissibleSnackBar( - context, - content: Text(l10n.settings_radioSettingsUpdated), - ); - } catch (e) { - _appLog.warn('Radio settings save failed: $e', tag: 'RadioSettings'); - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.settings_error(e.toString())), - ); - } - if (!mounted) return; - Navigator.pop(context); - } - - bool _deviceMatches({ - required int freqHz, - required int bwHz, - required int sf, - required int cr, - required int txPower, - required bool? clientRepeat, - }) { - final c = widget.connector; - // Firmware stores freq/bw as float MHz/kHz, so allow 1 unit of rounding. - return c.currentFreqHz != null && - (c.currentFreqHz! - freqHz).abs() <= 1 && - c.currentBwHz != null && - (c.currentBwHz! - bwHz).abs() <= 1 && - c.currentSf == sf && - c.currentCr != null && - _toUiCodingRate(c.currentCr!) == cr && - c.currentTxPower == txPower && - (clientRepeat == null || c.clientRepeat == clientRepeat); - } - - String _presetLabel(int? index) { - if (index == null) { - return 'custom'; - } - return '${RadioSettings.presets[index].$1} (#$index)'; - } - - String _formatSnapshot(_RadioSettingsSnapshot? snapshot) { - if (snapshot == null) { - return 'null'; - } - return '${snapshot.frequencyMHz.toStringAsFixed(3)}MHz/' - '${snapshot.bandwidth.label}/' - '${snapshot.spreadingFactor.label}/' - '${snapshot.codingRate.label}/' - '${snapshot.txPowerDbm}dBm'; - } - - void _logRadioSettingsState(String message) { - if (!kDebugMode) return; - _appLog.info( - '$message | ' - 'freq=${_frequencyController.text}MHz ' - 'bw=${_bandwidth.label} ' - 'sf=${_spreadingFactor.label} ' - 'cr=${_codingRate.label} ' - 'tx=${_txPowerController.text}dBm ' - 'repeat=$_clientRepeat ' - 'preset=${_presetLabel(_selectedPresetIndex)} ' - 'lastNonRepeat=${_formatSnapshot(_lastNonRepeatSnapshot)}', - tag: 'RadioSettings', - ); - } - @override Widget build(BuildContext context) { final l10n = context.l10n; return AlertDialog( - title: Text(l10n.settings_radioSettings), + title: Text(l10n.settings_nodeName), + content: TextField( + controller: _controller, + decoration: InputDecoration( + hintText: l10n.settings_nodeNameHint, + border: const OutlineInputBorder(), + ), + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(maxRadioNameBytes), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final name = _controller.text.trim(); + return TextButton( + onPressed: name.isEmpty + ? null + : () => Navigator.pop(context, name), + child: Text(l10n.common_save), + ); + }, + ), + ], + ); + } +} + +/// What the location dialog asks the screen to apply. Null fields are left +/// unchanged on the device. +class _LocationEdit { + final bool? gpsEnabled; + final int? intervalSeconds; + final double? latitude; + final double? longitude; + final bool clearsLocation; + + const _LocationEdit({ + this.gpsEnabled, + this.intervalSeconds, + this.latitude, + this.longitude, + this.clearsLocation = false, + }); + + bool get hasChanges => + gpsEnabled != null || + intervalSeconds != null || + (latitude != null && longitude != null); +} + +/// Location / GPS editor. Owns (and disposes) its controllers and validates +/// every field before closing, reporting each error under the field it +/// belongs to. +class _LocationDialog extends StatefulWidget { + final double? latitude; + final double? longitude; + final bool hasGPS; + final bool initialGPSEnabled; + final int initialIntervalSeconds; + + const _LocationDialog({ + required this.latitude, + required this.longitude, + required this.hasGPS, + required this.initialGPSEnabled, + required this.initialIntervalSeconds, + }); + + @override + State<_LocationDialog> createState() => _LocationDialogState(); +} + +class _LocationDialogState extends State<_LocationDialog> { + late final TextEditingController _latController; + late final TextEditingController _lonController; + late final TextEditingController _intervalController; + late bool _isGPSEnabled = widget.initialGPSEnabled; + String? _latError; + String? _lonError; + String? _intervalError; + + /// Firmware stores "no location" as 0,0 (the default for a fresh node), so + /// that pair is shown as empty fields rather than a real coordinate. + bool get _hasLocation { + final lat = widget.latitude; + final lon = widget.longitude; + return lat != null && lon != null && !(lat == 0 && lon == 0); + } + + @override + void initState() { + super.initState(); + _latController = TextEditingController( + text: _hasLocation ? widget.latitude!.toStringAsFixed(6) : '', + ); + _lonController = TextEditingController( + text: _hasLocation ? widget.longitude!.toStringAsFixed(6) : '', + ); + _intervalController = TextEditingController( + text: widget.initialIntervalSeconds.toString(), + ); + } + + @override + void dispose() { + _latController.dispose(); + _lonController.dispose(); + _intervalController.dispose(); + super.dispose(); + } + + void _save() { + final l10n = context.l10n; + // Validate every field before closing so a typo doesn't discard the + // input or leave half the changes applied. + int? interval; + String? intervalError; + if (widget.hasGPS) { + final intervalText = _intervalController.text.trim(); + if (intervalText.isNotEmpty) { + interval = int.tryParse(intervalText); + if (interval == null || interval < 60 || interval >= 86400) { + intervalError = l10n.settings_locationIntervalInvalid; + } + } + } + + final latText = _latController.text.trim(); + final lonText = _lonController.text.trim(); + double? lat; + double? lon; + String? latError; + String? lonError; + var clearsLocation = false; + if (latText.isEmpty && lonText.isEmpty) { + // Clearing both fields removes the location. Companion firmware has no + // dedicated "clear" command: CMD_SET_ADVERT_LATLON with 0,0 restores + // the factory default, which firmware and this app treat as unset. + if (_hasLocation) { + lat = 0; + lon = 0; + clearsLocation = true; + } + } else { + // One empty field keeps the device's current value for that axis. + lat = latText.isNotEmpty + ? double.tryParse(latText) + : (_hasLocation ? widget.latitude : null); + lon = lonText.isNotEmpty + ? double.tryParse(lonText) + : (_hasLocation ? widget.longitude : null); + if (lat == null) { + latError = latText.isEmpty + ? l10n.settings_locationBothRequired + : l10n.settings_locationInvalid; + } else if (lat < -90 || lat > 90) { + latError = l10n.settings_locationInvalid; + } + if (lon == null) { + lonError = lonText.isEmpty + ? l10n.settings_locationBothRequired + : l10n.settings_locationInvalid; + } else if (lon < -180 || lon > 180) { + lonError = l10n.settings_locationInvalid; + } + } + + if (intervalError != null || latError != null || lonError != null) { + setState(() { + _intervalError = intervalError; + _latError = latError; + _lonError = lonError; + }); + return; + } + + Navigator.pop( + context, + _LocationEdit( + gpsEnabled: widget.hasGPS && _isGPSEnabled != widget.initialGPSEnabled + ? _isGPSEnabled + : null, + intervalSeconds: interval, + latitude: lat, + longitude: lon, + clearsLocation: clearsLocation, + ), + ); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + const coordinateKeyboard = TextInputType.numberWithOptions( + decimal: true, + signed: true, + ); + return AlertDialog( + title: Text(l10n.settings_location), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, children: [ - DropdownButtonFormField( - key: ValueKey(_selectedPresetIndex), - initialValue: _selectedPresetIndex ?? -1, - isExpanded: true, - decoration: InputDecoration( - labelText: l10n.settings_presets, - border: const OutlineInputBorder(), - ), - items: [ - if (_selectedPresetIndex == null) - DropdownMenuItem( - value: -1, - child: Text(l10n.settings_presetCustom), - ), - for (final i in _visiblePresetIndexes()) - DropdownMenuItem( - value: i, - child: Text( - RadioSettings.presets[i].$1, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: (index) { - if (index != null && index >= 0) { - _applyPreset(index); - } + TextField( + controller: _latController, + onChanged: (_) { + if (_latError != null) setState(() => _latError = null); }, + decoration: InputDecoration( + labelText: l10n.settings_latitude, + border: const OutlineInputBorder(), + errorText: _latError, + errorMaxLines: 2, + ), + keyboardType: coordinateKeyboard, ), const SizedBox(height: 16), TextField( - controller: _frequencyController, - onChanged: (_) => _handleManualSettingsChanged('frequency'), - decoration: InputDecoration( - labelText: l10n.settings_frequency, - border: const OutlineInputBorder(), - helperText: _clientRepeat - ? l10n.settings_clientRepeatFrequencyNote( - _frequencyController.text, - ) - : l10n.settings_frequencyHelper, - errorText: _frequencyError, - ), - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - ), - const SizedBox(height: 16), - DropdownButtonFormField( - initialValue: _bandwidth, - decoration: InputDecoration( - labelText: l10n.settings_bandwidth, - border: const OutlineInputBorder(), - ), - items: LoRaBandwidth.values - .map( - (bw) => DropdownMenuItem(value: bw, child: Text(bw.label)), - ) - .toList(), - onChanged: (value) { - if (value != null) { - setState(() { - _bandwidth = value; - _syncPresetSelection(); - }); - _logRadioSettingsState('Manual settings edit: bandwidth'); - } + controller: _lonController, + onChanged: (_) { + if (_lonError != null) setState(() => _lonError = null); }, - ), - const SizedBox(height: 16), - DropdownButtonFormField( - initialValue: _spreadingFactor, decoration: InputDecoration( - labelText: l10n.settings_spreadingFactor, + labelText: l10n.settings_longitude, border: const OutlineInputBorder(), + helperText: l10n.settings_locationClearHelper, + helperMaxLines: 2, + errorText: _lonError, + errorMaxLines: 2, ), - items: LoRaSpreadingFactor.values - .map( - (sf) => DropdownMenuItem(value: sf, child: Text(sf.label)), - ) - .toList(), - onChanged: (value) { - if (value != null) { - setState(() { - _spreadingFactor = value; - _syncPresetSelection(); - }); - _logRadioSettingsState( - 'Manual settings edit: spreading factor', - ); - } - }, + keyboardType: coordinateKeyboard, ), - const SizedBox(height: 16), - DropdownButtonFormField( - initialValue: _codingRate, - decoration: InputDecoration( - labelText: l10n.settings_codingRate, - border: const OutlineInputBorder(), - ), - items: LoRaCodingRate.values - .map( - (cr) => DropdownMenuItem(value: cr, child: Text(cr.label)), - ) - .toList(), - onChanged: (value) { - if (value != null) { - setState(() { - _codingRate = value; - _syncPresetSelection(); - }); - _logRadioSettingsState('Manual settings edit: coding rate'); - } - }, - ), - const SizedBox(height: 16), - TextField( - controller: _txPowerController, - onChanged: (_) => _handleManualSettingsChanged('tx power'), - decoration: InputDecoration( - labelText: l10n.settings_txPower, - border: const OutlineInputBorder(), - helperText: l10n.settings_txPowerRangeHelper( - _minTxPowerDbm, - widget.connector.maxTxPower ?? 22, - ), - errorText: _txPowerError, - ), - keyboardType: TextInputType.number, - ), - if (widget.connector.clientRepeat != null) ...[ + if (widget.hasGPS) ...[ const SizedBox(height: 16), - SwitchListTile( - title: Text(l10n.settings_clientRepeat), - subtitle: Text(l10n.settings_clientRepeatSubtitle), - value: _clientRepeat, - onChanged: _handleClientRepeatChanged, - contentPadding: EdgeInsets.zero, + TextField( + controller: _intervalController, + onChanged: (_) { + if (_intervalError != null) { + setState(() => _intervalError = null); + } + }, + decoration: InputDecoration( + labelText: l10n.settings_locationIntervalSec, + border: const OutlineInputBorder(), + errorText: _intervalError, + ), + keyboardType: const TextInputType.numberWithOptions( + decimal: false, + signed: false, + ), + ), + const SizedBox(height: 16), + FeatureToggleRow( + title: l10n.settings_locationGPSEnable, + subtitle: l10n.settings_locationGPSEnableSubtitle, + value: _isGPSEnabled, + // Applied on Save so Cancel leaves the device untouched. + onChanged: (value) => setState(() => _isGPSEnabled = value), ), ], - const SizedBox(height: 16), - Text( - l10n.settings_radioMatchWarning, - style: Theme.of(context).textTheme.bodySmall, - ), ], ), ), @@ -2233,85 +1735,8 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { onPressed: () => Navigator.pop(context), child: Text(l10n.common_cancel), ), - FilledButton( - onPressed: (_frequencyError != null || _txPowerError != null) - ? null - : _saveSettings, - child: Text(l10n.common_save), - ), + TextButton(onPressed: _save, child: Text(l10n.common_save)), ], ); } } - -class _RadioSettingsSnapshot { - final double frequencyMHz; - final LoRaBandwidth bandwidth; - final LoRaSpreadingFactor spreadingFactor; - final LoRaCodingRate codingRate; - final int txPowerDbm; - - const _RadioSettingsSnapshot({ - required this.frequencyMHz, - required this.bandwidth, - required this.spreadingFactor, - required this.codingRate, - required this.txPowerDbm, - }); - - /// Frequency in integer Hz — avoids floating-point comparison issues. - int get frequencyHz => (frequencyMHz * 1000).round(); - - /// Convert from the connector's raw-int snapshot to UI-enum snapshot. - static _RadioSettingsSnapshot? fromMeshCoreSnapshot( - MeshCoreRadioStateSnapshot snapshot, - ) { - final bw = LoRaBandwidth.values - .where((b) => b.hz == snapshot.bwHz) - .firstOrNull; - final sf = LoRaSpreadingFactor.values - .where((s) => s.value == snapshot.sf) - .firstOrNull; - final cr = LoRaCodingRate.values - .where((c) => c.value == _toUiCodingRate(snapshot.cr)) - .firstOrNull; - if (bw == null || sf == null || cr == null) return null; - return _RadioSettingsSnapshot( - frequencyMHz: snapshot.freqHz / 1000.0, - bandwidth: bw, - spreadingFactor: sf, - codingRate: cr, - txPowerDbm: snapshot.txPowerDbm, - ); - } - - /// Convert back to the connector's raw-int snapshot. - MeshCoreRadioStateSnapshot toMeshCoreSnapshot() { - return MeshCoreRadioStateSnapshot( - freqHz: frequencyHz, - bwHz: bandwidth.hz, - sf: spreadingFactor.value, - cr: codingRate.value, - txPowerDbm: txPowerDbm, - ); - } - - @override - bool operator ==(Object other) { - return other is _RadioSettingsSnapshot && - frequencyHz == other.frequencyHz && - bandwidth == other.bandwidth && - spreadingFactor == other.spreadingFactor && - codingRate == other.codingRate && - txPowerDbm == other.txPowerDbm; - } - - @override - int get hashCode => Object.hash( - frequencyHz, - bandwidth, - spreadingFactor, - codingRate, - txPowerDbm, - ); -} diff --git a/lib/screens/tcp_screen.dart b/lib/screens/tcp_screen.dart index 85ac929f..8055a6f6 100644 --- a/lib/screens/tcp_screen.dart +++ b/lib/screens/tcp_screen.dart @@ -28,6 +28,8 @@ class _TcpScreenState extends State { late final MeshCoreConnector _connector; late final VoidCallback _connectionListener; bool _navigatedToChannels = false; + String? _hostError; + String? _portError; @override void initState() { @@ -47,8 +49,12 @@ class _TcpScreenState extends State { if (_connector.state == MeshCoreConnectionState.disconnected) { _navigatedToChannels = false; } + // Only navigate while this route is on top; otherwise a reconnect + // would replace whatever screen the user has pushed above it. + final isCurrentRoute = ModalRoute.of(context)?.isCurrent ?? true; if (_connector.state == MeshCoreConnectionState.connected && _connector.isTcpTransportConnected && + isCurrentRoute && !_navigatedToChannels) { context.read().setTcpServerAddress( _hostController.text, @@ -122,7 +128,7 @@ class _TcpScreenState extends State { _buildTransportLinks(context), // Connection form - const SectionHeader('TCP / IP'), + SectionHeader(context.l10n.tcpSectionTitle), MeshCard( padding: const EdgeInsets.all(16), child: Column( @@ -133,9 +139,16 @@ class _TcpScreenState extends State { decoration: InputDecoration( labelText: context.l10n.tcpHostLabel, hintText: context.l10n.tcpHostHint, + errorText: _hostError, + errorMaxLines: 3, ), enabled: !isConnecting, keyboardType: TextInputType.url, + onChanged: (_) { + if (_hostError != null) { + setState(() => _hostError = null); + } + }, ), const SizedBox(height: 12), TextField( @@ -143,9 +156,16 @@ class _TcpScreenState extends State { decoration: InputDecoration( labelText: context.l10n.tcpPortLabel, hintText: context.l10n.tcpPortHint, + errorText: _portError, + errorMaxLines: 3, ), enabled: !isConnecting, keyboardType: TextInputType.number, + onChanged: (_) { + if (_portError != null) { + setState(() => _portError = null); + } + }, ), const SizedBox(height: 16), FilledButton.icon( @@ -178,7 +198,7 @@ class _TcpScreenState extends State { // Last used endpoint if (connector.activeTcpEndpoint != null && connector.isTcpTransportConnected) ...[ - const SectionHeader('CONNECTED TO'), + SectionHeader(context.l10n.tcpConnectedToHeader), MeshCard( padding: const EdgeInsets.symmetric( horizontal: 14, @@ -188,7 +208,7 @@ class _TcpScreenState extends State { children: [ Icon( Icons.lan, - size: 16, + size: 20, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 10), @@ -196,7 +216,7 @@ class _TcpScreenState extends State { child: Text( connector.activeTcpEndpoint!, style: MeshTheme.mono( - fontSize: 13, + fontSize: 15, color: Theme.of(context).colorScheme.onSurface, ), maxLines: 1, @@ -283,12 +303,15 @@ class _TcpScreenState extends State { final host = _hostController.text.trim(); final parsedPort = int.tryParse(_portController.text.trim()); - if (host.isEmpty) { - _showError(context.l10n.tcpErrorHostRequired); - return; - } - if (parsedPort == null || parsedPort < 1 || parsedPort > 65535) { - _showError(context.l10n.tcpErrorPortInvalid); + final hostError = host.isEmpty ? context.l10n.tcpErrorHostRequired : null; + final portError = parsedPort == null || parsedPort < 1 || parsedPort > 65535 + ? context.l10n.tcpErrorPortInvalid + : null; + setState(() { + _hostError = hostError; + _portError = portError; + }); + if (hostError != null || portError != null || parsedPort == null) { return; } diff --git a/lib/screens/telemetry_screen.dart b/lib/screens/telemetry_screen.dart index 76cff5be..b6f085e8 100644 --- a/lib/screens/telemetry_screen.dart +++ b/lib/screens/telemetry_screen.dart @@ -135,27 +135,17 @@ class _TelemetryScreenState extends State { _tripTime = reader.readUInt32LE(); _statusTimeout?.cancel(); final isAutoRefreshRequest = _activeTelemetryRequestIsAutoRefresh; - _statusTimeout = Timer(Duration(milliseconds: _tripTime), () { - if (!mounted) return; - setState(() { - _isLoading = false; - _isLoaded = false; - if (isAutoRefreshRequest && _isAutoRefreshEnabled) { - _autoRefreshLastAttemptFailed = true; - } - }); - if (!isAutoRefreshRequest) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.telemetry_requestTimeout), - backgroundColor: Theme.of(context).colorScheme.error, - ); - } - if (isAutoRefreshRequest && _isAutoRefreshEnabled) { - _scheduleNextAutoRefreshAttempt(); - } - _recordTelemetryResult(false); - }); + _statusTimeout = Timer( + Duration(milliseconds: _tripTime), + () => _handleRequestFailed(isAutoRefreshRequest), + ); + } + + // The radio rejected the send: fail now instead of waiting forever. + if (cmd == respCodeErr && _awaitingSent) { + _awaitingSent = false; + _statusTimeout?.cancel(); + _handleRequestFailed(_activeTelemetryRequestIsAutoRefresh); } // Check if it's a binary response @@ -183,6 +173,30 @@ class _TelemetryScreenState extends State { }); } + /// Ends a telemetry request that timed out or was rejected by the radio. + void _handleRequestFailed(bool isAutoRefreshRequest) { + if (!mounted) return; + setState(() { + _isLoading = false; + _isLoaded = false; + if (isAutoRefreshRequest && _isAutoRefreshEnabled) { + _autoRefreshLastAttemptFailed = true; + } + _activeTelemetryRequestIsAutoRefresh = false; + }); + if (!isAutoRefreshRequest) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.telemetry_requestTimeout), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } + if (isAutoRefreshRequest && _isAutoRefreshEnabled) { + _scheduleNextAutoRefreshAttempt(); + } + _recordTelemetryResult(false); + } + void _handleTelemetryResponse(Uint8List frame) { final parsedTelemetry = CayenneLpp.parseByChannel(frame); final batteryMv = _extractTelemetryBatteryMillivolts(parsedTelemetry); @@ -239,28 +253,10 @@ class _TelemetryScreenState extends State { frame = buildSendTelemetryReq(null); final isAutoRefreshRequest = _activeTelemetryRequestIsAutoRefresh; _statusTimeout?.cancel(); - _statusTimeout = Timer(const Duration(seconds: 5), () { - if (!mounted) return; - setState(() { - _isLoading = false; - _isLoaded = false; - if (isAutoRefreshRequest && _isAutoRefreshEnabled) { - _autoRefreshLastAttemptFailed = true; - } - _activeTelemetryRequestIsAutoRefresh = false; - }); - if (!isAutoRefreshRequest) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.telemetry_requestTimeout), - backgroundColor: Theme.of(context).colorScheme.error, - ); - } - if (isAutoRefreshRequest && _isAutoRefreshEnabled) { - _scheduleNextAutoRefreshAttempt(); - } - _recordTelemetryResult(false); - }); + _statusTimeout = Timer( + const Duration(seconds: 5), + () => _handleRequestFailed(isAutoRefreshRequest), + ); } else { final selection = await connector.preparePathForContactSend( _resolveContact(connector), @@ -446,7 +442,26 @@ class _TelemetryScreenState extends State { child: ListView( padding: const EdgeInsets.all(16), children: [ - if (!_isLoaded && + if (_isLoading && + !_hasData && + (_parsedTelemetry == null || _parsedTelemetry!.isEmpty)) + Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Column( + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 12), + Text( + l10n.telemetry_loading, + style: TextStyle( + fontSize: 16, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ) + else if (!_isLoaded && !_hasData && (_parsedTelemetry == null || _parsedTelemetry!.isEmpty)) Center( @@ -506,7 +521,7 @@ class _TelemetryScreenState extends State { bool isImperialUnits, ) { if (entry.key == 'gps') { - return _buildGpsInfo(entry.value); + return _buildGpsInfo(entry.value, isImperialUnits); } final display = _formatTelemetryField( @@ -573,7 +588,7 @@ class _TelemetryScreenState extends State { case 'altitude': return _TelemetryFieldDisplay( l10n.telemetry_altitudeLabel, - l10n.telemetry_altitudeValue(text), + _lengthText(value, isImperialUnits, altitude: true), ); case 'voltage': return _TelemetryFieldDisplay( @@ -612,7 +627,7 @@ class _TelemetryScreenState extends State { case 'distance': return _TelemetryFieldDisplay( l10n.telemetry_distanceLabel, - l10n.telemetry_distanceValue(text), + _lengthText(value, isImperialUnits, altitude: false), ); case 'energy': return _TelemetryFieldDisplay( @@ -863,7 +878,7 @@ class _TelemetryScreenState extends State { return value; } - Widget _buildGpsInfo(dynamic value) { + Widget _buildGpsInfo(dynamic value, bool isImperialUnits) { final latitude = _readGpsValue(value, 'latitude'); final longitude = _readGpsValue(value, 'longitude'); final altitude = _readGpsValue(value, 'altitude'); @@ -872,7 +887,13 @@ class _TelemetryScreenState extends State { ? [ latitude!.toStringAsFixed(5), longitude!.toStringAsFixed(5), - if (altitude != null) '${altitude.toStringAsFixed(1)} m', + if (altitude != null) + _lengthText( + altitude, + isImperialUnits, + altitude: true, + metricText: altitude.toStringAsFixed(1), + ), ].join(', ') : value.toString(); @@ -927,7 +948,7 @@ class _TelemetryScreenState extends State { final x = _telemetryValueText(value['x']); final y = _telemetryValueText(value['y']); final z = _telemetryValueText(value['z']); - return 'X: $x, Y: $y, Z: $z'; + return context.l10n.telemetry_axisValue(x, y, z); } String _telemetryColorText(dynamic value) { @@ -935,7 +956,7 @@ class _TelemetryScreenState extends State { final red = _telemetryValueText(value['red']); final green = _telemetryValueText(value['green']); final blue = _telemetryValueText(value['blue']); - return 'R: $red, G: $green, B: $blue'; + return context.l10n.telemetry_colourValue(red, green, blue); } String _telemetryMapText(dynamic value) { @@ -1019,6 +1040,32 @@ class _TelemetryScreenState extends State { ); } + /// Formats a length reported in meters, converting to feet in imperial mode. + String _lengthText( + dynamic meters, + bool isImperialUnits, { + required bool altitude, + String? metricText, + }) { + final l10n = context.l10n; + if (meters is! num) { + final text = _telemetryValueText(meters); + return altitude + ? l10n.telemetry_altitudeValue(text) + : l10n.telemetry_distanceValue(text); + } + if (isImperialUnits) { + final feet = (meters * 3.28084).toStringAsFixed(1); + return altitude + ? l10n.telemetry_altitudeValueFeet(feet) + : l10n.telemetry_distanceValueFeet(feet); + } + final text = metricText ?? _telemetryValueText(meters); + return altitude + ? l10n.telemetry_altitudeValue(text) + : l10n.telemetry_distanceValue(text); + } + String _temperatureText(double? tempC, bool isImperialUnits) { final l10n = context.l10n; if (tempC == null) return l10n.common_notAvailable; diff --git a/lib/screens/usb_screen.dart b/lib/screens/usb_screen.dart index 9bd5a5ca..68d01d5a 100644 --- a/lib/screens/usb_screen.dart +++ b/lib/screens/usb_screen.dart @@ -24,7 +24,7 @@ class UsbScreen extends StatefulWidget { State createState() => _UsbScreenState(); } -class _UsbScreenState extends State { +class _UsbScreenState extends State with WidgetsBindingObserver { final List _ports = []; bool _isLoadingPorts = true; bool _navigatedToChannels = false; @@ -36,6 +36,13 @@ class _UsbScreenState extends State { bool get _supportsHotPlug => PlatformInfo.isWindows || PlatformInfo.isLinux || PlatformInfo.isMacOS; + /// Web Serial lists a synthetic "request a port" entry plus ports the user + /// already authorised; the request entry opens the browser's port picker. + static const String _webRequestPortName = 'web:request'; + + bool _isWebRequestEntry(String port) => + normalizeUsbPortName(port) == _webRequestPortName; + @override void initState() { super.initState(); @@ -55,9 +62,25 @@ class _UsbScreenState extends State { } }; _connector.addListener(_connectionListener); + WidgetsBinding.instance.addObserver(this); _startHotPlugTimer(); } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // Polling the serial ports in the background wastes power; stop while + // the app isn't in the foreground and resume when it returns. + if (state == AppLifecycleState.resumed) { + if (_supportsHotPlug && _hotPlugTimer == null) { + _startHotPlugTimer(); + unawaited(_pollHotPlug()); + } + } else { + _hotPlugTimer?.cancel(); + _hotPlugTimer = null; + } + } + @override void didChangeDependencies() { super.didChangeDependencies(); @@ -71,6 +94,7 @@ class _UsbScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _hotPlugTimer?.cancel(); _hotPlugTimer = null; _connector.removeListener(_connectionListener); @@ -125,7 +149,8 @@ class _UsbScreenState extends State { }, ), ), - bottomNavigationBar: _supportsHotPlug + // Desktop hot-plugs automatically; web uses the port-picker button. + bottomNavigationBar: _supportsHotPlug || PlatformInfo.isWeb ? null : SafeArea( top: false, @@ -227,6 +252,14 @@ class _UsbScreenState extends State { Widget _buildPortList(BuildContext context, MeshCoreConnector connector) { final l10n = context.l10n; + final isConnecting = + connector.state == MeshCoreConnectionState.connecting && + connector.activeTransport == MeshCoreTransportType.usb; + + if (PlatformInfo.isWeb) { + return _buildWebPortPicker(context, connector, isConnecting); + } + if (_isLoadingPorts) { return EmptyState(icon: Icons.usb, title: l10n.usbStatus_searching); } @@ -235,15 +268,67 @@ class _UsbScreenState extends State { return EmptyState(icon: Icons.usb, title: l10n.usbScreenEmptyState); } - final isConnecting = - connector.state == MeshCoreConnectionState.connecting && - connector.activeTransport == MeshCoreTransportType.usb; + return _buildPortListView(context, _ports, isConnecting); + } + /// Web: one prominent button opens the browser's serial-port picker; + /// ports the user already authorised are listed below it for reconnects. + Widget _buildWebPortPicker( + BuildContext context, + MeshCoreConnector connector, + bool isConnecting, + ) { + final authorizedPorts = _ports + .where((port) => !_isWebRequestEntry(port)) + .toList(); + final canConnect = + !isConnecting && + connector.state == MeshCoreConnectionState.disconnected; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: FilledButton.icon( + key: const Key('usb_choose_serial_port_button'), + style: FilledButton.styleFrom(minimumSize: const Size(0, 56)), + onPressed: canConnect + ? () { + HapticFeedback.selectionClick(); + _connectPort(_webRequestPortName); + } + : null, + icon: isConnecting + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.usb), + label: Text( + context.l10n.usbChooseSerialPort, + style: const TextStyle(fontSize: 16), + ), + ), + ), + if (authorizedPorts.isNotEmpty) + Expanded( + child: _buildPortListView(context, authorizedPorts, isConnecting), + ), + ], + ); + } + + Widget _buildPortListView( + BuildContext context, + List ports, + bool isConnecting, + ) { return ListView.builder( padding: const EdgeInsets.only(bottom: 32), - itemCount: _ports.length, + itemCount: ports.length, itemBuilder: (context, index) { - final port = _ports[index]; + final port = ports[index]; final displayName = friendlyUsbPortName(port); final rawName = normalizeUsbPortName(port); final showRawName = @@ -279,7 +364,7 @@ class _UsbScreenState extends State { ? Text( rawName, style: MeshTheme.mono( - fontSize: 11, + fontSize: 13, color: Theme.of(context).colorScheme.onSurfaceVariant, ), maxLines: 1, @@ -288,7 +373,7 @@ class _UsbScreenState extends State { : null, trailing: Icon( Icons.chevron_right, - size: 18, + size: 24, color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), @@ -309,6 +394,8 @@ class _UsbScreenState extends State { Future _pollHotPlug() async { if (_isLoadingPorts) return; if (!mounted) return; + // Skip while another screen covers this one. + if (!(ModalRoute.of(context)?.isCurrent ?? true)) return; // Don't poll while connecting or connected. if (_connector.state != MeshCoreConnectionState.disconnected) return; try { diff --git a/lib/services/map_tile_cache_service.dart b/lib/services/map_tile_cache_service.dart index 3be80f67..5538d91d 100644 --- a/lib/services/map_tile_cache_service.dart +++ b/lib/services/map_tile_cache_service.dart @@ -275,14 +275,26 @@ class MapTileCacheResult { final int total; final int downloaded; final int failed; + final bool cancelled; const MapTileCacheResult({ required this.total, required this.downloaded, required this.failed, + this.cancelled = false, }); } +/// Cooperative cancellation flag for [MapTileCacheService.downloadRegion]. +/// Tiles already in flight finish; no new tiles are queued after [cancel]. +class MapTileDownloadCancelToken { + bool _cancelled = false; + + bool get isCancelled => _cancelled; + + void cancel() => _cancelled = true; +} + class CachedTileInfo { final String key; final String host; @@ -316,6 +328,10 @@ class MapTileCacheService extends ChangeNotifier { static const int defaultMinZoom = 10; static const int defaultMaxZoom = 15; + /// Largest bulk download the UI allows in one go. Keeps a single request + /// within tile-server usage policies and avoids filling the device. + static const int maxBulkDownloadTiles = 20000; + final AppSettingsService appSettingsService; final BaseCacheManager cacheManager; late final TileProvider tileProvider; @@ -614,6 +630,7 @@ class MapTileCacheService extends ChangeNotifier { int concurrentDownloads = 8, Map? headers, void Function(MapTileCacheProgress progress)? onProgress, + MapTileDownloadCancelToken? cancelToken, }) async { final safeMin = math.min(minZoom, maxZoom); final safeMax = math.max(minZoom, maxZoom); @@ -652,10 +669,17 @@ class MapTileCacheService extends ChangeNotifier { } } + var stoppedEarly = false; + + outer: for (int zoom = safeMin; zoom <= safeMax; zoom++) { final tileBounds = _tileBoundsForBounds(bounds, zoom); for (int x = tileBounds.minX; x <= tileBounds.maxX; x++) { for (int y = tileBounds.minY; y <= tileBounds.maxY; y++) { + if (cancelToken?.isCancelled ?? false) { + stoppedEarly = true; + break outer; + } final url = _buildTileUrl(x, y, zoom, urlTemplate: currentTemplate); await queueDownload(url); } @@ -670,6 +694,7 @@ class MapTileCacheService extends ChangeNotifier { total: total, downloaded: completed - failed, failed: failed, + cancelled: stoppedEarly, ); } diff --git a/lib/services/repeater_command_service.dart b/lib/services/repeater_command_service.dart index 43e79a1d..246f01b6 100644 --- a/lib/services/repeater_command_service.dart +++ b/lib/services/repeater_command_service.dart @@ -131,6 +131,14 @@ class RepeaterCommandService { ); } + /// The text [sendCommand] would put on the wire for its next attempt: the + /// clock-sync rewrite plus the `XX|` reply prefix (unless [raw]). Used for + /// debug previews so they match what is actually sent. + String previewFramedCommand(String command, {bool raw = false}) { + if (raw) return command; + return '${_peekPrefixToken()}${normalizeRepeaterClockSyncCommand(command)}'; + } + /// Send [line] verbatim and don't wait for a reply. While `region load` is /// active the firmware consumes each line before prefix stripping and /// sends nothing back (simple_repeater/MyMesh.cpp handleCommand). @@ -185,6 +193,17 @@ class RepeaterCommandService { _pendingByPrefix.clear(); } + String _peekPrefixToken() { + for (var i = 0; i < 256; i++) { + final value = (_prefixCounter + i) & 0xFF; + final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|'; + if (!_pendingByPrefix.containsKey(token)) { + return token; + } + } + return '00|'; + } + String _nextPrefixToken() { for (var i = 0; i < 256; i++) { final value = _prefixCounter++ & 0xFF; diff --git a/lib/widgets/battery_indicator.dart b/lib/widgets/battery_indicator.dart index 9a74d7d5..8d70e8af 100644 --- a/lib/widgets/battery_indicator.dart +++ b/lib/widgets/battery_indicator.dart @@ -78,7 +78,7 @@ class _BatteryIndicatorState extends State { child: Text( displayText, style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, fontWeight: FontWeight.w600, color: batteryUi.color, ), diff --git a/lib/widgets/byte_count_input.dart b/lib/widgets/byte_count_input.dart index aa132366..5872b192 100644 --- a/lib/widgets/byte_count_input.dart +++ b/lib/widgets/byte_count_input.dart @@ -145,7 +145,7 @@ class ByteCountedTextField extends StatelessWidget { ? Text( softLimitNote!, style: TextStyle( - fontSize: 11, + fontSize: 12, color: Theme.of(context).colorScheme.tertiary, ), ) @@ -154,7 +154,7 @@ class ByteCountedTextField extends StatelessWidget { const SizedBox(width: 8), Text( '$usedBytes / $maxBytes', - style: TextStyle(fontSize: 11, color: counterColor), + style: TextStyle(fontSize: 12, color: counterColor), ), ], ), diff --git a/lib/widgets/chat_composer.dart b/lib/widgets/chat_composer.dart new file mode 100644 index 00000000..28cbf961 --- /dev/null +++ b/lib/widgets/chat_composer.dart @@ -0,0 +1,291 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../helpers/gif_helper.dart'; +import '../l10n/l10n.dart'; +import '../services/app_settings_service.dart'; +import '../theme/mesh_theme.dart'; +import 'byte_count_input.dart'; +import 'gif_message.dart'; +import 'gif_picker.dart'; +import 'message_translation_button.dart'; + +/// One entry of the composer's "+" menu. +@immutable +class ChatComposerAction { + final String id; + final IconData icon; + final String label; + + const ChatComposerAction({ + required this.id, + required this.icon, + required this.label, + }); +} + +/// Opens the GIF picker and puts the chosen GIF into [controller]. +void showChatGifPicker(BuildContext context, TextEditingController controller) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (context) => GifPicker( + onGifSelected: (gifId) { + controller.text = GifHelper.encodeGif(gifId); + }, + ), + ); +} + +/// Opens the outgoing-translation options sheet. +Future showComposerTranslationOptions(BuildContext context) async { + final settingsService = context.read(); + final settings = settingsService.settings; + await showMessageTranslationSheet( + context: context, + enabled: settings.composerTranslationEnabled, + selectedLanguageCode: settings.translationTargetLanguageCode, + onEnabledChanged: settingsService.setComposerTranslationEnabled, + onLanguageSelected: settingsService.setTranslationTargetLanguageCode, + ); +} + +/// The message composer shared by the direct and channel chat screens: +/// "+" action menu, optional translation toggle, byte-counted text field (or +/// GIF preview) and send button. [header] widgets (reply banner, progress) +/// are stacked above the row. +class ChatComposer extends StatelessWidget { + final TextEditingController controller; + final FocusNode focusNode; + final int maxBytes; + final int? softLimitBytes; + final String? softLimitNote; + final String Function(String)? encoder; + final VoidCallback onSend; + final String sendTooltip; + + /// Builds the "+" menu entries when it is opened, so they reflect the + /// current state (e.g. whether the radio has a position). + final List Function() actionsBuilder; + final ValueChanged onAction; + final List header; + + const ChatComposer({ + super.key, + required this.controller, + required this.focusNode, + required this.maxBytes, + required this.onSend, + required this.sendTooltip, + required this.actionsBuilder, + required this.onAction, + this.softLimitBytes, + this.softLimitNote, + this.encoder, + this.header = const [], + }); + + Future _openActionMenu(BuildContext buttonContext) async { + final actions = actionsBuilder(); + if (actions.isEmpty) return; + final button = buttonContext.findRenderObject() as RenderBox; + final overlay = + Overlay.of(buttonContext).context.findRenderObject() as RenderBox; + final buttonOffset = button.localToGlobal(Offset.zero, ancestor: overlay); + final menuHeight = actions.length * 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: buttonContext, + position: position, + // Keep focus on the text field: if the menu route took focus, the + // keyboard would close, the composer would drop down and the menu would + // be left floating where the keyboard used to be. + requestFocus: false, + items: [ + for (final action in actions) + PopupMenuItem( + value: action.id, + child: Row( + children: [ + Icon(action.icon), + const SizedBox(width: 12), + Flexible(child: Text(action.label)), + ], + ), + ), + ], + ); + if (selected == null || !buttonContext.mounted) return; + onAction(selected); + } + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final translation = context + .select( + (s) => ( + s.settings.translationEnabled, + s.settings.composerTranslationEnabled, + s.settings.translationTargetLanguageCode, + ), + ); + return Container( + decoration: BoxDecoration( + color: scheme.surface, + border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), + ), + child: SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ...header, + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Builder( + builder: (buttonContext) => IconButton( + icon: const Icon(Icons.add_circle_outline), + tooltip: context.l10n.chat_selectSendAction, + onPressed: () => _openActionMenu(buttonContext), + ), + ), + if (translation.$1) + MessageTranslationButton( + enabled: translation.$2, + languageCode: translation.$3, + onPressed: () => showComposerTranslationOptions(context), + ), + Expanded( + child: ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final gifId = GifHelper.parseGif(value.text); + if (gifId != null) { + return _buildGifPreview(context, gifId, scheme); + } + return _buildTextField(context, scheme); + }, + ), + ), + const SizedBox(width: 6), + ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final hasText = value.text.trim().isNotEmpty; + return IconButton.filled( + icon: const Icon(Icons.send, size: 20), + tooltip: sendTooltip, + style: IconButton.styleFrom( + backgroundColor: hasText + ? scheme.primary + : scheme.surfaceContainerHighest, + foregroundColor: hasText + ? scheme.onPrimary + : scheme.onSurfaceVariant, + minimumSize: const Size(40, 40), + shape: const CircleBorder(), + ), + onPressed: hasText + ? () { + HapticFeedback.lightImpact(); + onSend(); + } + : null, + ); + }, + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildGifPreview( + BuildContext context, + String gifId, + ColorScheme scheme, + ) { + return Focus( + autofocus: true, + onKeyEvent: (node, event) { + if (event is KeyDownEvent && + (event.logicalKey == LogicalKeyboardKey.enter || + event.logicalKey == LogicalKeyboardKey.numpadEnter)) { + onSend(); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: Row( + children: [ + Expanded( + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: scheme.surfaceContainerHighest, + fallbackTextColor: scheme.onSurface.withValues(alpha: 0.6), + maxSize: 160, + ), + ), + ), + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.close), + tooltip: context.l10n.chat_removeGif, + onPressed: () { + controller.clear(); + focusNode.requestFocus(); + }, + ), + ], + ), + ); + } + + Widget _buildTextField(BuildContext context, ColorScheme scheme) { + OutlineInputBorder border(Color color, [double width = 1]) => + OutlineInputBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + borderSide: BorderSide(color: color, width: width), + ); + return ByteCountedTextField( + maxBytes: maxBytes, + softLimitBytes: softLimitBytes, + softLimitNote: softLimitNote, + controller: controller, + focusNode: focusNode, + hintText: context.l10n.chat_typeMessage, + onSubmitted: (_) => onSend(), + encoder: encoder, + decoration: InputDecoration( + hintText: context.l10n.chat_typeMessage, + border: border(scheme.outlineVariant), + enabledBorder: border(scheme.outlineVariant), + focusedBorder: border(scheme.primary, 1.5), + filled: true, + fillColor: scheme.surfaceContainerLow, + contentPadding: const EdgeInsets.symmetric( + horizontal: 18, + vertical: 12, + ), + ), + ); + } +} diff --git a/lib/widgets/chat_day_separator.dart b/lib/widgets/chat_day_separator.dart index 292af8d6..a6d9bcad 100644 --- a/lib/widgets/chat_day_separator.dart +++ b/lib/widgets/chat_day_separator.dart @@ -51,7 +51,7 @@ class ChatDaySeparator extends StatelessWidget { Text( formatChatDayLabel(context, day), style: MeshTheme.mono( - fontSize: 10.5, + fontSize: 12, fontWeight: FontWeight.w600, color: color, ), diff --git a/lib/widgets/chat_send_pipeline.dart b/lib/widgets/chat_send_pipeline.dart new file mode 100644 index 00000000..9f3386d4 --- /dev/null +++ b/lib/widgets/chat_send_pipeline.dart @@ -0,0 +1,192 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/translation_support.dart'; +import '../services/app_settings_service.dart'; +import '../services/translation_service.dart'; +import '../utils/app_logger.dart'; +import '../utils/platform_info.dart'; +import 'marker_label_dialog.dart'; + +/// Send guard and one-second cooldown shared by the chat composers. +/// +/// The cooldown is only stamped by [markDispatched], i.e. once a send has +/// actually gone to the connector, so a rejected attempt (empty, too long, +/// translation aborted) never locks the user out. +class ChatSendGuard { + static const cooldown = Duration(seconds: 1); + + DateTime? _lastDispatchAt; + bool _busy = false; + + /// True while a send is awaiting outgoing translation, so a second tap + /// can't send the same text again. + bool get isBusy => _busy; + + /// Runs [action] unless another send is already in flight. + Future runExclusive(Future Function() action) async { + if (_busy) return; + _busy = true; + try { + await action(); + } finally { + _busy = false; + } + } + + /// Returns false, and tells the user, if the last dispatch was under a + /// second ago. + bool checkCooldown(BuildContext context) { + final last = _lastDispatchAt; + if (last != null && DateTime.now().difference(last) < cooldown) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_sendCooldown), + ); + return false; + } + return true; + } + + void markDispatched() => _lastDispatchAt = DateTime.now(); +} + +/// Outcome of the optional outgoing translation step. +@immutable +class OutgoingTranslation { + final String text; + final String? originalText; + final String? languageCode; + final String? modelId; + + const OutgoingTranslation( + this.text, { + this.originalText, + this.languageCode, + this.modelId, + }); +} + +/// Translates [text] when composer translation is on and applies, returning +/// the text to send plus translation metadata. Returns null when [context] +/// was unmounted while the translation ran. +Future translateOutgoingText( + BuildContext context, + String text, +) async { + final settings = context.read().settings; + if (!settings.translationEnabled) return OutgoingTranslation(text); + final translationService = context.read(); + final targetLanguageCode = translationService.resolvedTargetLanguageCode( + Localizations.localeOf(context).languageCode, + ); + if (!translationService.shouldTranslateOutgoing( + text: text, + targetLanguageCode: targetLanguageCode, + )) { + return OutgoingTranslation(text); + } + final result = await translationService.translateOutgoingText( + text: text, + targetLanguageCode: targetLanguageCode, + ); + if (!context.mounted) return null; + if (result != null && + result.status == MessageTranslationStatus.completed && + result.translatedText.isNotEmpty) { + return OutgoingTranslation( + result.translatedText, + originalText: text, + languageCode: result.targetLanguageCode, + modelId: result.modelId, + ); + } + return OutgoingTranslation(text); +} + +/// Shares the radio's own position as a map marker through [send]. Uses the +/// same [guard] as typed messages so it can't race or flood alongside them. +Future shareMyLocationMarker({ + required BuildContext context, + required MeshCoreConnector connector, + required ChatSendGuard guard, + required Future Function(String markerText) send, + String logTag = 'Chat', +}) async { + final lat = connector.selfLatitude; + final lon = connector.selfLongitude; + if (!hasShareableLocation(lat, lon)) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_noRadioLocation), + ); + return; + } + final selfName = connector.selfName; + final label = await showMarkerLabelDialog( + context, + lat: lat!, + lon: lon!, + defaultLabel: selfName != null && selfName.isNotEmpty + ? selfName + : context.l10n.map_sharedPin, + flags: 'poi', + confirmText: context.l10n.common_share, + ); + if (label == null || label.isEmpty || !context.mounted) return; + await guard.runExclusive(() async { + if (!guard.checkCooldown(context)) return; + final pending = send(formatMarkerText(lat, lon, label, 'poi')); + guard.markDispatched(); + try { + await pending; + } catch (e) { + // A failed send is already marked failed on the message itself. + appLogger.warn('Sharing location failed: $e', tag: logTag); + } + }); +} + +/// Copies a message to the clipboard and confirms it. +void copyChatMessageText(BuildContext context, 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), + ); +} + +/// Asks before clearing a transcript. [message] says what will be erased. +Future confirmClearChat( + BuildContext context, { + required String message, +}) async { + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(dialogContext.l10n.contact_clearChat), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(dialogContext.l10n.common_cancel), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, true), + style: TextButton.styleFrom( + foregroundColor: Theme.of(dialogContext).colorScheme.error, + ), + child: Text(dialogContext.l10n.common_delete), + ), + ], + ), + ); + return confirmed == true; +} diff --git a/lib/widgets/confirm_clear_dialog.dart b/lib/widgets/confirm_clear_dialog.dart new file mode 100644 index 00000000..d1d046e8 --- /dev/null +++ b/lib/widgets/confirm_clear_dialog.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; + +import '../l10n/l10n.dart'; + +/// Asks the user to confirm clearing a log or history. Resolves to true only +/// when the user taps Clear. +Future showConfirmClearDialog( + BuildContext context, { + required String title, + required String message, +}) async { + final l10n = context.l10n; + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + style: FilledButton.styleFrom( + backgroundColor: Theme.of(dialogContext).colorScheme.error, + foregroundColor: Theme.of(dialogContext).colorScheme.onError, + ), + child: Text(l10n.common_clear), + ), + ], + ), + ); + return confirmed == true; +} diff --git a/lib/widgets/contact_visuals.dart b/lib/widgets/contact_visuals.dart new file mode 100644 index 00000000..ace35429 --- /dev/null +++ b/lib/widgets/contact_visuals.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; + +import '../connector/meshcore_protocol.dart'; +import '../l10n/app_localizations.dart'; +import '../models/contact.dart'; +import '../theme/mesh_theme.dart'; + +/// Shared node-type visuals and last-seen formatting for contact lists +/// (contacts, discovery, nearby-node scan). + +/// Accent used for sensor nodes. +const Color meshSensorTeal = Color(0xFF4ACCC4); + +/// Node-type accent colour per design language. +Color contactTypeColor(int type) { + switch (type) { + case advTypeRepeater: + return MeshPalette.warn; + case advTypeRoom: + return MeshPalette.magenta; + case advTypeSensor: + return meshSensorTeal; + default: + return MeshPalette.blue; + } +} + +/// Node-type avatar icon. Returns null for chat nodes so [AvatarCircle] +/// shows initials. +IconData? contactTypeIcon(int type) { + switch (type) { + case advTypeRepeater: + return Icons.cell_tower; + case advTypeRoom: + return Icons.meeting_room; + case advTypeSensor: + return Icons.sensors; + default: + return null; + } +} + +/// The most recent activity for [contact]: for chat nodes this includes the +/// last message, for other node types only the last advert. +DateTime resolveContactLastSeen(Contact contact) { + if (contact.type != advTypeChat) return contact.lastSeen; + return contact.lastMessageAt.isAfter(contact.lastSeen) + ? contact.lastMessageAt + : contact.lastSeen; +} + +/// Short relative "last seen" label ("now", "5 mins ago", "2 days ago"). +String formatContactLastSeen(AppLocalizations l10n, DateTime lastSeen) { + final diff = DateTime.now().difference(lastSeen); + + if (diff.isNegative || diff.inMinutes < 5) { + return l10n.contacts_lastSeenNow; + } + if (diff.inMinutes < 60) { + return l10n.contacts_lastSeenMinsAgo(diff.inMinutes); + } + if (diff.inHours < 24) { + final hours = diff.inHours; + return hours == 1 + ? l10n.contacts_lastSeenHourAgo + : l10n.contacts_lastSeenHoursAgo(hours); + } + final days = diff.inDays; + return days == 1 + ? l10n.contacts_lastSeenDayAgo + : l10n.contacts_lastSeenDaysAgo(days); +} + +/// Memoizes a derived list (filtered/sorted contacts) so it is only +/// recomputed when the input elements or the filter key change. Contacts are +/// immutable, so element identity is a sufficient change check even though +/// the connector hands out a fresh list copy on every read. +class DerivedListCache { + List? _inputs; + List? _key; + List? _result; + + List get(List inputs, List key, List Function() compute) { + final cached = _result; + if (cached != null && + _sameElements(_inputs!, inputs) && + _sameKey(_key!, key)) { + return cached; + } + final result = compute(); + _inputs = List.of(inputs); + _key = key; + _result = result; + return result; + } + + void invalidate() => _result = null; + + static bool _sameElements(List a, List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (!identical(a[i], b[i])) return false; + } + return true; + } + + static bool _sameKey(List a, List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + final x = a[i]; + final y = b[i]; + if (x is List && y is List) { + if (x.length != y.length) return false; + for (var j = 0; j < x.length; j++) { + if (x[j] != y[j]) return false; + } + } else if (x != y) { + return false; + } + } + return true; + } +} diff --git a/lib/widgets/cyr2lat_profile_dialog.dart b/lib/widgets/cyr2lat_profile_dialog.dart new file mode 100644 index 00000000..e0846b75 --- /dev/null +++ b/lib/widgets/cyr2lat_profile_dialog.dart @@ -0,0 +1,151 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; + +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/app_settings.dart'; +import '../services/app_settings_service.dart'; + +/// Add or edit a Cyrillic-to-Latin transliteration profile. +/// +/// Pass [profile] to edit it; leave it null to create a new profile seeded +/// with the default character map. Owns (and disposes) its controllers. +class Cyr2LatProfileDialog extends StatefulWidget { + final AppSettingsService settingsService; + final Cyr2LatProfile? profile; + + const Cyr2LatProfileDialog({ + super.key, + required this.settingsService, + this.profile, + }); + + @override + State createState() => _Cyr2LatProfileDialogState(); +} + +class _Cyr2LatProfileDialogState extends State { + late final TextEditingController _nameController = TextEditingController( + text: widget.profile?.name ?? '', + ); + late final TextEditingController _jsonController = TextEditingController( + text: const JsonEncoder.withIndent( + ' ', + ).convert(widget.profile?.charMap ?? defaultCyr2LatCharMap), + ); + bool _saving = false; + + bool get _isEdit => widget.profile != null; + + @override + void dispose() { + _nameController.dispose(); + _jsonController.dispose(); + super.dispose(); + } + + Future _save() async { + final l10n = context.l10n; + final name = _nameController.text; + if (name.isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.settings_cyr2latProfileNameEmpty), + ); + return; + } + final Map map; + try { + final json = jsonDecode(_jsonController.text) as Map; + map = json.map((key, value) => MapEntry(key, value.toString())); + } catch (e) { + showDismissibleSnackBar( + context, + content: Text(l10n.channels_cyr2latSettingsDialogWrongJSON('$e')), + ); + return; + } + + setState(() => _saving = true); + try { + final existing = widget.profile; + if (existing != null) { + await widget.settingsService.updateCyr2LatProfile( + existing.copyWith(name: name, charMap: map), + ); + } else { + await widget.settingsService.addCyr2LatProfile( + Cyr2LatProfile( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: name, + charMap: map, + ), + ); + } + if (!mounted) return; + Navigator.pop(context); + showDismissibleSnackBar( + context, + content: Text( + _isEdit + ? l10n.settings_cyr2latProfileUpdated + : l10n.settings_cyr2latProfileAdded, + ), + ); + } catch (e) { + if (!mounted) return; + setState(() => _saving = false); + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error('$e')), + ); + } + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AlertDialog( + title: Text( + _isEdit + ? l10n.settings_cyr2latProfileEdit + : l10n.settings_cyr2latProfileAdd, + ), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.settings_cyr2latProfileName, + border: const OutlineInputBorder(), + ), + ), + const SizedBox(height: 16), + TextField( + controller: _jsonController, + maxLines: 15, + decoration: InputDecoration( + labelText: l10n.channels_cyr2latSettingsDialogHint, + border: const OutlineInputBorder(), + hintText: l10n.channels_cyr2latSettingsDscr, + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + TextButton( + onPressed: _saving ? null : _save, + child: Text(l10n.common_save), + ), + ], + ); + } +} diff --git a/lib/widgets/debug_frame_viewer.dart b/lib/widgets/debug_frame_viewer.dart index c8dc3712..2d4c3f28 100644 --- a/lib/widgets/debug_frame_viewer.dart +++ b/lib/widgets/debug_frame_viewer.dart @@ -65,7 +65,7 @@ class DebugFrameViewer { children: [ Text( details.toString(), - style: const TextStyle(fontFamily: 'monospace', fontSize: 12), + style: const TextStyle(fontFamily: 'monospace', fontSize: 13), ), const Divider(), Text( @@ -75,7 +75,7 @@ class DebugFrameViewer { const SizedBox(height: 8), Text( hexString, - style: const TextStyle(fontFamily: 'monospace', fontSize: 11), + style: const TextStyle(fontFamily: 'monospace', fontSize: 13), ), ], ), diff --git a/lib/widgets/device_tile.dart b/lib/widgets/device_tile.dart index 3763b78a..a66b78e5 100644 --- a/lib/widgets/device_tile.dart +++ b/lib/widgets/device_tile.dart @@ -77,7 +77,7 @@ class DeviceTile extends StatelessWidget { Text( mac, style: MeshTheme.mono( - fontSize: 11, + fontSize: 13, color: scheme.onSurfaceVariant, ), maxLines: 1, @@ -101,11 +101,15 @@ class DeviceTile extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [ - Icon(signalUi.icon, size: 16, color: signalUi.color), + Icon(signalUi.icon, size: 20, color: signalUi.color), const SizedBox(height: 3), Text( '$rssi dBm', - style: MeshTheme.mono(fontSize: 10, color: signalUi.color), + style: MeshTheme.mono( + fontSize: 13, + fontWeight: FontWeight.w600, + color: signalUi.color, + ), ), ], ), diff --git a/lib/widgets/gif_picker.dart b/lib/widgets/gif_picker.dart index 5205143d..e86ead15 100644 --- a/lib/widgets/gif_picker.dart +++ b/lib/widgets/gif_picker.dart @@ -183,7 +183,7 @@ class _GifPickerState extends State { Text( context.l10n.gifPicker_poweredBy, style: TextStyle( - fontSize: 11, + fontSize: 12, color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), diff --git a/lib/widgets/language_picker_sheet.dart b/lib/widgets/language_picker_sheet.dart new file mode 100644 index 00000000..e922289d --- /dev/null +++ b/lib/widgets/language_picker_sheet.dart @@ -0,0 +1,77 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../l10n/l10n.dart'; +import '../services/app_settings_service.dart'; +import 'mesh_nav_tile.dart'; +import 'mesh_ui.dart'; + +/// App UI languages offered in settings, in display order. A null code means +/// "follow the system language". Add a locale here (and only here) to make it +/// selectable and labelled. +final List<(String?, String Function(AppLocalizations))> appLanguageOptions = [ + (null, (l) => l.appSettings_languageSystem), + ('en', (l) => l.appSettings_languageEn), + ('fr', (l) => l.appSettings_languageFr), + ('es', (l) => l.appSettings_languageEs), + ('de', (l) => l.appSettings_languageDe), + ('pl', (l) => l.appSettings_languagePl), + ('sl', (l) => l.appSettings_languageSl), + ('pt', (l) => l.appSettings_languagePt), + ('it', (l) => l.appSettings_languageIt), + ('zh', (l) => l.appSettings_languageZh), + ('sv', (l) => l.appSettings_languageSv), + ('nl', (l) => l.appSettings_languageNl), + ('sk', (l) => l.appSettings_languageSk), + ('bg', (l) => l.appSettings_languageBg), + ('ru', (l) => l.appSettings_languageRu), + ('uk', (l) => l.appSettings_languageUk), + ('hu', (l) => l.appSettings_languageHu), + ('ja', (l) => l.appSettings_languageJa), + ('ko', (l) => l.appSettings_languageKo), +]; + +/// Localized label for [languageCode]; unknown codes and null read as +/// "System". +String appLanguageLabel(BuildContext context, String? languageCode) { + final l10n = context.l10n; + for (final (code, label) in appLanguageOptions) { + if (code == languageCode) return label(l10n); + } + return l10n.appSettings_languageSystem; +} + +/// Bottom sheet for choosing the app UI language override. +void showLanguagePickerSheet( + BuildContext context, + AppSettingsService settingsService, +) { + final l10n = context.l10n; + final current = settingsService.settings.languageOverride; + showMeshSheet( + context, + builder: (ctx) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader(title: l10n.appSettings_language), + SizedBox( + height: 400, + child: ListView( + children: [ + for (final (code, label) in appLanguageOptions) + MeshSheetOption( + label: label(l10n), + selected: current == code, + onTap: () { + settingsService.setLanguageOverride(code); + Navigator.pop(ctx); + }, + ), + SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8), + ], + ), + ), + ], + ), + ); +} diff --git a/lib/widgets/map_poi_cluster.dart b/lib/widgets/map_poi_cluster.dart new file mode 100644 index 00000000..2b448908 --- /dev/null +++ b/lib/widgets/map_poi_cluster.dart @@ -0,0 +1,121 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; + +import '../theme/mesh_theme.dart'; + +/// Size in degrees of a square grid cell that covers roughly [cellPx] +/// screen pixels at [zoom] (Web Mercator, 256 px tiles). +double mapGridCellDegrees(double zoom, {double cellPx = 64}) => + 360.0 / (256.0 * pow(2.0, zoom)) * cellPx; + +/// Key of the grid cell that [point] falls into for a cell size of [cellDeg]. +String mapGridCellKey(LatLng point, double cellDeg) => + '${(point.latitude / cellDeg).floor()}:${(point.longitude / cellDeg).floor()}'; + +/// Buckets [items] into grid cells of [cellDeg] degrees, keeping insertion +/// order inside each cell. +Map> mapGridCluster( + Iterable items, + LatLng Function(T item) positionOf, + double cellDeg, +) { + final cells = >{}; + for (final item in items) { + (cells[mapGridCellKey(positionOf(item), cellDeg)] ??= []).add(item); + } + return cells; +} + +/// Round marker that stands for several shared points of interest. When +/// [includesSelf] is set, it is drawn with the "You" ring and person icon so +/// the user's own position stays visible under the POIs placed there. +class PoiClusterMarker extends StatelessWidget { + final int count; + final bool includesSelf; + final String semanticLabel; + + const PoiClusterMarker({ + super.key, + required this.count, + required this.semanticLabel, + this.includesSelf = false, + }); + + @override + Widget build(BuildContext context) { + final circle = Container( + width: 40, + height: 40, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: includesSelf ? MapPalette.panelDark : MapPalette.router, + border: Border.all( + color: includesSelf ? MapPalette.selected : MapPalette.markerOutline, + width: 3, + ), + boxShadow: const [ + BoxShadow( + color: MapPalette.markerShadow, + blurRadius: 8, + offset: Offset(0, 3), + ), + ], + ), + alignment: Alignment.center, + child: includesSelf + ? const Icon( + Icons.person_pin_circle, + color: MapPalette.selected, + size: 24, + ) + : Text( + '$count', + style: MeshTheme.mono( + fontSize: count >= 100 ? 13 : 15, + fontWeight: FontWeight.w800, + color: MapPalette.markerOutline, + ), + ), + ); + return Semantics( + button: true, + label: semanticLabel, + excludeSemantics: true, + child: Stack( + clipBehavior: Clip.none, + alignment: Alignment.center, + children: [ + circle, + if (includesSelf) + Positioned( + right: -2, + top: -2, + child: Container( + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + padding: const EdgeInsets.symmetric(horizontal: 4), + decoration: BoxDecoration( + color: MapPalette.router, + borderRadius: BorderRadius.circular(MeshRadii.pill), + border: Border.all( + color: MapPalette.markerOutline, + width: 1.5, + ), + ), + alignment: Alignment.center, + child: Text( + '$count', + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w800, + color: MapPalette.markerOutline, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/mesh_nav_tile.dart b/lib/widgets/mesh_nav_tile.dart new file mode 100644 index 00000000..bfd7ae59 --- /dev/null +++ b/lib/widgets/mesh_nav_tile.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; + +/// Settings-style navigation row: leading icon, bold title, secondary +/// subtitle and an optional trailing chevron. +/// +/// Sized for readability (24px icons, `bodyLarge` titles, `bodyMedium` +/// subtitles). When [onTap] is null the row is rendered dimmed and reported +/// as disabled to accessibility services, so a tile that cannot be used never +/// looks identical to one that can. +class MeshNavTile extends StatelessWidget { + final IconData icon; + final String title; + final String? subtitle; + final VoidCallback? onTap; + final Color? titleColor; + final Color? iconColor; + final bool showChevron; + final Widget? trailing; + final int? subtitleMaxLines; + final EdgeInsetsGeometry padding; + + const MeshNavTile({ + super.key, + required this.icon, + required this.title, + this.subtitle, + this.onTap, + this.titleColor, + this.iconColor, + this.showChevron = true, + this.trailing, + this.subtitleMaxLines, + this.padding = const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final textTheme = theme.textTheme; + final enabled = onTap != null; + final effectiveIconColor = iconColor ?? scheme.onSurfaceVariant; + + final row = Row( + children: [ + Icon(icon, size: 24, color: effectiveIconColor), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: textTheme.bodyLarge?.copyWith( + fontWeight: FontWeight.w600, + color: titleColor, + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 2), + Text( + subtitle!, + maxLines: subtitleMaxLines, + overflow: subtitleMaxLines == null + ? null + : TextOverflow.ellipsis, + style: textTheme.bodyMedium?.copyWith( + color: titleColor != null + ? titleColor!.withValues(alpha: 0.8) + : scheme.onSurfaceVariant, + ), + ), + ], + ], + ), + ), + ?trailing, + if (showChevron && trailing == null) + Icon(Icons.chevron_right, color: scheme.onSurfaceVariant, size: 24), + ], + ); + + return MergeSemantics( + child: Semantics( + button: true, + enabled: enabled, + child: InkWell( + onTap: onTap, + child: Padding( + padding: padding, + // Dimmed rather than recoloured so warn/alert tints still read as + // such while clearly unavailable. + child: Opacity(opacity: enabled ? 1 : 0.5, child: row), + ), + ), + ), + ); + } +} + +/// One radio-style option row inside a bottom sheet picker. +class MeshSheetOption extends StatelessWidget { + final String label; + final bool selected; + final VoidCallback onTap; + + const MeshSheetOption({ + super.key, + required this.label, + required this.selected, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return ListTile( + leading: Icon( + selected ? Icons.radio_button_checked : Icons.radio_button_unchecked, + size: 24, + color: selected ? scheme.primary : scheme.onSurfaceVariant, + ), + title: Text(label), + onTap: onTap, + ); + } +} diff --git a/lib/widgets/mesh_ui.dart b/lib/widgets/mesh_ui.dart index 2943bc04..a69b2cfa 100644 --- a/lib/widgets/mesh_ui.dart +++ b/lib/widgets/mesh_ui.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -34,7 +36,10 @@ class SectionHeader extends StatelessWidget { Expanded( child: Text( label.toUpperCase(), - style: MeshTheme.accentLabel(color: scheme.onSurfaceVariant), + style: MeshTheme.accentLabel( + color: scheme.onSurfaceVariant, + fontSize: 13, + ), overflow: TextOverflow.ellipsis, ), ), @@ -114,7 +119,7 @@ class StatusChip extends StatelessWidget { required this.color, this.icon, this.pulse = false, - this.fontSize = 11.5, + this.fontSize = 12.5, }); @override @@ -192,7 +197,7 @@ class StatTile extends StatelessWidget { label.toUpperCase(), style: MeshTheme.accentLabel( color: scheme.onSurfaceVariant, - fontSize: 11, + fontSize: 12, ), maxLines: 2, overflow: TextOverflow.ellipsis, @@ -217,7 +222,7 @@ class StatTile extends StatelessWidget { TextSpan( text: ' $unit', style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: scheme.onSurfaceVariant, ), ), @@ -377,7 +382,7 @@ class RouteChip extends StatelessWidget { children: [ Icon( isDirect ? Icons.trending_flat : Icons.podcasts, - size: 11, + size: 14, color: scheme.onSurfaceVariant, ), const SizedBox(width: 3), @@ -385,7 +390,7 @@ class RouteChip extends StatelessWidget { label, style: MeshTheme.accentLabel( color: scheme.onSurfaceVariant, - fontSize: 8.5, + fontSize: 12, ), ), ], @@ -539,6 +544,11 @@ class BottomSheetHeader extends StatelessWidget { /// Shows a modal bottom sheet with the app-standard shape, scroll behavior /// and safe-area handling. Pair the content with [BottomSheetHeader]. +/// +/// `useSafeArea` only pads the top and sides, so the bottom is padded here by +/// whichever is larger: the keyboard inset or the system navigation bar +/// (edge-to-edge Android, iOS home indicator). Both are then removed from the +/// content's [MediaQuery] so nested [SafeArea]s don't apply them twice. Future showMeshSheet( BuildContext context, { required WidgetBuilder builder, @@ -549,10 +559,23 @@ Future showMeshSheet( isScrollControlled: isScrollControlled, useSafeArea: true, showDragHandle: false, - builder: (context) => Padding( - padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom), - child: builder(context), - ), + builder: (sheetContext) { + final media = MediaQuery.of(sheetContext); + final bottom = math.max( + media.viewInsets.bottom, + media.viewPadding.bottom, + ); + return Padding( + padding: EdgeInsets.only(bottom: bottom), + child: MediaQuery( + data: media + .removeViewInsets(removeBottom: true) + .removeViewPadding(removeBottom: true) + .removePadding(removeBottom: true), + child: Builder(builder: builder), + ), + ); + }, ); } diff --git a/lib/widgets/message_bubble_frame.dart b/lib/widgets/message_bubble_frame.dart new file mode 100644 index 00000000..3cd61556 --- /dev/null +++ b/lib/widgets/message_bubble_frame.dart @@ -0,0 +1,129 @@ +import 'package:flutter/material.dart'; + +import '../theme/mesh_theme.dart'; + +/// Colours shared by the direct-message and channel chat bubbles. +@immutable +class MessageBubbleColors { + final Color background; + final Color border; + final Color text; + final Color meta; + + const MessageBubbleColors({ + required this.background, + required this.border, + required this.text, + required this.meta, + }); + + /// Outgoing bubbles use [MeshPalette.me] / [MeshPalette.meBorder] / + /// [MeshPalette.meInk]; a failed send switches to the error container. + factory MessageBubbleColors.of( + ColorScheme scheme, { + required bool isOutgoing, + bool isFailed = false, + }) { + final text = isFailed + ? scheme.onErrorContainer + : isOutgoing + ? MeshPalette.meInk + : scheme.onSurface; + return MessageBubbleColors( + background: isFailed + ? scheme.errorContainer + : isOutgoing + ? MeshPalette.me + : scheme.surfaceContainerLow, + border: isFailed + ? scheme.error + : isOutgoing + ? MeshPalette.meBorder + : scheme.outlineVariant, + text: text, + meta: text.withValues(alpha: 0.65), + ); + } +} + +/// Asymmetric bubble radius: the corner nearest the sender is tight. +BorderRadius messageBubbleRadius({required bool isOutgoing}) { + return isOutgoing + ? const BorderRadius.only( + topLeft: Radius.circular(MeshRadii.lg), + topRight: Radius.circular(MeshRadii.lg), + bottomLeft: Radius.circular(MeshRadii.lg), + bottomRight: Radius.circular(MeshRadii.xs), + ) + : const BorderRadius.only( + topLeft: Radius.circular(MeshRadii.xs), + topRight: Radius.circular(MeshRadii.lg), + bottomLeft: Radius.circular(MeshRadii.lg), + bottomRight: Radius.circular(MeshRadii.lg), + ); +} + +/// Extra sender-name hues beyond the [MeshPalette] accents. They match the +/// two extra hues [AvatarCircle] uses, so a name and its avatar agree. +const Color kSenderHuePeriwinkle = Color(0xFF8FA8F0); +const Color kSenderHueAqua = Color(0xFF6FD9CE); + +const List _senderHues = [ + MeshPalette.blue, + MeshPalette.magenta, + MeshPalette.signal, + MeshPalette.warn, + kSenderHuePeriwinkle, + kSenderHueAqua, +]; + +/// Deterministic name-to-hue mapping consistent with [AvatarCircle]. +Color senderNameColor(String name) { + var h = 0; + for (final c in name.codeUnits) { + h = (h * 31 + c) & 0x7fffffff; + } + return _senderHues[h % _senderHues.length]; +} + +/// The bubble container shared by both chat screens: colour, border, +/// asymmetric radius, padding and the 72% max width. +class MessageBubbleFrame extends StatelessWidget { + final bool isOutgoing; + final bool isFailed; + + /// Tighter padding for media (GIF) content. + final bool compact; + final double maxWidth; + final Widget child; + + const MessageBubbleFrame({ + super.key, + required this.isOutgoing, + required this.maxWidth, + required this.child, + this.isFailed = false, + this.compact = false, + }); + + @override + Widget build(BuildContext context) { + final colors = MessageBubbleColors.of( + Theme.of(context).colorScheme, + isOutgoing: isOutgoing, + isFailed: isFailed, + ); + return Container( + padding: compact + ? const EdgeInsets.all(4) + : const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + constraints: BoxConstraints(maxWidth: maxWidth * 0.72), + decoration: BoxDecoration( + color: colors.background, + borderRadius: messageBubbleRadius(isOutgoing: isOutgoing), + border: Border.all(color: colors.border, width: 1), + ), + child: child, + ); + } +} diff --git a/lib/widgets/node_scan_sheet.dart b/lib/widgets/node_scan_sheet.dart index 8f7ae24d..5676d131 100644 --- a/lib/widgets/node_scan_sheet.dart +++ b/lib/widgets/node_scan_sheet.dart @@ -9,6 +9,7 @@ import '../l10n/contact_localization.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../theme/mesh_theme.dart'; +import 'contact_visuals.dart'; import 'mesh_ui.dart'; /// Opens the nearby-node scan (#570): a zero-hop DISCOVER_REQ whose answers @@ -180,7 +181,7 @@ class _NodeScanSheetState extends State { final known = _isKnownNode(contact); final inContacts = _isContact(response); final adding = _adding.contains(response.publicKeyHex); - final color = _typeColor(response.nodeType); + final color = contactTypeColor(response.nodeType); return Padding( padding: const EdgeInsets.symmetric(vertical: 4), @@ -192,7 +193,7 @@ class _NodeScanSheetState extends State { name: contact.name, size: 42, color: color, - icon: _typeIcon(response.nodeType), + icon: contactTypeIcon(response.nodeType), ), const SizedBox(width: 12), Expanded( @@ -217,7 +218,7 @@ class _NodeScanSheetState extends State { StatusChip( label: contact.typeLabel(l10n).toUpperCase(), color: color, - icon: _typeIcon(response.nodeType), + icon: contactTypeIcon(response.nodeType), ), ], ), @@ -281,30 +282,4 @@ class _NodeScanSheetState extends State { widget.connector.discoveredContacts.any( (c) => c.publicKeyHex == contact.publicKeyHex, ); - - static Color _typeColor(int type) { - switch (type) { - case advTypeRepeater: - return MeshPalette.warn; - case advTypeRoom: - return MeshPalette.magenta; - case advTypeSensor: - return const Color(0xFF4ACCC4); // teal, as in the discovery list - default: - return MeshPalette.blue; - } - } - - static IconData? _typeIcon(int type) { - switch (type) { - case advTypeRepeater: - return Icons.cell_tower; - case advTypeRoom: - return Icons.meeting_room; - case advTypeSensor: - return Icons.sensors; - default: - return null; - } - } } diff --git a/lib/widgets/path_map_scaffold.dart b/lib/widgets/path_map_scaffold.dart new file mode 100644 index 00000000..bfb1faef --- /dev/null +++ b/lib/widgets/path_map_scaffold.dart @@ -0,0 +1,506 @@ +import 'dart:math'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +import '../connector/meshcore_connector.dart'; +import '../helpers/guessed_location_estimator.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import '../models/display_path.dart'; +import '../models/path_playback.dart'; +import '../theme/mesh_theme.dart'; +import 'path_map_ui.dart'; + +/// Shared map plumbing for the path map screens (live path trace and +/// received-message path map): camera helpers, map options, desktop zoom +/// controls, node labels, and the collapsible bottom panel shell. + +const double kPathMapMinZoom = 2.0; +const double kPathMapMaxZoom = 18.0; +const double kPathMapLabelZoomThreshold = 8.5; +const EdgeInsets _fitPadding = EdgeInsets.all(64); + +bool isDesktopMapPlatform([TargetPlatform? platform]) { + final p = platform ?? defaultTargetPlatform; + return p == TargetPlatform.linux || + p == TargetPlatform.windows || + p == TargetPlatform.macOS; +} + +/// The connected radio's position, or null when it is unknown (disconnected) +/// or not a real fix (SELF_INFO reports 0,0 without GPS). +LatLng? plausibleSelfPoint(MeshCoreConnector connector) { + final lat = connector.selfLatitude; + final lon = connector.selfLongitude; + if (lat == null || lon == null || !isPlausibleLocation(lat, lon)) { + return null; + } + return LatLng(lat, lon); +} + +/// Cheap fingerprint of the fields path resolution depends on, used to skip +/// re-resolving hops when the connector notifies for unrelated reasons. +int contactListSignature(List contacts) { + return Object.hash( + contacts.length, + Object.hashAll( + contacts.map( + (c) => Object.hash( + Object.hashAll(c.publicKey.take(8)), + c.type, + c.name, + c.latitude, + c.longitude, + c.lastSeen, + c.path.length, + ), + ), + ), + ); +} + +bool sameLatLngList(List a, List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; +} + +/// Updates the playback path only when its geometry actually changed, so +/// unrelated rebuilds don't reset a running animation. +void syncPlaybackPath(PathPlaybackController playback, List points) { + if (sameLatLngList(points, playback.points)) return; + playback.setPath(points); +} + +/// Keeps the camera centered on the packet while the follow lock is on. +void followPacketCamera( + MapController controller, + PathPlaybackController playback, { + required bool enabled, +}) { + if (!enabled || !playback.started || !playback.hasPath) return; + controller.move(playback.position, controller.camera.zoom); +} + +void zoomMapBy( + MapController controller, + double delta, { + double minZoom = kPathMapMinZoom, + double maxZoom = kPathMapMaxZoom, +}) { + final camera = controller.camera; + final nextZoom = (camera.zoom + delta).clamp(minZoom, maxZoom).toDouble(); + controller.move(camera.center, nextZoom); +} + +void resetMapView( + MapController controller, { + required LatLngBounds? bounds, + required LatLng? center, + required double zoom, +}) { + if (bounds != null) { + controller.fitCamera( + CameraFit.bounds(bounds: bounds, padding: _fitPadding, maxZoom: 16), + ); + return; + } + if (center != null) controller.move(center, zoom); +} + +/// Map options shared by the path and line-of-sight maps: no rotation, +/// desktop keyboard panning/zooming, and an initial fit to [bounds]. +MapOptions buildPathMapOptions({ + required LatLng initialCenter, + required double initialZoom, + required LatLngBounds? bounds, + double minZoom = kPathMapMinZoom, + double maxZoom = kPathMapMaxZoom, + PositionCallback? onPositionChanged, + TapCallback? onLongPress, + TapCallback? onSecondaryTap, +}) { + final isDesktop = isDesktopMapPlatform(); + return MapOptions( + initialCenter: initialCenter, + initialZoom: initialZoom, + initialCameraFit: bounds == null + ? null + : CameraFit.bounds(bounds: bounds, padding: _fitPadding, maxZoom: 16), + minZoom: minZoom, + maxZoom: maxZoom, + interactionOptions: InteractionOptions( + flags: ~InteractiveFlag.rotate, + scrollWheelVelocity: isDesktop ? 0.012 : 0.005, + cursorKeyboardRotationOptions: CursorKeyboardRotationOptions.disabled(), + keyboardOptions: isDesktop + ? const KeyboardOptions( + enableArrowKeysPanning: true, + enableWASDPanning: true, + enableRFZooming: true, + ) + : const KeyboardOptions.disabled(), + ), + onPositionChanged: onPositionChanged, + onLongPress: onLongPress, + onSecondaryTap: onSecondaryTap, + ); +} + +/// Floating zoom in/out/recenter buttons for desktop platforms. +class PathMapDesktopControls extends StatelessWidget { + final VoidCallback onZoomIn; + final VoidCallback onZoomOut; + final VoidCallback onReset; + + const PathMapDesktopControls({ + super.key, + required this.onZoomIn, + required this.onZoomOut, + required this.onReset, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return Positioned( + top: 16, + left: 16, + child: DecoratedBox( + decoration: BoxDecoration( + color: MeshPalette.bg1.withValues(alpha: 0.90), + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: MeshPalette.line2), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(MeshRadii.md), + child: IconTheme( + data: const IconThemeData(color: MeshPalette.ink), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.add), + color: MeshPalette.ink, + tooltip: l10n.map_zoomIn, + onPressed: onZoomIn, + ), + IconButton( + icon: const Icon(Icons.remove), + color: MeshPalette.ink, + tooltip: l10n.map_zoomOut, + onPressed: onZoomOut, + ), + IconButton( + icon: const Icon(Icons.my_location), + color: MeshPalette.ink, + tooltip: l10n.map_centerMap, + onPressed: onReset, + ), + ], + ), + ), + ), + ), + ); + } +} + +/// Name label floating above a node marker. +Marker buildPathNodeLabelMarker({ + required LatLng point, + required String label, +}) { + return Marker( + point: point, + width: 140, + height: 26, + alignment: Alignment.topCenter, + child: IgnorePointer( + child: Transform.translate( + offset: const Offset(0, -20), + child: FittedBox( + fit: BoxFit.contain, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: MeshPalette.bg.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular(MeshRadii.xs), + border: Border.all(color: MeshPalette.line, width: 0.5), + ), + alignment: Alignment.center, + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w600, + color: MeshPalette.ink, + ), + ), + ), + ), + ), + ), + ); +} + +/// Small count badge drawn on markers for repeaters shared by several paths. +class PathSharedCountBadge extends StatelessWidget { + final int count; + + const PathSharedCountBadge({super.key, required this.count}); + + @override + Widget build(BuildContext context) { + return Container( + width: 20, + height: 20, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: MeshPalette.bg1, + border: Border.all(color: MeshPalette.line3), + ), + alignment: Alignment.center, + child: Text( + '$count', + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w700, + color: MeshPalette.ink, + ), + ), + ); + } +} + +/// Dark, collapsible bottom panel shared by the path map screens: header +/// with distance and legend, playback controls, warnings, optional +/// multi-path summary, and the hop list. +/// +/// Sets dark-panel text/icon/divider colours explicitly so content does not +/// inherit light-theme colours. +class PathMapBottomPanel extends StatelessWidget { + final Widget header; + final bool combined; + final bool showInferredLegend; + final bool collapsed; + final VoidCallback onToggleCollapsed; + final PathPlaybackController playback; + final DisplayPath? selected; + final bool animationEnabled; + final VoidCallback onToggleAnimation; + final bool followEnabled; + final VoidCallback onToggleFollow; + final bool showNoSelfGpsNote; + final int pathCount; + final int hopRowCount; + final Widget? summary; + final Widget hopList; + + const PathMapBottomPanel({ + super.key, + required this.header, + required this.combined, + required this.showInferredLegend, + required this.collapsed, + required this.onToggleCollapsed, + required this.playback, + required this.selected, + required this.animationEnabled, + required this.onToggleAnimation, + required this.followEnabled, + required this.onToggleFollow, + required this.showNoSelfGpsNote, + required this.pathCount, + required this.hopRowCount, + required this.summary, + required this.hopList, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final maxHeight = + MediaQuery.of(context).size.height * (combined ? 0.45 : 0.35); + const hopRowHeight = 60.0; + + double? cardHeight; + if (!collapsed) { + final summaryHeight = combined ? 34.0 + pathCount * 40.0 : 0.0; + final noteHeight = showNoSelfGpsNote ? 22.0 : 0.0; + final estimatedHeight = + 150.0 + summaryHeight + noteHeight + hopRowCount * hopRowHeight; + cardHeight = max(196.0, min(maxHeight, estimatedHeight)); + } + + final warnStyle = const TextStyle(fontSize: 12, color: MeshPalette.warn); + final unresolved = selected?.unresolvedHops ?? 0; + + return Positioned( + left: 16, + right: 16, + bottom: 16, + child: SizedBox( + height: cardHeight, + child: Container( + decoration: BoxDecoration( + color: MeshPalette.bg1.withValues(alpha: 0.96), + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: MeshPalette.line2), + ), + clipBehavior: Clip.antiAlias, + child: DefaultTextStyle.merge( + style: const TextStyle(color: MeshPalette.ink), + child: IconTheme( + data: const IconThemeData(color: MeshPalette.ink), + child: DividerTheme( + data: const DividerThemeData(color: MeshPalette.line), + child: ListTileTheme( + data: const ListTileThemeData( + iconColor: MeshPalette.ink2, + textColor: MeshPalette.ink, + ), + child: TextButtonTheme( + data: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: MeshPalette.ink, + ), + ), + child: LayoutBuilder( + builder: (context, constraints) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ConstrainedBox( + constraints: BoxConstraints( + maxHeight: max( + 0.0, + constraints.maxHeight - + (collapsed ? 0.0 : hopRowHeight + 1.0), + ), + ), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB( + 12, + 8, + 4, + 0, + ), + child: Row( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + header, + const SizedBox(height: 4), + PathMiniLegend( + combined: combined, + showInferred: + showInferredLegend, + ), + ], + ), + ), + IconButton( + icon: Icon( + collapsed + ? Icons.expand_less + : Icons.expand_more, + ), + color: MeshPalette.ink, + tooltip: collapsed + ? l10n.pathMap_expandPanel + : l10n.pathMap_collapsePanel, + onPressed: onToggleCollapsed, + ), + ], + ), + ), + PathAnimationControls( + playback: playback, + selected: selected, + animationEnabled: animationEnabled, + onToggleAnimation: onToggleAnimation, + followEnabled: followEnabled, + onToggleFollow: onToggleFollow, + ), + if (!collapsed) ...[ + if (showNoSelfGpsNote) + Padding( + padding: const EdgeInsets.fromLTRB( + 12, + 0, + 12, + 4, + ), + child: Row( + children: [ + const Icon( + Icons.gps_off, + size: 16, + color: MeshPalette.warn, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + l10n.pathMap_noSelfGpsFix, + style: warnStyle, + ), + ), + ], + ), + ), + if (unresolved > 0) + Padding( + padding: const EdgeInsets.fromLTRB( + 12, + 0, + 12, + 4, + ), + child: Text( + l10n.pathMap_partialAnimation( + unresolved, + ), + style: warnStyle, + ), + ), + ?summary, + ], + ], + ), + ), + ), + if (!collapsed) ...[ + const Divider(height: 1), + Expanded(child: hopList), + ], + ], + ), + ), + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/path_map_ui.dart b/lib/widgets/path_map_ui.dart index 333301e0..e2dde460 100644 --- a/lib/widgets/path_map_ui.dart +++ b/lib/widgets/path_map_ui.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:latlong2/latlong.dart'; +import '../l10n/app_localizations.dart'; import '../l10n/l10n.dart'; import '../models/display_path.dart'; import '../models/path_playback.dart'; @@ -13,7 +14,7 @@ import '../theme/mesh_theme.dart'; enum PathViewMode { single, combined } -const Color kPrimaryPathColor = Colors.blueAccent; +const Color kPrimaryPathColor = MeshPalette.blue; const List kAlternatePathColors = [ Color(0xFF8B5CF6), // purple MeshPalette.signal, // green @@ -34,11 +35,15 @@ double getPathDistanceMeters(List points) { return distanceMeters; } -String formatDistance(double distanceMeters, {required bool isImperial}) { +String formatDistance( + double distanceMeters, { + required bool isImperial, + AppLocalizations? l10n, +}) { if (isImperial) { - return '(${(distanceMeters / 1609.34).toStringAsFixed(2)} mi)'; + return '(${(distanceMeters / 1609.34).toStringAsFixed(2)} ${l10n?.units_mi ?? 'mi'})'; } - return '(${(distanceMeters / 1000).toStringAsFixed(2)} km)'; + return '(${(distanceMeters / 1000).toStringAsFixed(2)} ${l10n?.units_km ?? 'km'})'; } String formatLastObserved(BuildContext context, DateTime timestamp) { @@ -87,7 +92,7 @@ List buildMultiPathPolylines({ Polyline( points: [path.points[i], path.points[i + 1]], strokeWidth: 11, - color: Colors.white.withValues(alpha: 0.22), + color: MapPalette.markerOutline.withValues(alpha: 0.22), ), ); } @@ -153,7 +158,7 @@ List buildPacketTrailPolylines( Polyline( points: [playback.points[seg], playback.position], strokeWidth: 8, - color: Colors.white.withValues(alpha: 0.45), + color: MapPalette.markerOutline.withValues(alpha: 0.45), ), Polyline(points: traversed, strokeWidth: 5, color: color), ]; @@ -201,7 +206,7 @@ List buildPacketMarkers(PathPlaybackController playback, Color color) { decoration: BoxDecoration( shape: BoxShape.circle, color: color, - border: Border.all(color: Colors.white, width: 2), + border: Border.all(color: MapPalette.markerOutline, width: 2), boxShadow: [ BoxShadow( color: color.withValues(alpha: 0.7), @@ -262,7 +267,7 @@ void showSharedNodeSheet( ), trailing: Text( l10n.pathMap_hopCount(path.totalTransmissions), - style: MeshTheme.mono(fontSize: 11, color: MeshPalette.ink3), + style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3), ), onTap: () { Navigator.pop(sheetContext); @@ -380,82 +385,92 @@ class PathAnimationControls extends StatelessWidget { VoidCallback? onPressed, Color? color, }) => IconButton( - icon: Icon(icon, size: 20, color: color), + icon: Icon(icon, size: 24, color: color), tooltip: tooltip, onPressed: onPressed, - visualDensity: VisualDensity.compact, padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 34, minHeight: 34), + constraints: const BoxConstraints(minWidth: 48, minHeight: 48), ); return Padding( padding: const EdgeInsets.fromLTRB(4, 0, 12, 2), - child: Row( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, children: [ - controlButton( - icon: Icons.animation, - tooltip: animationEnabled - ? l10n.pathMap_animationOff - : l10n.pathMap_animationOn, - color: animationEnabled ? MeshPalette.blue : MeshPalette.ink4, - onPressed: onToggleAnimation, + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + controlButton( + icon: Icons.animation, + tooltip: animationEnabled + ? l10n.pathMap_animationOff + : l10n.pathMap_animationOn, + color: animationEnabled + ? MeshPalette.blue + : MeshPalette.ink4, + onPressed: onToggleAnimation, + ), + controlButton( + icon: Icons.skip_previous, + tooltip: l10n.pathMap_stepBack, + onPressed: enabled && playback.started + ? playback.stepBack + : null, + ), + controlButton( + icon: playback.playing ? Icons.pause : Icons.play_arrow, + tooltip: playback.playing + ? l10n.pathMap_pause + : l10n.pathMap_play, + onPressed: enabled ? playback.togglePlay : null, + ), + controlButton( + icon: Icons.skip_next, + tooltip: l10n.pathMap_stepForward, + onPressed: enabled ? playback.stepForward : null, + ), + controlButton( + icon: Icons.replay, + tooltip: l10n.pathMap_replay, + onPressed: enabled ? playback.replay : null, + ), + controlButton( + icon: followEnabled ? Icons.lock : Icons.lock_open, + tooltip: followEnabled + ? l10n.pathMap_unfollowPacket + : l10n.pathMap_followPacket, + color: followEnabled ? MeshPalette.blue : null, + onPressed: enabled ? onToggleFollow : null, + ), + TextButton( + onPressed: enabled ? playback.cycleSpeed : null, + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(48, 48), + ), + child: Text( + playback.speed == 0.5 + ? '0.5×' + : '${playback.speed.toInt()}×', + style: MeshTheme.mono(fontSize: 14), + ), + ), + ], ), - controlButton( - icon: Icons.skip_previous, - tooltip: l10n.pathMap_stepBack, - onPressed: enabled && playback.started - ? playback.stepBack - : null, - ), - controlButton( - icon: playback.playing ? Icons.pause : Icons.play_arrow, - tooltip: playback.playing - ? l10n.pathMap_pause - : l10n.pathMap_play, - onPressed: enabled ? playback.togglePlay : null, - ), - controlButton( - icon: Icons.skip_next, - tooltip: l10n.pathMap_stepForward, - onPressed: enabled ? playback.stepForward : null, - ), - controlButton( - icon: Icons.replay, - tooltip: l10n.pathMap_replay, - onPressed: enabled ? playback.replay : null, - ), - controlButton( - icon: followEnabled ? Icons.lock : Icons.lock_open, - tooltip: followEnabled - ? l10n.pathMap_unfollowPacket - : l10n.pathMap_followPacket, - color: followEnabled ? MeshPalette.blue : null, - onPressed: enabled ? onToggleFollow : null, - ), - TextButton( - onPressed: enabled ? playback.cycleSpeed : null, - style: TextButton.styleFrom( - visualDensity: VisualDensity.compact, - padding: const EdgeInsets.symmetric(horizontal: 6), - minimumSize: const Size(36, 30), - ), - child: Text( - playback.speed == 0.5 ? '0.5×' : '${playback.speed.toInt()}×', - style: MeshTheme.mono(fontSize: 12), - ), - ), - Expanded( - child: Text( - hopLabel ?? '', - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.right, - style: MeshTheme.mono( - fontSize: 10.5, - color: MeshPalette.ink2, + if (hopLabel != null) + Padding( + padding: const EdgeInsets.only(left: 8), + child: Text( + hopLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: MeshTheme.mono( + fontSize: 12, + color: MeshPalette.ink2, + ), ), ), - ), ], ), ); @@ -483,7 +498,12 @@ class PathMiniLegend extends StatelessWidget { children: [ swatch, const SizedBox(width: 4), - Text(text, style: TextStyle(fontSize: 11, color: MeshPalette.ink3)), + Flexible( + child: Text( + text, + style: TextStyle(fontSize: 12, color: MeshPalette.ink3), + ), + ), ], ); Widget dashSample() => Row( @@ -511,7 +531,7 @@ class PathMiniLegend extends StatelessWidget { width: 14, height: 6, decoration: BoxDecoration( - color: Colors.white.withValues(alpha: 0.35), + color: MapPalette.markerOutline.withValues(alpha: 0.35), borderRadius: BorderRadius.circular(3), ), ), @@ -572,7 +592,7 @@ class PathSummaryList extends StatelessWidget { ), child: Text( l10n.pathMap_showAllPaths, - style: const TextStyle(fontSize: 11), + style: const TextStyle(fontSize: 12), ), ), ], @@ -590,7 +610,7 @@ class PathSummaryList extends StatelessWidget { final hidden = hiddenIds.contains(path.id); final timestamp = path.record?.timestamp; final parts = [ - '${l10n.pathMap_hopCount(path.totalTransmissions)} ${formatDistance(path.distanceMeters, isImperial: isImperial)}', + '${l10n.pathMap_hopCount(path.totalTransmissions)} ${formatDistance(path.distanceMeters, isImperial: isImperial, l10n: l10n)}', l10n.pathMap_gpsCount(path.gpsConfirmedHops, path.hopBytes.length), if (timestamp != null) formatLastObserved(context, timestamp), ]; @@ -634,23 +654,19 @@ class PathSummaryList extends StatelessWidget { parts.join(' · '), maxLines: 1, overflow: TextOverflow.ellipsis, - style: MeshTheme.mono( - fontSize: 10.5, - color: MeshPalette.ink3, - ), + style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3), ), ), ), IconButton( icon: Icon( hidden ? Icons.visibility_off : Icons.visibility, - size: 16, + size: 20, color: hidden ? MeshPalette.ink4 : MeshPalette.ink3, ), tooltip: hidden ? l10n.pathMap_showPath : l10n.pathMap_hidePath, - visualDensity: VisualDensity.compact, padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 30, minHeight: 30), + constraints: const BoxConstraints(minWidth: 40, minHeight: 40), onPressed: () => onToggleVisibility(path), ), ], diff --git a/lib/widgets/qr_scanner_widget.dart b/lib/widgets/qr_scanner_widget.dart index 320cd714..00a5ad33 100644 --- a/lib/widgets/qr_scanner_widget.dart +++ b/lib/widgets/qr_scanner_widget.dart @@ -2,7 +2,36 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; +import '../helpers/snack_bar_builder.dart'; import '../l10n/l10n.dart'; +import '../theme/mesh_theme.dart'; + +/// Size of the square scan window cut out of the overlay. +const double _scanWindowSize = 250; + +/// Full-screen spinner shown in place of the scanner while a scanned code is +/// being processed (stops the camera and prevents duplicate detections). +class QrScannerProcessingBody extends StatelessWidget { + const QrScannerProcessingBody({super.key}); + + @override + Widget build(BuildContext context) { + return ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: const Center(child: CircularProgressIndicator()), + ); + } +} + +/// Short warning snackbar for a QR code that isn't the expected kind. +void showInvalidQrSnackBar(BuildContext context, String message) { + showDismissibleSnackBar( + context, + content: Text(message), + backgroundColor: MeshPalette.warn, + duration: const Duration(seconds: 2), + ); +} /// A reusable QR code scanner widget that can be embedded anywhere. /// @@ -33,6 +62,11 @@ class QrScannerWidget extends StatefulWidget { /// Custom overlay widget (defaults to scan window frame) final Widget? overlay; + /// Use the app-themed overlay (accent corner brackets and a high-contrast + /// instructions pill) instead of the plain default. Ignored when [overlay] + /// is given. + final bool themed; + /// Instructions text shown below the scan window final String? instructions; @@ -50,6 +84,7 @@ class QrScannerWidget extends StatefulWidget { this.showFlashButton = true, this.showCameraSwitchButton = true, this.overlay, + this.themed = false, this.instructions, this.continuousScanning = false, this.debounceDuration = const Duration(milliseconds: 500), @@ -184,55 +219,79 @@ class _QrScannerWidgetState extends State } Widget _buildDefaultOverlay(BuildContext context) { - return ColorFiltered( - colorFilter: ColorFilter.mode( - Colors.black.withValues(alpha: 0.5), - BlendMode.srcOut, - ), - child: Stack( - fit: StackFit.expand, - children: [ - Container( - decoration: const BoxDecoration( - color: Colors.black, - backgroundBlendMode: BlendMode.dstOut, - ), + final instructions = widget.instructions; + return Stack( + fit: StackFit.expand, + children: [ + // Dimmed background with a transparent cutout for the scan window. + ColorFiltered( + colorFilter: ColorFilter.mode( + MeshPalette.bg.withValues(alpha: 0.55), + BlendMode.srcOut, ), + child: Stack( + fit: StackFit.expand, + children: [ + Container( + decoration: const BoxDecoration( + color: MeshPalette.bg, + backgroundBlendMode: BlendMode.dstOut, + ), + ), + Center( + child: Container( + height: _scanWindowSize, + width: _scanWindowSize, + decoration: BoxDecoration( + // Any opaque colour: it only defines the cutout shape. + color: MeshPalette.ink, + borderRadius: BorderRadius.circular(16), + ), + ), + ), + ], + ), + ), + if (widget.themed) + const ScannerCornerOverlay( + scanWindowSize: _scanWindowSize, + borderColor: MeshPalette.blue, + borderWidth: 3, + cornerLength: 28, + ), + // Instructions pill below the scan window. + if (instructions != null) Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ + const SizedBox(height: _scanWindowSize + 24), Container( - height: 250, - width: 250, + margin: const EdgeInsets.symmetric(horizontal: 24), + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 12, + ), decoration: BoxDecoration( - color: Colors.red, // This color is used for cutout - borderRadius: BorderRadius.circular(16), + color: MeshPalette.bg.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular( + widget.themed ? MeshRadii.pill : 8, + ), + ), + child: Text( + instructions, + style: const TextStyle( + color: MeshPalette.ink, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + textAlign: TextAlign.center, ), ), - if (widget.instructions != null) ...[ - const SizedBox(height: 24), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 24, - vertical: 12, - ), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.7), - borderRadius: BorderRadius.circular(8), - ), - child: Text( - widget.instructions!, - style: const TextStyle(color: Colors.white, fontSize: 14), - textAlign: TextAlign.center, - ), - ), - ], ], ), ), - ], - ), + ], ); } @@ -251,10 +310,7 @@ class _QrScannerWidgetState extends State ? Icons.flash_on : Icons.flash_off, ), - style: IconButton.styleFrom( - backgroundColor: Colors.black54, - foregroundColor: Colors.white, - ), + style: _controlStyle, ); }, ), @@ -264,15 +320,19 @@ class _QrScannerWidgetState extends State IconButton.filled( onPressed: () => _controller.switchCamera(), icon: const Icon(Icons.cameraswitch), - style: IconButton.styleFrom( - backgroundColor: Colors.black54, - foregroundColor: Colors.white, - ), + style: _controlStyle, ), ], ); } + static final ButtonStyle _controlStyle = IconButton.styleFrom( + backgroundColor: MeshPalette.bg.withValues(alpha: 0.7), + foregroundColor: MeshPalette.ink, + minimumSize: const Size(56, 56), + iconSize: 28, + ); + Widget _buildErrorWidget(BuildContext context, MobileScannerException error) { String message; IconData icon; @@ -293,20 +353,24 @@ class _QrScannerWidgetState extends State icon = Icons.error_outline; } - return Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(icon, size: 64, color: Colors.grey), - const SizedBox(height: 16), - Text( - message, - textAlign: TextAlign.center, - style: TextStyle(color: Colors.grey[600], fontSize: 16), - ), - ], + final scheme = Theme.of(context).colorScheme; + return ColoredBox( + color: scheme.surface, + child: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 64, color: scheme.onSurfaceVariant), + const SizedBox(height: 16), + Text( + message, + textAlign: TextAlign.center, + style: TextStyle(color: scheme.onSurface, fontSize: 16), + ), + ], + ), ), ), ); @@ -323,7 +387,7 @@ class ScannerCornerOverlay extends StatelessWidget { const ScannerCornerOverlay({ super.key, this.scanWindowSize = 250, - this.borderColor = Colors.white, + this.borderColor = MeshPalette.ink, this.borderWidth = 3, this.cornerLength = 30, }); diff --git a/lib/widgets/radio_disconnected_banner.dart b/lib/widgets/radio_disconnected_banner.dart new file mode 100644 index 00000000..7a0afc4a --- /dev/null +++ b/lib/widgets/radio_disconnected_banner.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; + +/// Inline warning shown at the top of repeater screens while the companion +/// radio is disconnected. Renders nothing while connected. +class RadioDisconnectedBanner extends StatelessWidget { + const RadioDisconnectedBanner({super.key}); + + @override + Widget build(BuildContext context) { + final connected = context.select( + (c) => c.isConnected, + ); + if (connected) return const SizedBox.shrink(); + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + return Semantics( + liveRegion: true, + child: Material( + color: scheme.errorContainer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Icon(Icons.link_off, size: 24, color: scheme.onErrorContainer), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + context.l10n.repeater_radioDisconnected, + style: textTheme.titleSmall?.copyWith( + color: scheme.onErrorContainer, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 2), + Text( + context.l10n.repeater_radioDisconnectedHint, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onErrorContainer, + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/radio_settings_dialog.dart b/lib/widgets/radio_settings_dialog.dart new file mode 100644 index 00000000..39a3a950 --- /dev/null +++ b/lib/widgets/radio_settings_dialog.dart @@ -0,0 +1,794 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/radio_settings.dart'; +import '../services/app_debug_log_service.dart'; + +/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others) +/// to the UI enum range (always 5-8). +int _toUiCodingRate(int deviceCr) { + return deviceCr <= 4 ? deviceCr + 4 : deviceCr; +} + +const Set _defaultRepeatFreqsKHz = {433000, 869495, 918000}; + +/// Whether the firmware accepts [freqKHz] for off-grid client repeat, using +/// the ranges from CMD_GET_ALLOWED_REPEAT_FREQ when known. +bool _isAllowedRepeatFreqKHz(MeshCoreConnector connector, int freqKHz) { + final ranges = connector.allowedRepeatFreqRanges; + if (ranges == null || ranges.isEmpty) { + return _defaultRepeatFreqsKHz.contains(freqKHz); + } + return ranges.any((r) => freqKHz >= r.lowKHz && freqKHz <= r.highKHz); +} + +/// Lowest TX power companion firmware accepts (CMD_SET_RADIO_TX_POWER). +const int _minTxPowerDbm = -9; + +/// Radio parameter editor (preset, frequency, bandwidth, SF, CR, TX power and +/// off-grid client repeat). Stays open when the radio rejects or fails to +/// apply the settings so the user's edits are not lost. +class RadioSettingsDialog extends StatefulWidget { + final MeshCoreConnector connector; + + const RadioSettingsDialog({super.key, required this.connector}); + + @override + State createState() => _RadioSettingsDialogState(); +} + +class _RadioSettingsDialogState extends State { + final _frequencyController = TextEditingController(); + LoRaBandwidth _bandwidth = LoRaBandwidth.bw125; + LoRaSpreadingFactor _spreadingFactor = LoRaSpreadingFactor.sf7; + LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5; + final _txPowerController = TextEditingController(text: '20'); + bool _clientRepeat = false; + int? _selectedPresetIndex; + _RadioSettingsSnapshot? _lastNonRepeatSnapshot; + String? _frequencyError; + String? _txPowerError; + + AppDebugLogService get _appLog => + Provider.of(context, listen: false); + + @override + void initState() { + super.initState(); + + // Populate with current settings if available + if (widget.connector.currentFreqHz != null) { + _frequencyController.text = (widget.connector.currentFreqHz! / 1000.0) + .toStringAsFixed(3); + } else { + _frequencyController.text = '915.0'; + } + + if (widget.connector.currentBwHz != null) { + // Find matching bandwidth enum + final bwValue = widget.connector.currentBwHz!; + for (var bw in LoRaBandwidth.values) { + if (bw.hz == bwValue) { + _bandwidth = bw; + break; + } + } + } + + if (widget.connector.currentSf != null) { + // Find matching spreading factor enum + final sfValue = widget.connector.currentSf!; + for (var sf in LoRaSpreadingFactor.values) { + if (sf.value == sfValue) { + _spreadingFactor = sf; + break; + } + } + } + + if (widget.connector.currentCr != null) { + // Find matching coding rate enum + final crValue = _toUiCodingRate(widget.connector.currentCr!); + for (var cr in LoRaCodingRate.values) { + if (cr.value == crValue) { + _codingRate = cr; + break; + } + } + } + + if (widget.connector.currentTxPower != null) { + _txPowerController.text = widget.connector.currentTxPower.toString(); + } + + _clientRepeat = widget.connector.clientRepeat ?? false; + _selectedPresetIndex = _findMatchingPresetIndex(); + if (_clientRepeat) { + _lastNonRepeatSnapshot = + _sessionRememberedNonRepeatSnapshot() ?? + _inferNonRepeatSnapshotForRepeatEnabled(); + _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( + _lastNonRepeatSnapshot!, + ); + } else { + _lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection(); + } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _logRadioSettingsState('Dialog initialized'); + }); + } + + @override + void dispose() { + _frequencyController.dispose(); + _txPowerController.dispose(); + super.dispose(); + } + + void _applyPreset(int index) { + setState(() { + _applyPresetState(index); + }); + _logRadioSettingsState( + 'Applied preset ${RadioSettings.presets[index].$1} (#$index)', + ); + } + + int? _findMatchingPresetIndex() { + return _findMatchingPresetIndexForSnapshot(_currentSnapshot()); + } + + int? _findMatchingPresetIndexForSnapshot(_RadioSettingsSnapshot snapshot) { + for (final i in _visiblePresetIndexes()) { + final preset = RadioSettings.presets[i].$2; + if (preset.frequencyHz == snapshot.frequencyHz && + preset.bandwidth == snapshot.bandwidth && + preset.spreadingFactor == snapshot.spreadingFactor && + preset.codingRate == snapshot.codingRate) { + return i; + } + } + return null; + } + + Iterable _visiblePresetIndexes() sync* { + for (var i = 0; i < RadioSettings.presets.length; i++) { + if (_isOffGridPresetIndex(i)) { + continue; + } + yield i; + } + } + + _RadioSettingsSnapshot _currentSnapshot() { + final frequencyMHz = double.tryParse(_frequencyController.text) ?? 915.0; + final txPowerDbm = int.tryParse(_txPowerController.text) ?? 20; + return _RadioSettingsSnapshot( + frequencyMHz: frequencyMHz, + bandwidth: _bandwidth, + spreadingFactor: _spreadingFactor, + codingRate: _codingRate, + txPowerDbm: txPowerDbm, + ); + } + + bool _isOffGridPresetIndex(int? index) { + if (index == null) return false; + return RadioSettings.presets[index].$1.startsWith('Off-Grid '); + } + + double _offGridFrequencyForBaseFrequency(double baseFrequencyMHz) { + final baseKHz = (baseFrequencyMHz * 1000).round(); + final ranges = widget.connector.allowedRepeatFreqRanges; + final candidates = ranges == null || ranges.isEmpty + ? _defaultRepeatFreqsKHz + : {for (final r in ranges) baseKHz.clamp(r.lowKHz, r.highKHz)}; + final closestKHz = candidates.reduce( + (a, b) => (a - baseKHz).abs() <= (b - baseKHz).abs() ? a : b, + ); + return closestKHz / 1000.0; + } + + double _normalFrequencyForBand(double frequencyMHz) { + if (frequencyMHz < 500) return 433.650; + if (frequencyMHz < 900) return 869.432; + return 915.8; + } + + _RadioSettingsSnapshot _fallbackNonRepeatSnapshot( + double currentFrequencyMHz, + ) { + return _RadioSettingsSnapshot( + frequencyMHz: _normalFrequencyForBand(currentFrequencyMHz), + bandwidth: _bandwidth, + spreadingFactor: _spreadingFactor, + codingRate: _codingRate, + txPowerDbm: int.tryParse(_txPowerController.text) ?? 20, + ); + } + + _RadioSettingsSnapshot _nonRepeatSnapshotForCurrentSelection() { + final current = _currentSnapshot(); + if (!_isOffGridPresetIndex(_selectedPresetIndex)) { + return current; + } + return _fallbackNonRepeatSnapshot(current.frequencyMHz); + } + + _RadioSettingsSnapshot? _sessionRememberedNonRepeatSnapshot() { + final snapshot = widget.connector.rememberedNonRepeatRadioState; + if (snapshot == null) return null; + return _RadioSettingsSnapshot.fromMeshCoreSnapshot(snapshot); + } + + _RadioSettingsSnapshot _inferNonRepeatSnapshotForRepeatEnabled() { + final current = _currentSnapshot(); + for (final i in _visiblePresetIndexes()) { + final preset = RadioSettings.presets[i].$2; + final offGridFreqHz = + (_offGridFrequencyForBaseFrequency(preset.frequencyMHz) * 1000) + .round(); + if (offGridFreqHz == current.frequencyHz && + preset.bandwidth == current.bandwidth && + preset.spreadingFactor == current.spreadingFactor && + preset.codingRate == current.codingRate) { + return _RadioSettingsSnapshot( + frequencyMHz: preset.frequencyMHz, + bandwidth: preset.bandwidth, + spreadingFactor: preset.spreadingFactor, + codingRate: preset.codingRate, + txPowerDbm: current.txPowerDbm, + ); + } + } + return _fallbackNonRepeatSnapshot(current.frequencyMHz); + } + + void _applySnapshot(_RadioSettingsSnapshot snapshot) { + _frequencyController.text = snapshot.frequencyMHz.toStringAsFixed(3); + _bandwidth = snapshot.bandwidth; + _spreadingFactor = snapshot.spreadingFactor; + _codingRate = snapshot.codingRate; + _txPowerController.text = snapshot.txPowerDbm.toString(); + } + + void _applyPresetState(int index) { + final preset = RadioSettings.presets[index].$2; + final baseSnapshot = _RadioSettingsSnapshot( + frequencyMHz: preset.frequencyMHz, + bandwidth: preset.bandwidth, + spreadingFactor: preset.spreadingFactor, + codingRate: preset.codingRate, + txPowerDbm: preset.txPowerDbm, + ); + final frequencyMHz = _clientRepeat + ? _offGridFrequencyForBaseFrequency(baseSnapshot.frequencyMHz) + : baseSnapshot.frequencyMHz; + _frequencyController.text = frequencyMHz.toString(); + _bandwidth = preset.bandwidth; + _spreadingFactor = preset.spreadingFactor; + _codingRate = preset.codingRate; + _txPowerController.text = preset.txPowerDbm.toString(); + _selectedPresetIndex = index; + _lastNonRepeatSnapshot = baseSnapshot; + // Programmatic writes skip TextField.onChanged, so clear any stale + // frequency/TX errors here or Save stays disabled. + _validateFields(); + } + + void _syncPresetSelection() { + final previousPresetIndex = _selectedPresetIndex; + final previousLastNonRepeat = _lastNonRepeatSnapshot; + if (_clientRepeat) { + final baseSnapshot = + previousLastNonRepeat ?? _inferNonRepeatSnapshotForRepeatEnabled(); + if (_bandwidth != baseSnapshot.bandwidth || + _spreadingFactor != baseSnapshot.spreadingFactor || + _codingRate != baseSnapshot.codingRate || + (int.tryParse(_txPowerController.text) ?? 20) != + baseSnapshot.txPowerDbm) { + _lastNonRepeatSnapshot = _RadioSettingsSnapshot( + frequencyMHz: baseSnapshot.frequencyMHz, + bandwidth: _bandwidth, + spreadingFactor: _spreadingFactor, + codingRate: _codingRate, + txPowerDbm: int.tryParse(_txPowerController.text) ?? 20, + ); + } + _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( + _lastNonRepeatSnapshot ?? baseSnapshot, + ); + if (previousPresetIndex != _selectedPresetIndex || + previousLastNonRepeat != _lastNonRepeatSnapshot) { + _logRadioSettingsState( + 'Preset match updated while repeat enabled: ${_presetLabel(previousPresetIndex)} -> ${_presetLabel(_selectedPresetIndex)}', + ); + } + return; + } + _lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection(); + _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( + _lastNonRepeatSnapshot!, + ); + if (previousPresetIndex != _selectedPresetIndex || + previousLastNonRepeat != _lastNonRepeatSnapshot) { + _logRadioSettingsState( + 'Preset sync updated state from ${_presetLabel(previousPresetIndex)} to ${_presetLabel(_selectedPresetIndex)}', + ); + } + } + + void _handleManualSettingsChanged(String source) { + _logRadioSettingsState('Manual settings edit: $source'); + setState(() { + _validateFields(); + _syncPresetSelection(); + }); + } + + void _validateFields() { + final l10n = context.l10n; + final freqMHz = double.tryParse(_frequencyController.text); + _frequencyError = (freqMHz == null || freqMHz < 150 || freqMHz > 2500) + ? l10n.settings_frequencyInvalid + : null; + + final maxTxPower = widget.connector.maxTxPower ?? 22; + final txPower = int.tryParse(_txPowerController.text); + _txPowerError = + (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) + ? l10n.settings_txPowerInvalidRange(_minTxPowerDbm, maxTxPower) + : null; + } + + void _handleClientRepeatChanged(bool enabled) { + _logRadioSettingsState( + 'Off-grid repeat toggle requested: $_clientRepeat -> $enabled', + ); + setState(() { + final currentSnapshot = _currentSnapshot(); + if (enabled) { + if (!_clientRepeat) { + _syncPresetSelection(); + } + final baseSnapshot = _lastNonRepeatSnapshot ?? currentSnapshot; + _clientRepeat = true; + _frequencyController.text = _offGridFrequencyForBaseFrequency( + baseSnapshot.frequencyMHz, + ).toStringAsFixed(3); + _validateFields(); + return; + } + + _clientRepeat = false; + _applySnapshot( + _lastNonRepeatSnapshot ?? + _fallbackNonRepeatSnapshot(currentSnapshot.frequencyMHz), + ); + _validateFields(); + _syncPresetSelection(); + }); + _logRadioSettingsState('Off-grid repeat toggle applied'); + } + + Future _saveSettings() async { + final l10n = context.l10n; + final freqMHz = double.tryParse(_frequencyController.text); + final txPower = int.tryParse(_txPowerController.text); + + if (freqMHz == null || freqMHz < 150 || freqMHz > 2500) { + showDismissibleSnackBar( + context, + content: Text(l10n.settings_frequencyInvalid), + ); + return; + } + + final maxTxPower = widget.connector.maxTxPower ?? 22; + if (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) { + showDismissibleSnackBar( + context, + content: Text( + l10n.settings_txPowerInvalidRange(_minTxPowerDbm, maxTxPower), + ), + ); + return; + } + + final freqHz = (freqMHz * 1000).round(); + final bwHz = _bandwidth.hz; + final sf = _spreadingFactor.value; + final cr = _codingRate.value; + + // if the client repeat isnt null then we know its supported + //otherwise we leave it out of the frame to avoid accidentally enabling + final knownRepeat = widget.connector.clientRepeat != null; + + if (knownRepeat) { + if (_clientRepeat && !_isAllowedRepeatFreqKHz(widget.connector, freqHz)) { + showDismissibleSnackBar( + context, + content: Text(l10n.settings_clientRepeatFreqWarning), + ); + return; + } + } + + try { + _logRadioSettingsState('Saving radio settings'); + final accepted = await widget.connector.setRadioParams( + freqHz, + bwHz, + sf, + cr, + clientRepeat: knownRepeat ? _clientRepeat : null, + ); + if (!accepted) { + _logRadioSettingsState('Radio rejected requested settings'); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_radioSettingsNotApplied), + ); + return; + } + await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); + final selfInfo = widget.connector.receivedFrames + .firstWhere((f) => f.isNotEmpty && f[0] == respCodeSelfInfo) + .timeout(const Duration(seconds: 5)); + await widget.connector.refreshDeviceInfo(); + final applied = await selfInfo.then( + (_) => _deviceMatches( + freqHz: freqHz, + bwHz: bwHz, + sf: sf, + cr: cr, + txPower: txPower, + clientRepeat: knownRepeat ? _clientRepeat : null, + ), + onError: (_) => true, + ); + if (!applied) { + _logRadioSettingsState('Radio did not apply requested settings'); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_radioSettingsNotApplied), + ); + return; + } + final rememberedSnapshot = _clientRepeat + ? _lastNonRepeatSnapshot + : _currentSnapshot(); + if (rememberedSnapshot != null) { + widget.connector.rememberNonRepeatRadioState( + rememberedSnapshot.toMeshCoreSnapshot(), + ); + } + + if (!mounted) return; + _logRadioSettingsState('Radio settings saved successfully'); + showDismissibleSnackBar( + context, + content: Text(l10n.settings_radioSettingsUpdated), + ); + Navigator.pop(context); + } catch (e) { + _appLog.warn('Radio settings save failed: $e', tag: 'RadioSettings'); + if (!mounted) return; + // Keep the dialog open, like the rejected/not-applied paths, so the + // user's edits survive a transient failure and can be retried. + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + } + } + + bool _deviceMatches({ + required int freqHz, + required int bwHz, + required int sf, + required int cr, + required int txPower, + required bool? clientRepeat, + }) { + final c = widget.connector; + // Firmware stores freq/bw as float MHz/kHz, so allow 1 unit of rounding. + return c.currentFreqHz != null && + (c.currentFreqHz! - freqHz).abs() <= 1 && + c.currentBwHz != null && + (c.currentBwHz! - bwHz).abs() <= 1 && + c.currentSf == sf && + c.currentCr != null && + _toUiCodingRate(c.currentCr!) == cr && + c.currentTxPower == txPower && + (clientRepeat == null || c.clientRepeat == clientRepeat); + } + + String _presetLabel(int? index) { + if (index == null) { + return 'custom'; + } + return '${RadioSettings.presets[index].$1} (#$index)'; + } + + String _formatSnapshot(_RadioSettingsSnapshot? snapshot) { + if (snapshot == null) { + return 'null'; + } + return '${snapshot.frequencyMHz.toStringAsFixed(3)}MHz/' + '${snapshot.bandwidth.label}/' + '${snapshot.spreadingFactor.label}/' + '${snapshot.codingRate.label}/' + '${snapshot.txPowerDbm}dBm'; + } + + void _logRadioSettingsState(String message) { + if (!kDebugMode) return; + _appLog.info( + '$message | ' + 'freq=${_frequencyController.text}MHz ' + 'bw=${_bandwidth.label} ' + 'sf=${_spreadingFactor.label} ' + 'cr=${_codingRate.label} ' + 'tx=${_txPowerController.text}dBm ' + 'repeat=$_clientRepeat ' + 'preset=${_presetLabel(_selectedPresetIndex)} ' + 'lastNonRepeat=${_formatSnapshot(_lastNonRepeatSnapshot)}', + tag: 'RadioSettings', + ); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AlertDialog( + title: Text(l10n.settings_radioSettings), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + DropdownButtonFormField( + key: ValueKey(_selectedPresetIndex), + initialValue: _selectedPresetIndex ?? -1, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.settings_presets, + border: const OutlineInputBorder(), + ), + items: [ + if (_selectedPresetIndex == null) + DropdownMenuItem( + value: -1, + child: Text(l10n.settings_presetCustom), + ), + for (final i in _visiblePresetIndexes()) + DropdownMenuItem( + value: i, + child: Text( + RadioSettings.presets[i].$1, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + onChanged: (index) { + if (index != null && index >= 0) { + _applyPreset(index); + } + }, + ), + const SizedBox(height: 16), + TextField( + controller: _frequencyController, + onChanged: (_) => _handleManualSettingsChanged('frequency'), + decoration: InputDecoration( + labelText: l10n.settings_frequency, + border: const OutlineInputBorder(), + helperText: _clientRepeat + ? l10n.settings_clientRepeatFrequencyNote( + _frequencyController.text, + ) + : l10n.settings_frequencyHelper, + errorText: _frequencyError, + ), + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + ), + const SizedBox(height: 16), + DropdownButtonFormField( + initialValue: _bandwidth, + decoration: InputDecoration( + labelText: l10n.settings_bandwidth, + border: const OutlineInputBorder(), + ), + items: LoRaBandwidth.values + .map( + (bw) => DropdownMenuItem(value: bw, child: Text(bw.label)), + ) + .toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _bandwidth = value; + _syncPresetSelection(); + }); + _logRadioSettingsState('Manual settings edit: bandwidth'); + } + }, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + initialValue: _spreadingFactor, + decoration: InputDecoration( + labelText: l10n.settings_spreadingFactor, + border: const OutlineInputBorder(), + ), + items: LoRaSpreadingFactor.values + .map( + (sf) => DropdownMenuItem(value: sf, child: Text(sf.label)), + ) + .toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _spreadingFactor = value; + _syncPresetSelection(); + }); + _logRadioSettingsState( + 'Manual settings edit: spreading factor', + ); + } + }, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + initialValue: _codingRate, + decoration: InputDecoration( + labelText: l10n.settings_codingRate, + border: const OutlineInputBorder(), + ), + items: LoRaCodingRate.values + .map( + (cr) => DropdownMenuItem(value: cr, child: Text(cr.label)), + ) + .toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _codingRate = value; + _syncPresetSelection(); + }); + _logRadioSettingsState('Manual settings edit: coding rate'); + } + }, + ), + const SizedBox(height: 16), + TextField( + controller: _txPowerController, + onChanged: (_) => _handleManualSettingsChanged('tx power'), + decoration: InputDecoration( + labelText: l10n.settings_txPower, + border: const OutlineInputBorder(), + helperText: l10n.settings_txPowerRangeHelper( + _minTxPowerDbm, + widget.connector.maxTxPower ?? 22, + ), + errorText: _txPowerError, + ), + keyboardType: TextInputType.number, + ), + if (widget.connector.clientRepeat != null) ...[ + const SizedBox(height: 16), + SwitchListTile( + title: Text(l10n.settings_clientRepeat), + subtitle: Text(l10n.settings_clientRepeatSubtitle), + value: _clientRepeat, + onChanged: _handleClientRepeatChanged, + contentPadding: EdgeInsets.zero, + ), + ], + const SizedBox(height: 16), + Text( + l10n.settings_radioMatchWarning, + style: Theme.of(context).textTheme.bodyMedium, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: (_frequencyError != null || _txPowerError != null) + ? null + : _saveSettings, + child: Text(l10n.common_save), + ), + ], + ); + } +} + +class _RadioSettingsSnapshot { + final double frequencyMHz; + final LoRaBandwidth bandwidth; + final LoRaSpreadingFactor spreadingFactor; + final LoRaCodingRate codingRate; + final int txPowerDbm; + + const _RadioSettingsSnapshot({ + required this.frequencyMHz, + required this.bandwidth, + required this.spreadingFactor, + required this.codingRate, + required this.txPowerDbm, + }); + + /// Frequency in integer Hz — avoids floating-point comparison issues. + int get frequencyHz => (frequencyMHz * 1000).round(); + + /// Convert from the connector's raw-int snapshot to UI-enum snapshot. + static _RadioSettingsSnapshot? fromMeshCoreSnapshot( + MeshCoreRadioStateSnapshot snapshot, + ) { + final bw = LoRaBandwidth.values + .where((b) => b.hz == snapshot.bwHz) + .firstOrNull; + final sf = LoRaSpreadingFactor.values + .where((s) => s.value == snapshot.sf) + .firstOrNull; + final cr = LoRaCodingRate.values + .where((c) => c.value == _toUiCodingRate(snapshot.cr)) + .firstOrNull; + if (bw == null || sf == null || cr == null) return null; + return _RadioSettingsSnapshot( + frequencyMHz: snapshot.freqHz / 1000.0, + bandwidth: bw, + spreadingFactor: sf, + codingRate: cr, + txPowerDbm: snapshot.txPowerDbm, + ); + } + + /// Convert back to the connector's raw-int snapshot. + MeshCoreRadioStateSnapshot toMeshCoreSnapshot() { + return MeshCoreRadioStateSnapshot( + freqHz: frequencyHz, + bwHz: bandwidth.hz, + sf: spreadingFactor.value, + cr: codingRate.value, + txPowerDbm: txPowerDbm, + ); + } + + @override + bool operator ==(Object other) { + return other is _RadioSettingsSnapshot && + frequencyHz == other.frequencyHz && + bandwidth == other.bandwidth && + spreadingFactor == other.spreadingFactor && + codingRate == other.codingRate && + txPowerDbm == other.txPowerDbm; + } + + @override + int get hashCode => Object.hash( + frequencyHz, + bandwidth, + spreadingFactor, + codingRate, + txPowerDbm, + ); +} diff --git a/lib/widgets/reaction_chips.dart b/lib/widgets/reaction_chips.dart new file mode 100644 index 00000000..c7f2d39d --- /dev/null +++ b/lib/widgets/reaction_chips.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; + +import '../l10n/l10n.dart'; +import '../models/message.dart'; +import '../theme/mesh_theme.dart'; + +/// The emoji reaction pills under a chat bubble, shared by the direct and +/// channel chat screens. +/// +/// [statuses] carries per-emoji send state for reactions this device sent +/// (direct chats only): pending chips are dimmed with a spinner and failed +/// chips become a retry button with a full-size tap target. +class ReactionChips extends StatelessWidget { + final Map> reactions; + final Map statuses; + + /// Called when a chip that is not in the failed state is tapped. + final ValueChanged? onTap; + + /// Called when a failed chip is tapped. + final ValueChanged? onRetry; + + const ReactionChips({ + super.key, + required this.reactions, + this.statuses = const {}, + this.onTap, + this.onRetry, + }); + + @override + Widget build(BuildContext context) { + return Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + for (final entry in reactions.entries) + _ReactionChip( + emoji: entry.key, + count: entry.value.length, + status: statuses[entry.key], + onTap: onTap, + onRetry: onRetry, + ), + ], + ); + } +} + +class _ReactionChip extends StatelessWidget { + final String emoji; + final int count; + final MessageStatus? status; + final ValueChanged? onTap; + final ValueChanged? onRetry; + + const _ReactionChip({ + required this.emoji, + required this.count, + required this.status, + required this.onTap, + required this.onRetry, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final isPending = + status == MessageStatus.pending || status == MessageStatus.sent; + final isFailed = status == MessageStatus.failed; + final VoidCallback? handler = isFailed + ? (onRetry == null ? null : () => onRetry!(emoji)) + : (onTap == null ? null : () => onTap!(emoji)); + final shape = RoundedRectangleBorder( + borderRadius: BorderRadius.circular(MeshRadii.pill), + side: BorderSide( + color: isFailed ? scheme.error : scheme.outlineVariant, + width: 1, + ), + ); + + Widget content = Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + emoji, + style: MeshTheme.emoji(fontSize: 16), + textHeightBehavior: const TextHeightBehavior( + applyHeightToFirstAscent: false, + applyHeightToLastDescent: false, + ), + ), + if (count > 1) ...[ + const SizedBox(width: 4), + Text( + '$count', + style: MeshTheme.mono( + fontSize: 12, + fontWeight: FontWeight.w700, + color: scheme.onSurface, + ), + ), + ], + if (isPending) ...[ + const SizedBox(width: 4), + SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator( + strokeWidth: 1.5, + color: scheme.primary, + ), + ), + ], + if (isFailed) ...[ + const SizedBox(width: 6), + Icon(Icons.replay, size: 18, color: scheme.error), + ], + ], + ); + + content = Padding( + padding: EdgeInsets.symmetric(horizontal: isFailed ? 12 : 8, vertical: 4), + child: content, + ); + if (isFailed) { + // A failed reaction is a retry button: give it a full tap target. + content = ConstrainedBox( + constraints: const BoxConstraints(minHeight: 40, minWidth: 40), + child: Center(widthFactor: 1, heightFactor: 1, child: content), + ); + } + + Widget chip = Material( + color: isFailed ? scheme.errorContainer : scheme.surfaceContainerHigh, + shape: shape, + clipBehavior: Clip.antiAlias, + child: InkWell(onTap: handler, child: content), + ); + if (isFailed && onRetry != null) { + chip = Semantics( + button: true, + label: context.l10n.common_retry, + child: chip, + ); + } + return Opacity(opacity: isPending ? 0.5 : 1.0, child: chip); + } +} diff --git a/lib/widgets/received_image_message.dart b/lib/widgets/received_image_message.dart index 3bc5944f..6507bc71 100644 --- a/lib/widgets/received_image_message.dart +++ b/lib/widgets/received_image_message.dart @@ -457,7 +457,7 @@ class _ReceivedImageMessageState extends State { textAlign: TextAlign.center, maxLines: 3, overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: 11, color: color ?? widget.fallbackTextColor), + style: TextStyle(fontSize: 12, color: color ?? widget.fallbackTextColor), ); } @@ -547,20 +547,22 @@ class _SyntheticBanner extends StatelessWidget { @override Widget build(BuildContext context) { return Container( - height: 18, + height: 20, alignment: Alignment.center, color: Colors.black.withValues(alpha: 0.62), padding: const EdgeInsets.symmetric(horizontal: 4), child: Row( mainAxisSize: MainAxisSize.min, children: [ - const Icon(Icons.auto_awesome, size: 11, color: Colors.white), + const Icon(Icons.auto_awesome, size: 12, color: Colors.white), const SizedBox(width: 4), - Text( - _kSyntheticBadge, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle(fontSize: 10, color: Colors.white), + Flexible( + child: Text( + _kSyntheticBadge, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: Colors.white), + ), ), ], ), @@ -590,7 +592,7 @@ class _SyntheticCaption extends StatelessWidget { // than none — it clips exactly where the warning was going. softWrap: true, style: TextStyle( - fontSize: 10, + fontSize: 12, color: onDark ? Colors.white70 : Theme.of(context).colorScheme.onSurfaceVariant, diff --git a/lib/widgets/repeater_login_dialog.dart b/lib/widgets/repeater_login_dialog.dart index ff9e8197..8e449550 100644 --- a/lib/widgets/repeater_login_dialog.dart +++ b/lib/widgets/repeater_login_dialog.dart @@ -423,7 +423,7 @@ class _RepeaterLoginDialogState extends State { l10n.login_routing, style: MeshTheme.accentLabel( color: scheme.onSurfaceVariant, - fontSize: 11, + fontSize: 13, ), ), const Spacer(), @@ -501,7 +501,7 @@ class _RepeaterLoginDialogState extends State { pathHashByteWidth: connector.pathHashByteWidth, ), style: TextStyle( - fontSize: 11, + fontSize: 13, color: scheme.onSurfaceVariant, ), ), diff --git a/lib/widgets/room_login_dialog.dart b/lib/widgets/room_login_dialog.dart index 428ae351..2ebefd50 100644 --- a/lib/widgets/room_login_dialog.dart +++ b/lib/widgets/room_login_dialog.dart @@ -355,7 +355,7 @@ class _RoomLoginDialogState extends State { l10n.login_routing, style: MeshTheme.accentLabel( color: scheme.onSurfaceVariant, - fontSize: 11, + fontSize: 12, ), ), const Spacer(), @@ -433,7 +433,7 @@ class _RoomLoginDialogState extends State { pathHashByteWidth: connector.pathHashByteWidth, ), style: TextStyle( - fontSize: 11, + fontSize: 12, color: scheme.onSurfaceVariant, ), ), diff --git a/lib/widgets/routing_sheet.dart b/lib/widgets/routing_sheet.dart index 3934a7df..21b98920 100644 --- a/lib/widgets/routing_sheet.dart +++ b/lib/widgets/routing_sheet.dart @@ -492,7 +492,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { title: Text(l10n.routing_floodDelivery), subtitle: Text( _floodStatsLine(context, stats), - style: const TextStyle(fontSize: 11), + style: const TextStyle(fontSize: 12), ), trailing: mode == _RoutingMode.flood ? Icon( @@ -596,7 +596,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text( '$line1\n${line2Parts.join(' • ')}', - style: const TextStyle(fontSize: 11), + style: const TextStyle(fontSize: 12), ), isThreeLine: true, trailing: Row( diff --git a/lib/widgets/snr_indicator.dart b/lib/widgets/snr_indicator.dart index f485e0c0..d07e2bba 100644 --- a/lib/widgets/snr_indicator.dart +++ b/lib/widgets/snr_indicator.dart @@ -313,7 +313,7 @@ class _SNRIndicatorState extends State { Text( '${repeater.snr.toStringAsFixed(1)} dB • ${_formatLastUpdated(repeater.lastUpdated)}', style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, color: colorScheme.onSurfaceVariant, ), ), diff --git a/lib/widgets/telemetry_location_map.dart b/lib/widgets/telemetry_location_map.dart index 537867c5..b95c20b0 100644 --- a/lib/widgets/telemetry_location_map.dart +++ b/lib/widgets/telemetry_location_map.dart @@ -240,7 +240,7 @@ class _TelemetryLocationMapState extends State { overflow: TextOverflow.ellipsis, style: const TextStyle( color: Colors.white, - fontSize: 11, + fontSize: 12, fontWeight: FontWeight.w500, ), ), diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart new file mode 100644 index 00000000..dd8c6ac5 --- /dev/null +++ b/lib/widgets/translation_settings_section.dart @@ -0,0 +1,611 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/translation_support.dart'; +import '../services/app_settings_service.dart'; +import '../services/translation_service.dart'; +import '../theme/mesh_theme.dart'; +import 'mesh_nav_tile.dart'; + +/// [TranslationService] publishes this as `downloadFileName` while it merges +/// downloaded chunks (see translation_service.dart). The service owns the +/// value and exposes no separate state flag, so it is matched here, in one +/// place, until the service grows a proper "merging" getter. +const String _mergingChunksFileName = 'Merging chunks...'; + +/// On-device translation settings: feature toggles, target language, model +/// selection, model downloads and the downloaded-model list. +/// +/// Watches only [AppSettingsService] and [TranslationService], so download +/// progress ticks rebuild this card and nothing else on the settings screen. +class TranslationSettingsSection extends StatelessWidget { + const TranslationSettingsSection({super.key}); + + @override + Widget build(BuildContext context) { + final settingsService = context.watch(); + final translationService = context.watch(); + final l10n = context.l10n; + final settings = settingsService.settings; + final translationEnabled = settings.translationEnabled; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final textTheme = theme.textTheme; + final disabledColor = translationEnabled ? null : theme.disabledColor; + const tilePadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SwitchListTile( + contentPadding: tilePadding, + secondary: const Icon(Icons.translate, size: 24), + title: Text(l10n.translation_enableTitle), + subtitle: Text(l10n.translation_enableSubtitle), + value: settings.translationEnabled, + onChanged: settingsService.setTranslationEnabled, + ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: tilePadding, + secondary: Icon( + Icons.auto_awesome_outlined, + size: 24, + color: disabledColor, + ), + title: Text( + l10n.translation_autoIncomingTitle, + style: TextStyle(color: disabledColor), + ), + subtitle: Text( + l10n.translation_autoIncomingSubtitle, + style: TextStyle(color: disabledColor), + ), + value: settings.autoTranslateIncomingMessages, + onChanged: translationEnabled + ? settingsService.setAutoTranslateIncomingMessages + : null, + ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: tilePadding, + secondary: Icon(Icons.outgoing_mail, size: 24, color: disabledColor), + title: Text( + l10n.translation_composerTitle, + style: TextStyle(color: disabledColor), + ), + subtitle: Text( + l10n.translation_composerSubtitle, + style: TextStyle(color: disabledColor), + ), + value: settings.composerTranslationEnabled, + onChanged: translationEnabled + ? settingsService.setComposerTranslationEnabled + : null, + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.language, + title: l10n.translation_targetLanguage, + subtitle: _translationLanguageLabel( + context, + settings.translationTargetLanguageCode, + ), + onTap: () => _showTranslationLanguageDialog(context, settingsService), + ), + const Divider(height: 1, indent: 16), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: DropdownButtonFormField( + initialValue: settings.translationSelectedModelId, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.translation_downloadedModelLabel, + border: const OutlineInputBorder(), + ), + items: [ + for (final model in settings.translationDownloadedModels) + DropdownMenuItem( + value: model.id, + child: Text( + translationModelFriendlyName(model), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + onChanged: settings.translationDownloadedModels.isEmpty + ? null + : (value) { + settingsService.setTranslationSelectedModelId(value); + }, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: DropdownButtonFormField( + initialValue: null, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.translation_presetModelLabel, + border: const OutlineInputBorder(), + ), + items: [ + for (final preset in translationPresetModels) + DropdownMenuItem( + value: preset.sourceUrl, + child: Text( + translationModelFriendlyName(preset), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + onChanged: translationService.isBusy + ? null + : (value) async { + if (value == null) return; + final preset = translationPresetModels.firstWhere( + (entry) => entry.sourceUrl == value, + ); + await _downloadTranslationModel( + context, + translationService, + settingsService, + sourceUrl: preset.sourceUrl, + fileName: preset.name, + id: preset.id, + ); + }, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _TranslationUrlField( + initialValue: settings.translationModelSourceUrl ?? '', + onChanged: settingsService.setTranslationModelSourceUrl, + onDownload: translationService.isBusy + ? null + : (url) => _downloadTranslationModel( + context, + translationService, + settingsService, + sourceUrl: url, + ), + downloadLabel: translationService.isDownloading + ? l10n.translation_downloading + : translationService.isBusy + ? l10n.translation_working + : l10n.translation_downloadModel, + isDownloading: translationService.isDownloading, + onCancel: translationService.cancelDownload, + labelText: l10n.translation_manualUrlLabel, + stopLabel: l10n.translation_stop, + ), + if (translationService.isDownloading) ...[ + const SizedBox(height: 12), + ClipRRect( + borderRadius: BorderRadius.circular(2), + child: LinearProgressIndicator( + value: _isMerging(translationService) + ? null + : translationService.downloadProgress, + ), + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerLeft, + child: Text( + _downloadProgressLabel(context, translationService), + style: MeshTheme.mono( + fontSize: 14, + color: scheme.onSurfaceVariant, + ), + ), + ), + ], + if (settings.translationDownloadedModels.isNotEmpty) ...[ + const SizedBox(height: 16), + Align( + alignment: Alignment.centerLeft, + child: Text( + l10n.translation_downloadedModels, + style: textTheme.titleSmall, + ), + ), + const SizedBox(height: 8), + for (final model in settings.translationDownloadedModels) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Icon( + model.id == settings.translationSelectedModelId + ? Icons.check_circle + : Icons.memory_outlined, + size: 24, + color: model.id == settings.translationSelectedModelId + ? scheme.primary + : scheme.onSurfaceVariant, + ), + const SizedBox(width: 12), + Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(MeshRadii.xs), + onTap: () => settingsService + .setTranslationSelectedModelId(model.id), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + translationModelFriendlyName(model), + style: textTheme.bodyLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + Text( + _downloadedModelLabel(context, model), + style: MeshTheme.mono( + fontSize: 12, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + IconButton( + tooltip: l10n.translation_deleteModel, + onPressed: translationService.isBusy + ? null + : () => _deleteTranslationModel( + context, + translationService, + model, + ), + icon: const Icon(Icons.delete_outline), + ), + ], + ), + ), + ], + if (translationService.lastError != null) ...[ + const SizedBox(height: 8), + Text( + translationService.lastError!, + style: TextStyle(color: scheme.error), + ), + ], + ], + ), + ), + ], + ); + } + + static bool _isMerging(TranslationService service) => + service.downloadFileName == _mergingChunksFileName; + + void _showTranslationLanguageDialog( + BuildContext context, + AppSettingsService settingsService, + ) { + showDialog( + context: context, + builder: (context) => _TranslationLanguageDialogContent( + currentLanguageCode: + settingsService.settings.translationTargetLanguageCode, + onLanguageSelected: (value) { + settingsService.setTranslationTargetLanguageCode(value); + Navigator.pop(context); + }, + ), + ); + } + + Future _downloadTranslationModel( + BuildContext context, + TranslationService translationService, + AppSettingsService settingsService, { + required String sourceUrl, + String? fileName, + String? id, + }) async { + if (sourceUrl.isEmpty) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.translation_enterUrlFirst), + ); + return; + } + try { + await translationService.downloadModel( + sourceUrl: sourceUrl, + fileName: fileName, + id: id, + ); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.translation_modelDownloaded), + ); + await settingsService.setTranslationEnabled(true); + } on TranslationDownloadCancelled { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.translation_downloadStopped), + ); + } catch (error) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + context.l10n.translation_downloadFailed(error.toString()), + ), + ); + } + } + + String _translationLanguageLabel(BuildContext context, String? languageCode) { + if (languageCode == null || languageCode.isEmpty) { + return context.l10n.translation_useAppLanguage; + } + for (final option in supportedTranslationLanguages) { + if (option.code == languageCode) { + return option.label; + } + } + return languageCode.toUpperCase(); + } + + String _downloadProgressLabel( + BuildContext context, + TranslationService translationService, + ) { + final l10n = context.l10n; + if (_isMerging(translationService)) { + return l10n.translation_mergingChunks; + } + final fileName = + translationService.downloadFileName ?? + l10n.translation_defaultModelName; + final currentMb = translationService.downloadedBytes / (1024 * 1024); + final totalBytes = translationService.downloadTotalBytes; + if (totalBytes == null || totalBytes <= 0) { + return l10n.translation_downloadProgressBytes( + fileName, + currentMb.toStringAsFixed(1), + ); + } + final totalMb = totalBytes / (1024 * 1024); + final percent = ((translationService.downloadProgress ?? 0) * 100) + .toStringAsFixed(0); + return l10n.translation_downloadProgressTotal( + fileName, + currentMb.toStringAsFixed(1), + totalMb.toStringAsFixed(1), + percent, + ); + } + + Future _deleteTranslationModel( + BuildContext context, + TranslationService translationService, + TranslationModelRecord model, + ) async { + try { + await translationService.removeModel(model); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + context.l10n.appSettings_translationModelDeleted( + translationModelFriendlyName(model), + ), + ), + ); + } catch (error) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + context.l10n.appSettings_translationModelDeleteFailed('$error'), + ), + ); + } + } + + String _downloadedModelLabel( + BuildContext context, + TranslationModelRecord model, + ) { + final sizeMb = model.fileSizeBytes / (1024 * 1024); + final source = model.sourceUrl.isEmpty ? model.name : model.sourceUrl; + return context.l10n.translation_downloadedModelDetails( + sizeMb.toStringAsFixed(1), + source, + ); + } +} + +/// Owns the [TextEditingController] for the manual model URL field so it +/// survives rebuilds of the parent section. +class _TranslationUrlField extends StatefulWidget { + const _TranslationUrlField({ + required this.initialValue, + required this.onChanged, + required this.onDownload, + required this.downloadLabel, + required this.isDownloading, + required this.onCancel, + required this.labelText, + required this.stopLabel, + }); + + final String initialValue; + final ValueChanged onChanged; + final void Function(String url)? onDownload; + final String downloadLabel; + final bool isDownloading; + final VoidCallback onCancel; + final String labelText; + final String stopLabel; + + @override + State<_TranslationUrlField> createState() => _TranslationUrlFieldState(); +} + +class _TranslationUrlFieldState extends State<_TranslationUrlField> { + late final TextEditingController _controller; + + @override + void initState() { + super.initState(); + _controller = TextEditingController(text: widget.initialValue); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + TextField( + controller: _controller, + decoration: InputDecoration( + labelText: widget.labelText, + border: const OutlineInputBorder(), + ), + onChanged: widget.onChanged, + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: FilledButton.icon( + onPressed: widget.onDownload == null + ? null + : () => widget.onDownload!(_controller.text.trim()), + icon: const Icon(Icons.download), + label: Text(widget.downloadLabel), + ), + ), + if (widget.isDownloading) ...[ + const SizedBox(width: 8), + OutlinedButton.icon( + onPressed: widget.onCancel, + icon: const Icon(Icons.stop_circle_outlined), + label: Text(widget.stopLabel), + ), + ], + ], + ), + ], + ); + } +} + +/// Dialog content for choosing the translation target language. +/// Owns the search [TextEditingController] so it is properly disposed. +class _TranslationLanguageDialogContent extends StatefulWidget { + const _TranslationLanguageDialogContent({ + required this.currentLanguageCode, + required this.onLanguageSelected, + }); + + final String? currentLanguageCode; + final ValueChanged onLanguageSelected; + + @override + State<_TranslationLanguageDialogContent> createState() => + _TranslationLanguageDialogContentState(); +} + +class _TranslationLanguageDialogContentState + extends State<_TranslationLanguageDialogContent> { + late final TextEditingController _searchController; + List _filtered = supportedTranslationLanguages; + + @override + void initState() { + super.initState(); + _searchController = TextEditingController(); + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(context.l10n.translation_targetLanguage), + content: SizedBox( + width: 360, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: _searchController, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + border: OutlineInputBorder(), + ), + onChanged: (value) { + final normalized = value.trim().toLowerCase(); + setState(() { + _filtered = supportedTranslationLanguages.where((option) { + return option.label.toLowerCase().contains(normalized) || + option.code.toLowerCase().contains(normalized); + }).toList(); + }); + }, + ), + const SizedBox(height: 12), + Flexible( + child: RadioGroup( + groupValue: widget.currentLanguageCode, + onChanged: (value) { + widget.onLanguageSelected(value); + }, + child: ListView( + shrinkWrap: true, + children: [ + RadioListTile( + value: null, + title: Text(context.l10n.translation_useAppLanguage), + ), + for (final option in _filtered) + RadioListTile( + value: option.code, + title: Text(option.label), + subtitle: Text(option.code.toUpperCase()), + ), + ], + ), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(context.l10n.common_close), + ), + ], + ); + } +} diff --git a/lib/widgets/unread_badge.dart b/lib/widgets/unread_badge.dart index dd2e2ab3..33d8412c 100644 --- a/lib/widgets/unread_badge.dart +++ b/lib/widgets/unread_badge.dart @@ -21,7 +21,7 @@ class UnreadBadge extends StatelessWidget { child: Text( display, style: MeshTheme.mono( - fontSize: 11, + fontSize: 12, fontWeight: FontWeight.w700, color: Colors.white, ), diff --git a/lib/widgets/unread_divider.dart b/lib/widgets/unread_divider.dart index 4de05b32..bf069a7a 100644 --- a/lib/widgets/unread_divider.dart +++ b/lib/widgets/unread_divider.dart @@ -28,7 +28,7 @@ class UnreadDivider extends StatelessWidget { child: Text( context.l10n.chat_newMessages, style: MeshTheme.mono( - fontSize: 10.5, + fontSize: 12, fontWeight: FontWeight.w600, color: color, ), diff --git a/test/widgets/path_map_bottom_panel_test.dart b/test/widgets/path_map_bottom_panel_test.dart new file mode 100644 index 00000000..9efca127 --- /dev/null +++ b/test/widgets/path_map_bottom_panel_test.dart @@ -0,0 +1,144 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/path_playback.dart'; +import 'package:meshcore_open/widgets/path_map_scaffold.dart'; + +void main() { + for (final scenario in [ + ( + name: 'compact portrait', + size: const Size(320, 568), + scale: 1.0, + combined: false, + collapsed: false, + ), + ( + name: 'compact landscape', + size: const Size(568, 320), + scale: 1.0, + combined: false, + collapsed: false, + ), + ( + name: 'large text', + size: const Size(320, 568), + scale: 2.0, + combined: false, + collapsed: false, + ), + ( + name: 'combined paths', + size: const Size(320, 568), + scale: 1.0, + combined: true, + collapsed: false, + ), + ( + name: 'collapsed', + size: const Size(320, 568), + scale: 1.0, + combined: false, + collapsed: true, + ), + ]) { + testWidgets( + 'path panel fits ${scenario.name} and keeps content accessible', + (tester) async { + tester.view.physicalSize = scenario.size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final playback = PathPlaybackController(const TestVSync()); + addTearDown(playback.dispose); + var animationToggles = 0; + const hopListKey = ValueKey('hop-list'); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scenario.scale)), + child: child!, + ), + home: Scaffold( + body: Stack( + children: [ + PathMapBottomPanel( + header: const Text('3 hops (2.00 km)'), + combined: scenario.combined, + showInferredLegend: true, + collapsed: scenario.collapsed, + onToggleCollapsed: () {}, + playback: playback, + selected: null, + animationEnabled: true, + onToggleAnimation: () => animationToggles++, + followEnabled: false, + onToggleFollow: () {}, + showNoSelfGpsNote: true, + pathCount: scenario.combined ? 3 : 1, + hopRowCount: 3, + summary: scenario.combined + ? Column( + children: [ + for (var i = 1; i <= 3; i++) + SizedBox(height: 40, child: Text('Path $i')), + ], + ) + : null, + hopList: ListView( + key: hopListKey, + children: [ + for (var i = 1; i <= 3; i++) + SizedBox(height: 60, child: Text('Hop $i')), + ], + ), + ), + ], + ), + ), + ), + ); + expect(tester.takeException(), isNull); + + final animationButton = find.widgetWithIcon( + IconButton, + Icons.animation, + ); + await tester.ensureVisible(animationButton); + await tester.pumpAndSettle(); + await tester.tap(animationButton); + expect(animationToggles, 1); + + if (!scenario.collapsed) { + expect( + tester.getSize(find.byKey(hopListKey)).height, + greaterThanOrEqualTo(60), + ); + final l10n = AppLocalizations.of( + tester.element(find.byType(PathMapBottomPanel)), + ); + final gpsNote = find.text(l10n.pathMap_noSelfGpsFix); + await tester.ensureVisible(gpsNote); + await tester.pumpAndSettle(); + expect(gpsNote.hitTestable(), findsOneWidget); + await tester.scrollUntilVisible( + find.text('Hop 3'), + 60, + scrollable: find.descendant( + of: find.byKey(hopListKey), + matching: find.byType(Scrollable), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Hop 3').hitTestable(), findsOneWidget); + } + expect(tester.takeException(), isNull); + }, + ); + } +} From b18da94a16401f733444269c5ae5b567dd33a9fd Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 15:25:32 -0700 Subject: [PATCH 2/8] Clear unsaved-changes guard before popping on discard --- lib/screens/repeater_settings_screen.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index a277e4c6..7c4cdcd6 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -1487,6 +1487,9 @@ class _RepeaterSettingsScreenState extends State { if (choice == 'save') { await _saveSettings(); if (!mounted || _hasChanges) return; + } else { + // Drop the PopScope guard so the pop below can't re-trigger this dialog. + setState(() => _hasChanges = false); } Navigator.of(context).pop(); } From 679116ed031d0e7acfde60ac7ba7efc4457e548f Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 17:52:59 -0700 Subject: [PATCH 3/8] Key per-channel storage by PSK-derived channel ID Channel messages, settings, region, order and images were persisted by radio slot index, so a slot reused for a different channel inherited the old channel's history and settings (#359). - Channel.storageId: first 8 bytes of SHA-256("meshcore-channel:" + psk). - All per-channel stores key by channel ID; in-memory state stays by slot. - The connector keeps a slot -> channel ID map, diffs it against the saved map on every channel sync and reloads slots whose channel changed. - Queued channel frames wait until this session's map is confirmed. - One-shot per-radio migration from slot keys, using the cached channel list the legacy data was written under; rerun-safe if interrupted. - Deleting a channel clears its data; a channel removed elsewhere keeps its history and gets it back when re-added. A PSK edit keeps its place in the custom order. - Slots sharing a PSK share history and settings. - Image entries record their channel ID; a slot change resets that slot's in-progress reassembly. --- documentation/ble-protocol.md | 10 +- documentation/channels.md | 4 +- lib/connector/meshcore_connector.dart | 652 +++++++++++++++--- lib/main.dart | 25 +- lib/models/channel.dart | 19 + lib/models/channel_message.dart | 3 +- lib/screens/channel_chat_screen.dart | 12 +- lib/screens/channels_screen.dart | 67 +- lib/services/image_chunk_transport.dart | 32 + lib/services/received_image_store.dart | 53 +- lib/storage/channel_message_store.dart | 68 +- lib/storage/channel_order_store.dart | 39 +- lib/storage/channel_region_store.dart | 21 +- lib/storage/channel_settings_store.dart | 77 +-- lib/storage/channel_storage_migration.dart | 186 +++++ lib/storage/channel_store.dart | 33 + test/connector/channel_slot_map_test.dart | 346 ++++++++++ test/image_chunk_transport_test.dart | 34 + test/models/model_changes_test.dart | 5 +- test/models/received_at_test.dart | 10 +- test/services/received_image_store_test.dart | 56 +- test/storage/channel_storage_by_id_test.dart | 351 ++++++++++ test/storage/message_store_archive_test.dart | 25 +- test/storage/store_tolerant_parsing_test.dart | 6 +- 24 files changed, 1794 insertions(+), 340 deletions(-) create mode 100644 lib/storage/channel_storage_migration.dart create mode 100644 test/connector/channel_slot_map_test.dart create mode 100644 test/storage/channel_storage_by_id_test.dart diff --git a/documentation/ble-protocol.md b/documentation/ble-protocol.md index 8bd742ad..88f83dc3 100644 --- a/documentation/ble-protocol.md +++ b/documentation/ble-protocol.md @@ -198,13 +198,17 @@ UUID, name, 32-byte secret, hashtag channel list. Shared via QR code. Message/contact metadata and preferences use `SharedPreferences` (JSON-serialized); there is no SQLite database. Model bundles, received image bitstreams/reconstructions, and map caches use files. Region metadata is persisted with channel messages; older records without it load with a null region. +Per-channel data is keyed by a channel ID, not the radio slot: `` is the first 8 bytes of SHA-256(`"meshcore-channel:"` + PSK) as 16 hex characters, so a reused slot starts clean and a re-added channel gets its history back. Each channel sync saves the slot-to-ID map (`channel_slot_ids_`) and reloads any slot whose channel changed since the last connection; queued channel messages are not fetched until that map is confirmed. Older slot-keyed data is moved once per radio (`channel_storage_v2_`) using the cached channel list; slots with no cached PSK keep their old keys unread. + | Data | Storage Key Pattern | Scope | |---|---|---| | Contacts | `contacts` | Per device identity | | Messages | `messages_` | Per device + contact | -| Channel Messages | `channel_messages_` | Per device + channel | +| Channel Messages | `channel_messages__` | Per device + channel | | Channels | `channels` | Per device identity | -| Channel Order | `channel_order_` | Per device identity | +| Channel Order | `channel_order_` (list of channel IDs) | Per device identity | +| Channel Slot Map | `channel_slot_ids_` | Per device identity | +| Channel Settings | `channel_{smaz,cyr2lat,url_images}__`, `channel_cyr2lat__profile_` | Per device + channel | | Contact Groups | `contact_groups` | Per device identity | | Communities | `communities_v1` | Per device identity | | Unread Counts | `contact_unread_count` | Per device identity | @@ -212,7 +216,7 @@ Message/contact metadata and preferences use `SharedPreferences` (JSON-serialize | App Settings | `app_settings` | Global | | Path History | `path_history_` | Per contact | | Region Names | `regions` | Global | -| Channel Region | `channel_region_` | Per device + channel | +| Channel Region | `channel_region__` | Per device + channel | | Default Region | `default_region_` | Per device identity | ## Auto-Add Configuration Bitmask diff --git a/documentation/channels.md b/documentation/channels.md index b569f54b..2f4e55fa 100644 --- a/documentation/channels.md +++ b/documentation/channels.md @@ -63,7 +63,9 @@ Name limits count the `#` and any community prefix, so the name stored on the ra |---|---| | Edit | Change name, PSK (with a dice icon to generate a random PSK), SMAZ compression toggle (compresses outgoing messages to allow longer text within the byte limit), Cyr2Lat encoding toggle (transliterates Cyrillic to Latin for compatibility), or "Enable URL images" toggle (previews image links; requires internet) | | Mute / Unmute | Toggle push notification suppression for this channel | -| Delete | Remove the channel from the device (confirmation required) | +| Delete | Remove the channel from the device and delete its messages, settings, region and images (confirmation required) | + +Channel history and settings belong to the channel's key, not its slot on the radio. A slot reused for another channel (here or in another app) starts empty, editing a channel's PSK starts a fresh history, and adding a channel again with its old PSK brings its history back. ## Channel Chat diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index bf05ab44..bf4d7005 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -35,6 +35,7 @@ import '../services/image_chunk_transport.dart' respCodeChannelDataRecv, senderPrefixFromKey; import '../services/image_codec_service.dart'; +import '../services/received_image_store.dart'; import '../services/message_retry_service.dart'; import '../services/path_history_service.dart'; import '../services/app_settings_service.dart'; @@ -49,6 +50,7 @@ import '../storage/channel_message_store.dart'; import '../storage/channel_order_store.dart'; import '../storage/channel_settings_store.dart'; import '../storage/channel_region_store.dart'; +import '../storage/channel_storage_migration.dart'; import '../storage/channel_store.dart'; import '../storage/contact_discovery_store.dart'; import '../storage/contact_settings_store.dart'; @@ -310,6 +312,7 @@ class MeshCoreConnector extends ChangeNotifier { // frames (chunks of one image arrive in separate GRP_DATA frames, and via the // firmware offline queue they may be minutes apart). ImageChunkTransport? _imageTransport; + ReceivedImageStore? _receivedImageStore; void Function(ImageChunkOutcome outcome)? _onImageChunk; void Function(int senderPrefix)? _onImageSenderPrefix; // Intentionally global (not per-contact): tracks overall network activity. @@ -419,8 +422,25 @@ class MeshCoreConnector extends ChangeNotifier { // 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 = {}; + // A slot timed out in this sync pass (restored from cache or unconfirmed). + bool _channelSyncIncomplete = false; + int _channelMapSyncRetries = 0; + static const int _maxChannelMapSyncRetries = 2; + // Completes when the running channel sync has applied its slot map. + Completer? _channelSyncCompleter; static const int _maxChannelSyncRetries = 3; - static const int _channelSyncTimeoutMs = 2000; // 2 second timeout per channel + @visibleForTesting + int channelSyncTimeoutMs = 2000; // timeout per channel + // Slot -> Channel.storageId for the connected radio. Persisted data is + // keyed by channel ID while in-memory state stays keyed by slot; this map + // is the only bridge between them. Seeded from the saved map at SELF_INFO + // and replaced when a channel sync completes. + final Map _slotChannelIds = {}; + // Whether this session's channel sync has confirmed _slotChannelIds. + // Queued channel frames carry only a slot index, so they wait for it. + bool _channelMapConfirmed = false; + int _channelSessionGeneration = 0; + Future _channelStorageReady = Future.value(); static const Duration _batteryPollInterval = Duration(seconds: 120); // Services @@ -468,7 +488,7 @@ class MeshCoreConnector extends ChangeNotifier { final Map _pendingRepeaterAcks = {}; String? _activeContactKey; int? _activeChannelIndex; - List _channelOrder = []; + List _channelOrder = []; int _storageUsedKb = -1; int _storageTotalKb = -1; @@ -592,6 +612,13 @@ class MeshCoreConnector extends ChangeNotifier { bool get hasLoadedChannels => _hasLoadedChannels; Set get unconfirmedChannelSlots => Set.unmodifiable(_unconfirmedChannelSlots); + + /// [Channel.storageId] of the channel in radio slot [slot], as of the last + /// channel sync, or null for an empty or unknown slot. + String? channelIdForSlot(int slot) => _slotChannelIds[slot]; + + @visibleForTesting + bool get channelMapConfirmed => _channelMapConfirmed; Stream get receivedFrames => _receivedFramesController.stream; Uint8List? get selfPublicKey => _selfPublicKey; String get selfPublicKeyHex => pubKeyToHex(_selfPublicKey ?? Uint8List(0)); @@ -873,20 +900,60 @@ class MeshCoreConnector extends ChangeNotifier { } List getChannelMessages(Channel channel) { - return _channelMessages[channel.index] ?? []; + return _channelMessages[_canonicalSlot(channel.index)] ?? []; } Future deleteChannelMessage(ChannelMessage message) async { final channelIndex = message.channelIndex; if (channelIndex == null) return; - final messages = _channelMessages[channelIndex]; + final slot = _canonicalSlot(channelIndex); + final messages = _channelMessages[slot]; if (messages == null) return; final removed = messages.remove(message); if (!removed) return; - await _channelMessageStore.saveChannelMessages(channelIndex, messages); + await _saveChannelMessages(slot, messages); notifyListeners(); } + /// Storage ID for [slot], or null (logged) when the slot has none, in which + /// case the caller skips persistence. + String? _channelIdForSlot(int slot) { + final id = _slotChannelIds[slot]; + if (id == null) { + debugPrint( + '[ChannelStorage] Slot $slot has no channel ID; not persisted', + ); + } + return id; + } + + /// Lowest slot holding the same channel as [slot] in [slotIds], matching + /// the firmware, which files a PSK held twice under its first slot. Both + /// slots share that slot's in-memory history. + static int _canonicalSlotIn(Map slotIds, int slot) { + final id = slotIds[slot]; + if (id == null) return slot; + return _lowestSlotFor(slotIds, id) ?? slot; + } + + static int? _lowestSlotFor(Map slotIds, String channelId) { + int? lowest; + for (final entry in slotIds.entries) { + if (entry.value == channelId && (lowest == null || entry.key < lowest)) { + lowest = entry.key; + } + } + return lowest; + } + + int _canonicalSlot(int slot) => _canonicalSlotIn(_slotChannelIds, slot); + + Future _saveChannelMessages(int slot, List messages) { + final id = _channelIdForSlot(slot); + if (id == null) return Future.value(); + return _channelMessageStore.saveChannelMessages(id, messages); + } + int getUnreadCountForContact(Contact contact) { if (contact.type == advTypeRepeater) return 0; return getUnreadCountForContactKey(contact.publicKeyHex); @@ -1299,13 +1366,34 @@ class MeshCoreConnector extends ChangeNotifier { ); } + /// Slots holding the same channel as [slot]. Settings are stored per + /// channel ID, so the in-memory copy of every such slot must change too. + List _slotsSharingChannel(int slot) { + final id = _slotChannelIds[slot]; + if (id == null) return [slot]; + return [ + for (final entry in _slotChannelIds.entries) + if (entry.value == id) entry.key, + ]; + } + Future setChannelSmazEnabled(int channelIndex, bool enabled) async { - _channelSmazEnabled[channelIndex] = enabled; - if (enabled) { - _channelCyr2LatEnabled[channelIndex] = false; - await _channelSettingsStore.saveCyr2LatEnabled(channelIndex, false); + final slots = _slotsSharingChannel(channelIndex); + for (final slot in slots) { + _channelSmazEnabled[slot] = enabled; + } + final channelId = _channelIdForSlot(channelIndex); + if (enabled) { + for (final slot in slots) { + _channelCyr2LatEnabled[slot] = false; + } + if (channelId != null) { + await _channelSettingsStore.saveCyr2LatEnabled(channelId, false); + } + } + if (channelId != null) { + await _channelSettingsStore.saveSmazEnabled(channelId, enabled); } - await _channelSettingsStore.saveSmazEnabled(channelIndex, enabled); notifyListeners(); } @@ -1319,8 +1407,13 @@ class MeshCoreConnector extends ChangeNotifier { int channelIndex, bool enabled, ) async { - _channelUrlImagesEnabled[channelIndex] = enabled; - await _channelSettingsStore.saveUrlImagesEnabled(channelIndex, enabled); + for (final slot in _slotsSharingChannel(channelIndex)) { + _channelUrlImagesEnabled[slot] = enabled; + } + final channelId = _channelIdForSlot(channelIndex); + if (channelId != null) { + await _channelSettingsStore.saveUrlImagesEnabled(channelId, enabled); + } notifyListeners(); } @@ -1334,12 +1427,22 @@ class MeshCoreConnector extends ChangeNotifier { } Future setChannelCyr2LatEnabled(int channelIndex, bool enabled) async { - _channelCyr2LatEnabled[channelIndex] = enabled; - if (enabled) { - _channelSmazEnabled[channelIndex] = false; - await _channelSettingsStore.saveSmazEnabled(channelIndex, false); + final slots = _slotsSharingChannel(channelIndex); + for (final slot in slots) { + _channelCyr2LatEnabled[slot] = enabled; + } + final channelId = _channelIdForSlot(channelIndex); + if (enabled) { + for (final slot in slots) { + _channelSmazEnabled[slot] = false; + } + if (channelId != null) { + await _channelSettingsStore.saveSmazEnabled(channelId, false); + } + } + if (channelId != null) { + await _channelSettingsStore.saveCyr2LatEnabled(channelId, enabled); } - await _channelSettingsStore.saveCyr2LatEnabled(channelIndex, enabled); notifyListeners(); } @@ -1355,9 +1458,14 @@ class MeshCoreConnector extends ChangeNotifier { Future setChannelRegion(int channelIndex, String region) async { // Update in-memory state and notify synchronously so the UI reflects the // change immediately; persistence happens in the background. - _channelRegions[channelIndex] = region; + for (final slot in _slotsSharingChannel(channelIndex)) { + _channelRegions[slot] = region; + } notifyListeners(); - await _channelRegionStore.saveRegion(channelIndex, region); + final channelId = _channelIdForSlot(channelIndex); + if (channelId != null) { + await _channelRegionStore.saveRegion(channelId, region); + } } Future _loadChannelOrder() async { @@ -1366,19 +1474,34 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// History is stored by channel ID, so it may carry the slot the channel + /// sat in when it was saved; rebind it to the slot it is shown in now. + List _bindToSlot(List messages, int slot) => [ + for (final message in messages) + message.channelIndex == slot + ? message + : message.copyWith(channelIndex: slot), + ]; + /// Load persisted channel messages for a specific channel Future _loadChannelMessages(int channelIndex) async { - final allMessages = await _channelMessageStore.loadChannelMessages( - channelIndex, - ); + final channelId = _slotChannelIds[channelIndex]; + final allMessages = channelId == null + ? [] + : _bindToSlot( + await _channelMessageStore.loadChannelMessages(channelId), + channelIndex, + ); // 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), - ); + if (channelId != null) { + _channelMessageStore.setArchived( + channelId, + 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; @@ -1391,14 +1514,17 @@ class MeshCoreConnector extends ChangeNotifier { int channelIndex, { int count = 50, }) async { + final slot = _canonicalSlot(channelIndex); + final channelId = _channelIdForSlot(slot); + if (channelId == null) return []; final allMessages = await _channelMessageStore.loadChannelMessages( - channelIndex, + channelId, ); - final currentMessages = _channelMessages[channelIndex] ?? []; + final currentMessages = _channelMessages[slot] ?? []; // Storage holds the archived entries followed by the in-memory window. final currentOffset = - (_channelMessageStore.archivedCount(channelIndex) ?? + (_channelMessageStore.archivedCount(channelId) ?? allMessages.length - currentMessages.length) .clamp(0, allMessages.length); if (currentOffset == 0) { @@ -1408,22 +1534,34 @@ class MeshCoreConnector extends ChangeNotifier { final fetchCount = count.clamp(0, currentOffset); final startIndex = currentOffset - fetchCount; - final olderMessages = allMessages.sublist(startIndex, currentOffset); - _channelMessageStore.unarchiveNewest(channelIndex, olderMessages.length); + final olderMessages = _bindToSlot( + allMessages.sublist(startIndex, currentOffset), + slot, + ); + _channelMessageStore.unarchiveNewest(channelId, olderMessages.length); // Prepend to current conversation - _channelMessages[channelIndex] = [...olderMessages, ...currentMessages]; + _channelMessages[slot] = [...olderMessages, ...currentMessages]; notifyListeners(); return olderMessages; } - /// Load all persisted channel messages on startup - Future loadAllChannelMessages({int? maxChannels}) async { - final channelCount = maxChannels ?? _maxChannels; - // Load messages for all known channels (0-7 by default) - for (int i = 0; i < channelCount; i++) { - await _loadChannelMessages(i); + /// Loads the persisted messages of every channel in the slot map. Slots + /// that hold no channel, or alias a lower slot with the same PSK, are + /// emptied. + Future loadAllChannelMessages() async { + var removed = false; + for (final slot in _channelMessages.keys.toList()) { + if (!_slotChannelIds.containsKey(slot) || _canonicalSlot(slot) != slot) { + _channelMessages.remove(slot); + _processedChannelReactions.remove(slot); + removed = true; + } + } + if (removed) notifyListeners(); + for (final slot in _slotChannelIds.keys.toList()..sort()) { + if (_canonicalSlot(slot) == slot) await _loadChannelMessages(slot); } } @@ -1438,6 +1576,7 @@ class MeshCoreConnector extends ChangeNotifier { TimeoutPredictionService? timeoutPredictionService, ImageCodecService? imageCodecService, ImageChunkTransport? imageTransport, + ReceivedImageStore? receivedImageStore, void Function(ImageChunkOutcome outcome)? onImageChunk, void Function(int senderPrefix)? onImageSenderPrefix, }) { @@ -1447,6 +1586,7 @@ class MeshCoreConnector extends ChangeNotifier { _translationService = translationService; _imageCodecService = imageCodecService; _imageTransport = imageTransport; + _receivedImageStore = receivedImageStore; _onImageChunk = onImageChunk; _onImageSenderPrefix = onImageSenderPrefix; _bleDebugLogService = bleDebugLogService; @@ -1564,23 +1704,32 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } - Future loadChannelSettings({int? maxChannels}) async { + /// Reloads the persisted settings of every channel in the slot map. + Future loadChannelSettings() async { _channelSmazEnabled.clear(); _channelCyr2LatEnabled.clear(); _channelUrlImagesEnabled.clear(); + _channelCyr2LatProfileId.clear(); _channelRegions.clear(); _defaultRegion = _channelRegionStore.loadDefaultRegion(); - final channelCount = maxChannels ?? _maxChannels; - for (int i = 0; i < channelCount; i++) { - _channelSmazEnabled[i] = await _channelSettingsStore.loadSmazEnabled(i); - _channelCyr2LatEnabled[i] = await _channelSettingsStore - .loadCyr2LatEnabled(i); - _channelUrlImagesEnabled[i] = await _channelSettingsStore - .loadUrlImagesEnabled(i); - _channelRegions[i] = await _channelRegionStore.loadRegion(i); + for (final slot in _slotChannelIds.keys.toList()) { + await _loadChannelSlotSettings(slot); } } + Future _loadChannelSlotSettings(int slot) async { + final channelId = _slotChannelIds[slot]; + if (channelId == null) return; + _channelSmazEnabled[slot] = await _channelSettingsStore.loadSmazEnabled( + channelId, + ); + _channelCyr2LatEnabled[slot] = await _channelSettingsStore + .loadCyr2LatEnabled(channelId); + _channelUrlImagesEnabled[slot] = await _channelSettingsStore + .loadUrlImagesEnabled(channelId); + _channelRegions[slot] = await _channelRegionStore.loadRegion(channelId); + } + /// After an incoming DM or channel message, wait before TX so we do not /// collide with mesh propagation. With companion stats, scale wait by RF /// conditions (up to [_contactMsgBackoffMaxMs]); otherwise use @@ -1869,7 +2018,8 @@ class MeshCoreConnector extends ChangeNotifier { String messageId, ChannelMessage Function(ChannelMessage current) update, ) { - final messages = _channelMessages[channelIndex]; + final slot = _canonicalSlot(channelIndex); + final messages = _channelMessages[slot]; if (messages == null) { return; } @@ -1878,7 +2028,7 @@ class MeshCoreConnector extends ChangeNotifier { return; } messages[index] = update(messages[index]); - _channelMessageStore.saveChannelMessages(channelIndex, messages); + _saveChannelMessages(slot, messages); notifyListeners(); } @@ -3295,6 +3445,13 @@ class MeshCoreConnector extends ChangeNotifier { _totalChannelsToRequest = 0; _previousChannelsCache.clear(); _unconfirmedChannelSlots.clear(); + _channelSyncIncomplete = false; + _channelMapSyncRetries = 0; + _channelMapConfirmed = false; + _channelSessionGeneration++; + final channelSync = _channelSyncCompleter; + _channelSyncCompleter = null; + if (channelSync != null && !channelSync.isCompleted) channelSync.complete(); } bool get _shouldAutoReconnect => @@ -4540,30 +4697,29 @@ class MeshCoreConnector extends ChangeNotifier { final reactionInfo = ReactionHelper.parseReaction(text); if (reactionInfo != null) { reactionInfo.senderName = selfName; + final slot = _canonicalSlot(channel.index); // Check if we've already processed this reaction - _processedChannelReactions.putIfAbsent(channel.index, () => {}); + _processedChannelReactions.putIfAbsent(slot, () => {}); final reactionIdentifier = reactionInfo.identifier(); // Maybe we should allow resending. Recipients can drop duplicates. - if (_processedChannelReactions[channel.index]!.contains( - reactionIdentifier, - )) { + if (_processedChannelReactions[slot]!.contains(reactionIdentifier)) { // Already processed, don't process again return; } // Get the in-memory messages list (same as _addChannelMessage uses) - _channelMessages.putIfAbsent(channel.index, () => []); - final messages = _channelMessages[channel.index]!; + _channelMessages.putIfAbsent(slot, () => []); + final messages = _channelMessages[slot]!; // Process reaction locally to update the UI immediately appLogger.info('Adding sent channel reaction, id: $reactionIdentifier'); final reactionApplied = _processReaction(messages, reactionInfo); if (reactionApplied) { - await _channelMessageStore.saveChannelMessages(channel.index, messages); + await _saveChannelMessages(slot, messages); // Mark this reaction as processed - _processedChannelReactions[channel.index]!.add(reactionIdentifier); + _processedChannelReactions[slot]!.add(reactionIdentifier); notifyListeners(); @@ -5101,6 +5257,13 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildSetDeviceTimeFrame(now)); } + bool get _channelSyncBlocksQueue => + !_channelMapConfirmed || + _pendingInitialChannelSync || + _isSyncingChannels || + _channelSyncInFlight || + _channelSyncCompleter != null; + Future syncQueuedMessages({bool force = false}) async { if (!isConnected) return; if (!force && _isSyncingQueuedMessages) return; @@ -5112,7 +5275,9 @@ class MeshCoreConnector extends ChangeNotifier { _pendingQueueSync = true; return; } - if (_isSyncingChannels || _channelSyncInFlight) { + // Queued channel frames carry only a slot index, so they wait until this + // session's slot map is confirmed and no channel sync can change it. + if (_channelSyncBlocksQueue) { _pendingQueueSync = true; return; } @@ -5129,6 +5294,17 @@ class MeshCoreConnector extends ChangeNotifier { return; } if (_queuedMessageSyncInFlight) return; + if (_channelSyncBlocksQueue) { + // A channel sync started mid-queue: hold the next frame until its slot + // map is in place. _finishChannelSync resumes the queue. + debugPrint('[QueueSync] Paused for channel sync'); + _queueSyncTimeout?.cancel(); + _isSyncingQueuedMessages = false; + _queueSyncRetries = 0; + _pendingQueueSync = true; + notifyListeners(); + return; + } _queuedMessageSyncInFlight = true; // Cancel any existing timeout @@ -5247,11 +5423,20 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// Syncs every channel slot from the radio. Completes once the sync has + /// applied its slot map, so callers can persist under the new channel IDs. Future getChannels({int? maxChannels, bool force = false}) async { if (!isConnected) return; - if (_isSyncingChannels) { - debugPrint('[ChannelSync] Already syncing channels, ignoring request'); - return; + while (_channelSyncCompleter != null) { + final running = _channelSyncCompleter!.future; + if (!force) { + debugPrint('[ChannelSync] Already syncing channels, ignoring request'); + return running; + } + // A forced refresh follows a SET_CHANNEL the running sync may have + // read past, so run a fresh sync once it ends. + await running; + if (!isConnected) return; } // Skip fetching if already loaded and not forced @@ -5262,12 +5447,16 @@ class MeshCoreConnector extends ChangeNotifier { return; } + final completer = Completer(); + _channelSyncCompleter = completer; + _channelMapSyncRetries = 0; _isLoadingChannels = true; _isSyncingChannels = true; _hasLoadedChannels = false; _previousChannelsCache = List.from(_channels); _channels.clear(); _unconfirmedChannelSlots.clear(); + _channelSyncIncomplete = false; _nextChannelIndexToRequest = 0; _totalChannelsToRequest = maxChannels ?? _maxChannels; _channelSyncRetries = 0; @@ -5279,6 +5468,25 @@ class MeshCoreConnector extends ChangeNotifier { // Start sequential sync await _requestNextChannel(); + return completer.future; + } + + /// Runs another full pass after slots timed out, keeping what this pass + /// learned as the fallback for slots that time out again. + void _restartChannelSyncPass() { + final known = { + for (final channel in _previousChannelsCache) channel.index: channel, + for (final channel in _channels) channel.index: channel, + }; + _previousChannelsCache = known.values.toList(); + _channels.clear(); + _unconfirmedChannelSlots.clear(); + _channelSyncIncomplete = false; + _nextChannelIndexToRequest = 0; + _channelSyncRetries = 0; + _channelSyncInFlight = false; + notifyListeners(); + unawaited(_requestNextChannel()); } Future _requestNextChannel() async { @@ -5303,7 +5511,7 @@ class MeshCoreConnector extends ChangeNotifier { // Set up timeout for this channel request _channelSyncTimeout = Timer( - Duration(milliseconds: _channelSyncTimeoutMs), + Duration(milliseconds: channelSyncTimeoutMs), () => _handleChannelSyncTimeout(channelIndex), ); @@ -5335,6 +5543,7 @@ class MeshCoreConnector extends ChangeNotifier { debugPrint( '[ChannelSync] Max retries reached for channel $channelIndex, attempting cache restore', ); + _channelSyncIncomplete = true; // Try to restore this channel from cache try { @@ -5382,6 +5591,19 @@ class MeshCoreConnector extends ChangeNotifier { '[ChannelSync] Sync complete: received ${_channels.length}/$_totalChannelsToRequest channels', ); + if (_channelSyncIncomplete && + _channelMapSyncRetries < _maxChannelMapSyncRetries && + isConnected) { + _channelMapSyncRetries++; + debugPrint( + '[ChannelSync] Some slots did not answer; retrying the sync ' + '($_channelMapSyncRetries/$_maxChannelMapSyncRetries)', + ); + _restartChannelSyncPass(); + return; + } + final complete = !_channelSyncIncomplete; + _cleanupChannelSync(completed: true); // Cache channels for offline use @@ -5392,6 +5614,153 @@ class MeshCoreConnector extends ChangeNotifier { // Apply ordering and notify UI _applyChannelOrder(); notifyListeners(); + unawaited(_applyChannelMap(complete: complete)); + } + + /// Replaces the slot map with the one this sync read and reloads the + /// in-memory state of every slot whose channel changed, then releases the + /// queued messages that were waiting for it. + Future _applyChannelMap({required bool complete}) async { + final generation = _channelSessionGeneration; + final next = { + for (final channel in _channels) + if (channel.storageId != null) channel.index: channel.storageId!, + }; + final unconfirmed = Set.of(_unconfirmedChannelSlots); + await _channelStorageReady; + if (generation != _channelSessionGeneration) return; + + final previous = Map.of(_slotChannelIds); + if (!complete) { + for (final slot in unconfirmed) { + final saved = previous[slot]; + if (saved != null) next[slot] = saved; + } + appLogger.warn( + 'Channel sync incomplete; using the saved channel map for slots ' + '$unconfirmed', + ); + } + _slotChannelIds + ..clear() + ..addAll(next); + + try { + var orderChanged = false; + final slots = {...previous.keys, ...next.keys}.toList()..sort(); + for (final slot in slots) { + final before = previous[slot]; + final after = next[slot]; + if (before == after && + _canonicalSlotIn(previous, slot) == _canonicalSlotIn(next, slot)) { + continue; + } + if (before != after) { + appLogger.info( + 'Channel slot $slot: ${before ?? 'empty'} -> ${after ?? 'empty'}', + ); + orderChanged |= _carryChannelOrder(before, after, next); + } + _dropChannelSlotState(slot, before); + await _loadChannelSlotSettings(slot); + if (_canonicalSlot(slot) == slot) await _loadChannelMessages(slot); + if (generation != _channelSessionGeneration) return; + } + if (orderChanged) { + _applyChannelOrder(); + await _channelOrderStore.saveChannelOrder(_channelOrder); + } + await _channelStore.saveSlotChannelIds(next); + } catch (e) { + // The map is already applied in memory; a storage failure must not + // leave the queue blocked for the rest of the session. + appLogger.warn('Applying the channel slot map failed: $e'); + } + if (generation != _channelSessionGeneration) return; + _channelMapConfirmed = true; + notifyListeners(); + _finishChannelSync(); + } + + /// A channel whose key changed in place keeps its position in the custom + /// order: [after] takes [before]'s place when no slot holds [before] any + /// more. Returns true when the order changed. + bool _carryChannelOrder( + String? before, + String? after, + Map next, + ) { + if (before == null || after == null) return false; + if (next.containsValue(before) || _channelOrder.contains(after)) { + return false; + } + final position = _channelOrder.indexOf(before); + if (position < 0) return false; + _channelOrder[position] = after; + return true; + } + + /// Releases queued messages after a sync failed without reading the slots, + /// keeping the saved slot map. + Future _releaseChannelMapWithoutSync() async { + final generation = _channelSessionGeneration; + await _channelStorageReady; + if (generation != _channelSessionGeneration) return; + if (!_channelMapConfirmed) { + appLogger.warn('Channel sync failed; using the saved channel map'); + _channelMapConfirmed = true; + } + _finishChannelSync(); + } + + void _finishChannelSync() { + final completer = _channelSyncCompleter; + _channelSyncCompleter = null; + if (completer != null && !completer.isCompleted) completer.complete(); + if (isConnected) _startPostChannelInitialQueuedMessageSync(); + } + + /// Forgets everything held in memory for [slot], whose channel changed. + void _dropChannelSlotState(int slot, String? previousId) { + _channelMessages.remove(slot); + _processedChannelReactions.remove(slot); + _channelSmazEnabled.remove(slot); + _channelCyr2LatEnabled.remove(slot); + _channelUrlImagesEnabled.remove(slot); + _channelCyr2LatProfileId.remove(slot); + _channelRegions.remove(slot); + if (previousId != null && !_slotChannelIds.containsValue(previousId)) { + _channelMessageStore.forgetArchive(previousId); + } + // The reassembler reports in-progress streams as failed while the store + // can still map them to their entries, so drop it first. + _imageTransport?.reassembler.clearChannel(slot); + _receivedImageStore?.forgetChannelSlot(slot); + } + + /// Runs the one-shot storage migration, then preloads this radio's channel + /// state from the saved slot map so it shows before the channel sync ends. + Future _prepareChannelStorage() async { + try { + // First: the channel sync is already running and carries unread counts + // over from these. The migration never touches the channel cache. + await loadCachedChannels(); + final migrated = await ChannelStorageMigration.migrate( + _channelStore.publicKeyHex, + ); + if (migrated.isNotEmpty) { + await _receivedImageStore?.stampLegacyChannelIds(migrated); + } + await _loadChannelOrder(); + final saved = await _channelStore.loadSlotChannelIds(); + _slotChannelIds + ..clear() + ..addAll(saved); + await loadChannelSettings(); + await loadAllChannelMessages(); + } catch (e) { + appLogger.warn('Loading channel storage failed: $e'); + } } void _cleanupChannelSync({required bool completed}) { @@ -5414,19 +5783,25 @@ class MeshCoreConnector extends ChangeNotifier { _recalculateCachedChannelsUnreadTotal(); } - if (isConnected) { - _startPostChannelInitialQueuedMessageSync(); - } - // Keep cache on failure/disconnection for future attempts if (!completed) { + if (isConnected) { + unawaited(_releaseChannelMapWithoutSync()); + } else { + final completer = _channelSyncCompleter; + _channelSyncCompleter = null; + if (completer != null && !completer.isCompleted) completer.complete(); + } notifyListeners(); } } void _startPostChannelInitialQueuedMessageSync() { if (_pendingInitialQueuedMessageSync || _pendingQueueSync) { - _deferQueuedContactMessagesUntilContacts = _pendingInitialContactsSync; + // Keep a deferral already in force so its held frames still replay. + _deferQueuedContactMessagesUntilContacts = + _deferQueuedContactMessagesUntilContacts || + _pendingInitialContactsSync; _pendingInitialQueuedMessageSync = false; _pendingQueueSync = false; unawaited(syncQueuedMessages(force: true)); @@ -5444,17 +5819,37 @@ class MeshCoreConnector extends ChangeNotifier { Future deleteChannel(int index) async { if (!isConnected) return; + // The PSK of the channel being deleted, as the channel list shows it, + // not the slot map, which can lag for a slot left unconfirmed. + final channelId = + _findChannelByIndex(index)?.storageId ?? _slotChannelIds[index]; // Delete by setting empty name and zero PSK await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); - // Clear stored messages for this channel - await _channelMessageStore.clearChannelMessages(index); - // Clear in-memory messages for this channel + // Another slot holding the same PSK keeps the shared history. + final stillHeld = _channels.any( + (channel) => channel.index != index && channel.storageId == channelId, + ); + if (channelId != null && !stillHeld) { + await _clearChannelStorage(channelId); + } _channelMessages.remove(index); _processedChannelReactions.remove(index); // Refresh channels after deleting await getChannels(force: true); } + /// Removes everything persisted for [channelId]: messages, settings, + /// region, images and its place in the channel order. + Future _clearChannelStorage(String channelId) async { + await _channelMessageStore.clearChannelMessages(channelId); + await _channelSettingsStore.clearChannel(channelId); + await _channelRegionStore.clearRegion(channelId); + await _receivedImageStore?.deleteImagesForChannelId(channelId); + if (_channelOrder.remove(channelId)) { + await _channelOrderStore.saveChannelOrder(_channelOrder); + } + } + void _handleFrame(List data) { if (data.isEmpty) return; _lastRxBeforeFrame = _lastRxTime; @@ -5844,13 +6239,10 @@ class MeshCoreConnector extends ChangeNotifier { _pathHistoryService?.setDevicePublicKey(selfPublicKeyHex); // Now that we have self info, we can load all the persisted data for this node - _loadChannelOrder(); loadContactCache(); - loadChannelSettings(); - loadCachedChannels(); - - // Load persisted channel messages - loadAllChannelMessages(); + // Channel data is migrated and preloaded from the saved slot map before + // the channel sync diffs that map against the radio. + _channelStorageReady = _prepareChannelStorage(); loadUnreadState(); _loadDiscoveredContactCache(); _persistedStateLoadedKey = selfPublicKeyHex; @@ -5923,8 +6315,6 @@ class MeshCoreConnector extends ChangeNotifier { _maxContacts = nextMaxContacts; _maxChannels = nextMaxChannels; if (nextMaxChannels > previousMaxChannels) { - unawaited(loadChannelSettings(maxChannels: nextMaxChannels)); - unawaited(loadAllChannelMessages(maxChannels: nextMaxChannels)); if (isConnected && _selfPublicKey != null && !_pendingInitialChannelSync) { @@ -6800,7 +7190,9 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureChannelCyr2LatSettingLoaded(int channelIndex) { if (_channelCyr2LatEnabled.containsKey(channelIndex)) return; - _channelSettingsStore.loadCyr2LatEnabled(channelIndex).then((enabled) { + final channelId = _slotChannelIds[channelIndex]; + if (channelId == null) return; + _channelSettingsStore.loadCyr2LatEnabled(channelId).then((enabled) { if (_channelCyr2LatEnabled[channelIndex] == enabled) return; _channelCyr2LatEnabled[channelIndex] = enabled; notifyListeners(); @@ -6809,7 +7201,9 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureChannelCyr2LatProfileLoaded(int channelIndex) { if (_channelCyr2LatProfileId.containsKey(channelIndex)) return; - _channelSettingsStore.loadCyr2LatProfileId(channelIndex).then((profileId) { + final channelId = _slotChannelIds[channelIndex]; + if (channelId == null) return; + _channelSettingsStore.loadCyr2LatProfileId(channelId).then((profileId) { if (_channelCyr2LatProfileId[channelIndex] == profileId) return; _channelCyr2LatProfileId[channelIndex] = profileId; notifyListeners(); @@ -6826,8 +7220,13 @@ class MeshCoreConnector extends ChangeNotifier { String? profileId, ) async { if (_channelCyr2LatProfileId[channelIndex] == profileId) return; - _channelCyr2LatProfileId[channelIndex] = profileId; - await _channelSettingsStore.saveCyr2LatProfileId(channelIndex, profileId); + for (final slot in _slotsSharingChannel(channelIndex)) { + _channelCyr2LatProfileId[slot] = profileId; + } + final channelId = _channelIdForSlot(channelIndex); + if (channelId != null) { + await _channelSettingsStore.saveCyr2LatProfileId(channelId, profileId); + } notifyListeners(); } @@ -7044,6 +7443,19 @@ class MeshCoreConnector extends ChangeNotifier { return; } + // File the message under the channel this PSK is now in, which + // may not be the slot the channel list says. + final channelId = channel.storageId; + final slot = _channelMapConfirmed && channelId != null + ? _slotForChannelId(channelId) + : null; + if (slot == null) { + debugPrint( + '[RxLog] No confirmed slot holds channel $channelId; dropped', + ); + return; + } + final pktHash = _computePacketHash( packet.payloadType, packet.payload, @@ -7060,7 +7472,7 @@ class MeshCoreConnector extends ChangeNotifier { pathLength: packet.isFlood ? packet.hopCount : 0, pathHashWidth: packet.pathHashWidth, pathBytes: packet.pathBytes, - channelIndex: channel.index, + channelIndex: slot, region: _resolveTransportRegion(packet), packetHash: pktHash, ); @@ -7071,14 +7483,14 @@ class MeshCoreConnector extends ChangeNotifier { pathBytes: message.pathBytes, pathHashWidth: message.pathHashWidth, ); - final isNew = _addChannelMessage(channel.index, message); + final isNew = _addChannelMessage(slot, message); _maybeIncrementChannelUnread(message, isNew: isNew); notifyListeners(); if (isNew) { // Run translation + notification asynchronously to avoid blocking unawaited(() async { final translationResult = await translateChannelMessage( - channel.index, + slot, message, ); _maybeNotifyChannelMessage( @@ -7152,9 +7564,7 @@ class MeshCoreConnector extends ChangeNotifier { status: ChannelMessageStatus.sent, ); _pendingChannelSentQueue.remove(messageId); - unawaited( - _channelMessageStore.saveChannelMessages(entry.key, channelMessages), - ); + unawaited(_saveChannelMessages(entry.key, channelMessages)); notifyListeners(); return true; } @@ -7177,9 +7587,7 @@ class MeshCoreConnector extends ChangeNotifier { channelMessages[i] = message.copyWith( status: ChannelMessageStatus.failed, ); - unawaited( - _channelMessageStore.saveChannelMessages(entry.key, channelMessages), - ); + unawaited(_saveChannelMessages(entry.key, channelMessages)); notifyListeners(); return; } @@ -7275,11 +7683,17 @@ class MeshCoreConnector extends ChangeNotifier { '[ChannelSync] Received channel ${channel.index}: ${channel.isEmpty ? "empty" : channel.name}', ); - // Preserve unread count from cached channel - final cachedChannel = _cachedChannels.cast().firstWhere( - (c) => c?.index == channel.index, - orElse: () => null, - ); + // Preserve unread count from the cached copy of the same channel (same + // PSK), wherever it sat; a reused slot starts with no unread. + final cachedChannel = + _cachedChannels.cast().firstWhere( + (c) => c?.index == channel.index && listEquals(c?.psk, channel.psk), + orElse: () => null, + ) ?? + _cachedChannels.cast().firstWhere( + (c) => listEquals(c?.psk, channel.psk), + orElse: () => null, + ); if (cachedChannel != null) { channel.unreadCount = cachedChannel.unreadCount; } @@ -7324,8 +7738,10 @@ class MeshCoreConnector extends ChangeNotifier { (c) => c.index == channel.index, ); if (existingIndex >= 0) { - // Preserve unread count from existing channel - channel.unreadCount = _channels[existingIndex].unreadCount; + // Preserve unread count from the existing channel if unchanged + if (listEquals(_channels[existingIndex].psk, channel.psk)) { + channel.unreadCount = _channels[existingIndex].unreadCount; + } _channels[existingIndex] = channel; } else { _channels.add(channel); @@ -7345,14 +7761,14 @@ class MeshCoreConnector extends ChangeNotifier { return; } - final orderIndex = {}; + final orderIndex = {}; for (int i = 0; i < _channelOrder.length; i++) { - orderIndex[_channelOrder[i]] = i; + orderIndex.putIfAbsent(_channelOrder[i], () => i); } _channels.sort((a, b) { - final aPos = orderIndex[a.index]; - final bPos = orderIndex[b.index]; + final aPos = orderIndex[a.storageId]; + final bPos = orderIndex[b.storageId]; if (aPos != null && bPos != null) return aPos.compareTo(bPos); if (aPos != null) return -1; if (bPos != null) return 1; @@ -7360,8 +7776,15 @@ class MeshCoreConnector extends ChangeNotifier { }); } + /// Saves the channel order given as slot indexes; it is stored by channel + /// ID so it follows channels that move between slots. Future setChannelOrder(List order) async { - _channelOrder = List.from(order); + final ids = []; + for (final slot in order) { + final id = _findChannelByIndex(slot)?.storageId; + if (id != null && !ids.contains(id)) ids.add(id); + } + _channelOrder = ids; _applyChannelOrder(); notifyListeners(); await _channelOrderStore.saveChannelOrder(_channelOrder); @@ -7655,6 +8078,9 @@ class MeshCoreConnector extends ChangeNotifier { } } + int? _slotForChannelId(String channelId) => + _lowestSlotFor(_slotChannelIds, channelId); + int _computeChannelHash(Uint8List psk) { final digest = crypto.sha256.convert(psk).bytes; return digest[0]; @@ -7785,7 +8211,8 @@ class MeshCoreConnector extends ChangeNotifier { return _ParsedText(senderName: 'Unknown', text: text); } - bool _addChannelMessage(int channelIndex, ChannelMessage message) { + bool _addChannelMessage(int slot, ChannelMessage message) { + final channelIndex = _canonicalSlot(slot); _channelMessages.putIfAbsent(channelIndex, () => []); final messages = _channelMessages[channelIndex]!; @@ -7807,7 +8234,7 @@ class MeshCoreConnector extends ChangeNotifier { if (reactionApplied) { appLogger.info('Adding channel reaction, id: $reactionIdentifier'); // Save updated messages - _channelMessageStore.saveChannelMessages(channelIndex, messages); + _saveChannelMessages(channelIndex, messages); // Mark as processed _processedChannelReactions[channelIndex]!.add(reactionIdentifier); @@ -7915,7 +8342,7 @@ class MeshCoreConnector extends ChangeNotifier { } // Save to persistent storage - _channelMessageStore.saveChannelMessages(channelIndex, messages); + _saveChannelMessages(channelIndex, messages); return isNew; } @@ -8150,6 +8577,8 @@ class MeshCoreConnector extends ChangeNotifier { _channelHopShortfalls.clear(); _messageStore.forgetArchive(); _channelMessageStore.forgetArchive(); + _slotChannelIds.clear(); + _channelMapConfirmed = false; _messageStateOwnerKey = null; _persistedStateLoadedKey = null; } @@ -8834,11 +9263,12 @@ class MeshCoreConnector extends ChangeNotifier { } void clearMessagesForChannel(int channelIndex) { - final messages = _channelMessages[channelIndex]; - if (messages == null) return; - messages.clear(); - // Clear storage too, not just the in-memory window. - unawaited(_channelMessageStore.clearChannelMessages(channelIndex)); + _channelMessages[_canonicalSlot(channelIndex)]?.clear(); + // Clear storage too, even when nothing of it is in memory. + final channelId = _channelIdForSlot(channelIndex); + if (channelId != null) { + unawaited(_channelMessageStore.clearChannelMessages(channelId)); + } markChannelRead(channelIndex); notifyListeners(); } diff --git a/lib/main.dart b/lib/main.dart index f5f54751..9d9c333e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -109,7 +109,10 @@ void main() async { // Availability/isBusy changes are the only thing that un-parks a decode // queue that stopped because the codec was unusable or busy. imageCodecService.addListener(receivedImageStore.notifyDecoderChanged); - final imageReassembler = ImageStreamReassembler(store: receivedImageStore); + final imageReassembler = ImageStreamReassembler( + store: receivedImageStore, + channelIdForSlot: connector.channelIdForSlot, + ); final imageTransport = ImageChunkTransport( reassembler: imageReassembler, // The UI sends whole chunk sets through connector.sendImageChunks so it @@ -158,6 +161,7 @@ void main() async { timeoutPredictionService: timeoutPredictionService, imageCodecService: imageCodecService, imageTransport: imageTransport, + receivedImageStore: receivedImageStore, // ImageStreamReassembler.addChunk already forwards every outcome to the // store together with the channel index (which ImageChunkOutcome itself // does not carry), so onImageChunk would be a second, channel-blind path. @@ -165,11 +169,7 @@ void main() async { ); await connector.loadContactCache(); - await connector.loadChannelSettings(); await connector.loadCachedChannels(); - - // Load persisted channel messages - await connector.loadAllChannelMessages(); await connector.loadUnreadState(); runApp( @@ -251,7 +251,7 @@ class AppSettingsImageCodecStore implements ImageCodecSettingsStore { /// An [ImageReassembler] that (a) learns the local sender prefix after /// SELF_INFO and (b) forwards every outcome to [ReceivedImageStore] together -/// with the channel index. +/// with the channel index and the channel ID that slot holds. /// /// Both exist because of upstream shapes this file cannot change: /// * `ImageReassembler.selfPrefix` is `final`, but the local public key does @@ -265,9 +265,12 @@ class AppSettingsImageCodecStore implements ImageCodecSettingsStore { class ImageStreamReassembler extends ImageReassembler { final ReceivedImageStore store; + /// Resolves the radio slot a chunk arrived on to its [Channel.storageId]. + final String? Function(int channelIndex)? channelIdForSlot; + int? _selfPrefix; - ImageStreamReassembler({required this.store}) + ImageStreamReassembler({required this.store, this.channelIdForSlot}) : super(onFailed: ((failure) => unawaited(store.handleFailure(failure)))); @override @@ -282,7 +285,13 @@ class ImageStreamReassembler extends ImageReassembler { DateTime? now, }) { final outcome = super.addChunk(blob, channelIndex: channelIndex, now: now); - unawaited(store.handleOutcome(outcome, channelIndex: channelIndex)); + unawaited( + store.handleOutcome( + outcome, + channelIndex: channelIndex, + channelId: channelIdForSlot?.call(channelIndex), + ), + ); return outcome; } } diff --git a/lib/models/channel.dart b/lib/models/channel.dart index 73a9f3c7..4e67d2af 100644 --- a/lib/models/channel.dart +++ b/lib/models/channel.dart @@ -25,6 +25,25 @@ class Channel { bool get isEmpty => name.isEmpty && psk.every((b) => b == 0); + /// Key for this channel's persisted data (messages, settings, region, + /// order, images). Derived from the PSK so it follows the channel across + /// radio slots; null for an empty slot. + late final String? storageId = storageIdForPsk(psk); + + static const String _storageIdDomain = 'meshcore-channel:'; + + /// First 8 bytes of SHA-256("meshcore-channel:" + psk) as 16 hex chars, or + /// null for an all-zero PSK. Not the 1-byte on-air channel hash, which + /// collides. + static String? storageIdForPsk(Uint8List psk) { + if (psk.every((b) => b == 0)) return null; + final digest = crypto.sha256.convert([ + ...utf8.encode(_storageIdDomain), + ...psk, + ]); + return _bytesToHex(Uint8List.fromList(digest.bytes.sublist(0, 8))); + } + /// Key used for per-channel notification muting. String get muteKey => name.isEmpty ? 'Channel $index' : name; diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index 153d220c..ccaf9170 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -124,6 +124,7 @@ class ChannelMessage { MessageTranslationStatus? translationStatus, Object? translationModelId = _unset, Map>? reactions, + int? channelIndex, }) { return ChannelMessage( senderKey: senderKey, @@ -152,7 +153,7 @@ class ChannelMessage { pathHashWidth: pathHashWidth ?? this.pathHashWidth, pathBytes: pathBytes ?? this.pathBytes, pathVariants: pathVariants ?? this.pathVariants, - channelIndex: channelIndex, + channelIndex: channelIndex ?? this.channelIndex, region: region == _unset ? this.region : region as String?, messageId: messageId, packetHash: packetHash ?? this.packetHash, diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 5ab34313..358ea298 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1514,6 +1514,7 @@ class _ChannelChatScreenState extends State { try { await store.registerOutgoing( channelIndex: widget.channel.index, + channelId: widget.channel.storageId, // The same 16 bits the chunk header carries, so the entry keys the // same way an inbound one would. senderPrefix: senderPrefix, @@ -1629,10 +1630,7 @@ class _ChannelChatScreenState extends State { } final images = store == null ? const [] - : [ - for (final entry in store.entries) - if (entry.channelIndex == widget.channel.index) entry, - ]; + : store.entriesForChannel(widget.channel.storageId); final layout = _TranscriptLayout.build( messages: messages, images: images, @@ -2339,9 +2337,11 @@ class _ChannelChatScreenState extends State { context.read().clearMessagesForChannel( widget.channel.index, ); + final channelId = widget.channel.storageId; + if (channelId == null) return; try { - await context.read().deleteImagesForChannel( - widget.channel.index, + await context.read().deleteImagesForChannelId( + channelId, ); } on ProviderNotFoundException { return; diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 655f7af1..0e48c008 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:meshcore_open/storage/channel_message_store.dart'; import 'package:meshcore_open/utils/keys.dart'; import 'package:meshcore_open/utils/platform_info.dart'; import 'package:meshcore_open/widgets/app_bar.dart'; @@ -12,7 +11,6 @@ import 'package:uuid/uuid.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../services/app_settings_service.dart'; -import '../services/received_image_store.dart'; import '../services/ui_view_state_service.dart'; import '../models/channel.dart'; import '../models/community.dart'; @@ -55,8 +53,6 @@ class _ChannelsScreenState extends State List _communities = []; Timer? _searchDebounce; - ChannelMessageStore get _channelMessageStore => ChannelMessageStore(); - @override void initState() { super.initState(); @@ -102,9 +98,6 @@ class _ChannelsScreenState extends State final connector = context.watch(); final viewState = context.watch(); - final channelMessageStore = ChannelMessageStore(); - channelMessageStore.setPublicKeyHex = connector.selfPublicKeyHex; - // Auto-navigate back to scanner if disconnected if (!checkConnectionAndNavigate(connector)) { return const SizedBox.shrink(); @@ -316,7 +309,6 @@ class _ChannelsScreenState extends State return _buildChannelTile( context, connector, - channelMessageStore, channel, showDragHandle: true, dragIndex: index, @@ -337,7 +329,6 @@ class _ChannelsScreenState extends State return _buildChannelTile( context, connector, - channelMessageStore, channel, listIndex: index, ); @@ -373,7 +364,6 @@ class _ChannelsScreenState extends State Widget _buildChannelTile( BuildContext context, MeshCoreConnector connector, - ChannelMessageStore channelMessageStore, Channel channel, { bool showDragHandle = false, int? dragIndex, @@ -467,19 +457,10 @@ class _ChannelsScreenState extends State ), ); }, - onLongPress: () => _showChannelActions( - this.context, - connector, - channelMessageStore, - channel, - ), + onLongPress: () => + _showChannelActions(this.context, connector, channel), onSecondaryTap: PlatformInfo.isDesktop - ? () => _showChannelActions( - this.context, - connector, - channelMessageStore, - channel, - ) + ? () => _showChannelActions(this.context, connector, channel) : null, child: Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -639,7 +620,6 @@ class _ChannelsScreenState extends State void _showChannelActions( BuildContext context, MeshCoreConnector connector, - ChannelMessageStore channelMessageStore, Channel channel, ) { final parentContext = context; @@ -698,12 +678,7 @@ class _ChannelsScreenState extends State Navigator.pop(sheetContext); await Future.delayed(const Duration(milliseconds: 100)); if (parentContext.mounted) { - _confirmDeleteChannel( - parentContext, - connector, - channelMessageStore, - channel, - ); + _confirmDeleteChannel(parentContext, connector, channel); } }, ), @@ -949,9 +924,7 @@ class _ChannelsScreenState extends State ); } - Widget? buildExpandedContent( - ChannelMessageStore channelMessageStore, - ) { + Widget? buildExpandedContent() { switch (selectedOption) { case 0: // Create Private Channel return Column( @@ -1005,8 +978,6 @@ class _ChannelsScreenState extends State name, psk, ); - await channelMessageStore - .clearChannelMessages(nextIndex); if (context.mounted) { showDismissibleSnackBar( context, @@ -1607,8 +1578,7 @@ class _ChannelsScreenState extends State .l10n .channels_joinPublicChannelDesc, ), - if (selectedOption == 2) - buildExpandedContent(_channelMessageStore)!, + if (selectedOption == 2) buildExpandedContent()!, ], buildOptionCard( optionIndex: 3, @@ -1619,8 +1589,7 @@ class _ChannelsScreenState extends State .l10n .channels_joinHashtagChannelDesc, ), - if (selectedOption == 3) - buildExpandedContent(_channelMessageStore)!, + if (selectedOption == 3) buildExpandedContent()!, buildOptionCard( optionIndex: 1, icon: Icons.lock, @@ -1630,16 +1599,14 @@ class _ChannelsScreenState extends State .l10n .channels_joinPrivateChannelDesc, ), - if (selectedOption == 1) - buildExpandedContent(_channelMessageStore)!, + if (selectedOption == 1) buildExpandedContent()!, buildOptionCard( optionIndex: 4, icon: Icons.qr_code_scanner, title: sheetContext.l10n.community_scanQr, subtitle: sheetContext.l10n.community_join, ), - if (selectedOption == 4) - buildExpandedContent(_channelMessageStore)!, + if (selectedOption == 4) buildExpandedContent()!, SectionHeader( sheetContext.l10n.channels_addSectionCreate, ), @@ -1652,16 +1619,14 @@ class _ChannelsScreenState extends State .l10n .channels_createPrivateChannelDesc, ), - if (selectedOption == 0) - buildExpandedContent(_channelMessageStore)!, + if (selectedOption == 0) buildExpandedContent()!, buildOptionCard( optionIndex: 5, icon: Icons.groups, title: sheetContext.l10n.community_create, subtitle: sheetContext.l10n.community_createDesc, ), - if (selectedOption == 5) - buildExpandedContent(_channelMessageStore)!, + if (selectedOption == 5) buildExpandedContent()!, ], ), ), @@ -1914,15 +1879,8 @@ class _ChannelsScreenState extends State void _confirmDeleteChannel( BuildContext context, MeshCoreConnector connector, - ChannelMessageStore channelMessageStore, Channel channel, ) { - ReceivedImageStore? imageStore; - try { - imageStore = context.read(); - } on ProviderNotFoundException { - imageStore = null; - } final channelLabel = channel.name.isEmpty ? context.l10n.channels_channelIndex(channel.index) : channel.name; @@ -1944,9 +1902,6 @@ class _ChannelsScreenState extends State try { await connector.deleteChannel(channel.index); - await channelMessageStore.clearChannelMessages(channel.index); - await imageStore?.deleteImagesForChannel(channel.index); - if (!context.mounted) return; showDismissibleSnackBar( diff --git a/lib/services/image_chunk_transport.dart b/lib/services/image_chunk_transport.dart index 90483d84..5bacd78d 100644 --- a/lib/services/image_chunk_transport.dart +++ b/lib/services/image_chunk_transport.dart @@ -633,6 +633,10 @@ enum ImageReassemblyFailureReason { /// Dropped by [ImageReassembler.clear] (disconnect / new session). disconnected, + + /// Dropped by [ImageReassembler.clearChannel] because the radio slot it + /// arrived on now holds a different channel. + channelChanged, } /// A fully reassembled image. @@ -878,6 +882,34 @@ class ImageReassembler { } } + /// Drops every stream that arrived on [channelIndex], whose radio slot now + /// holds a different channel, so a new image there can never be completed + /// with the old channel's bytes. In-progress streams are reported through + /// [onFailed] so their bubbles stop showing "receiving". + void clearChannel(int channelIndex, {DateTime? now}) { + final at = now ?? _clock(); + _recentlyCompleted.removeWhere( + (key, _) => key.channelIndex == channelIndex, + ); + final dropped = _pending.values + .where((entry) => entry.key.channelIndex == channelIndex) + .toList(); + for (final entry in dropped) { + _pending.remove(entry.key); + onFailed?.call( + ImageReassemblyFailure( + key: entry.key, + total: entry.total, + receivedDataChunks: entry.bodies.length, + hadParity: entry.hasParity, + firstSeen: entry.firstSeen, + expiredAt: at, + reason: ImageReassemblyFailureReason.channelChanged, + ), + ); + } + } + /// Feeds one received GRP_DATA blob. /// /// [now] overrides the clock for tests. Expired entries are swept first, so diff --git a/lib/services/received_image_store.dart b/lib/services/received_image_store.dart index e7d07339..94ee9ee1 100644 --- a/lib/services/received_image_store.dart +++ b/lib/services/received_image_store.dart @@ -159,6 +159,11 @@ class ReceivedImageEntry { final int imgId; final int channelIndex; + /// [Channel.storageId] of the channel the image belongs to. [channelIndex] + /// is the radio slot it arrived on, which another channel may reuse later. + /// Null only for entries written before channel IDs existed. + final String? channelId; + /// Local clock at the first chunk — code 27 carries no timestamp. final DateTime firstSeen; @@ -221,6 +226,7 @@ class ReceivedImageEntry { required this.senderPrefix, required this.imgId, required this.channelIndex, + this.channelId, required this.firstSeen, required this.state, required this.receivedChunks, @@ -259,6 +265,7 @@ class ReceivedImageEntry { static const Object _unset = Object(); ReceivedImageEntry copyWith({ + String? channelId, ReceivedImageState? state, int? receivedChunks, int? totalChunks, @@ -281,6 +288,7 @@ class ReceivedImageEntry { senderPrefix: senderPrefix, imgId: imgId, channelIndex: channelIndex, + channelId: channelId ?? this.channelId, firstSeen: firstSeen, state: state ?? this.state, receivedChunks: receivedChunks ?? this.receivedChunks, @@ -309,6 +317,7 @@ class ReceivedImageEntry { 'senderPrefix': senderPrefix, 'imgId': imgId, 'channelIndex': channelIndex, + if (channelId != null) 'channelId': channelId, 'firstSeenMs': firstSeen.millisecondsSinceEpoch, 'state': state.name, 'receivedChunks': receivedChunks, @@ -335,6 +344,7 @@ class ReceivedImageEntry { senderPrefix: json['senderPrefix'] as int? ?? 0, imgId: json['imgId'] as int? ?? 0, channelIndex: json['channelIndex'] as int? ?? 0, + channelId: json['channelId'] as String?, firstSeen: DateTime.fromMillisecondsSinceEpoch( json['firstSeenMs'] as int? ?? 0, ), @@ -760,6 +770,7 @@ class ReceivedImageStore extends ChangeNotifier { Future handleOutcome( ImageChunkOutcome outcome, { required int channelIndex, + String? channelId, DateTime? at, }) async { final now = at ?? _clock(); @@ -810,6 +821,8 @@ class ReceivedImageStore extends ChangeNotifier { .toInt(), totalChunks: header.total, error: null, + // A first chunk seen before its slot had an ID gets one now. + channelId: existing.channelId ?? channelId, ); return _store(updated); } @@ -826,6 +839,7 @@ class ReceivedImageStore extends ChangeNotifier { senderPrefix: header.senderPrefix, imgId: header.imgId, channelIndex: channelIndex, + channelId: channelId, firstSeen: now, state: ReceivedImageState.receiving, receivedChunks: counts, @@ -861,13 +875,14 @@ class ReceivedImageStore extends ChangeNotifier { case ImageChunkStatus.completed: final result = outcome.result; if (result == null) return null; - return _handleCompleted(result, now); + return _handleCompleted(result, now, channelId); } } Future _handleCompleted( ImageReassemblyResult result, DateTime now, + String? channelId, ) async { final key = result.key; var entry = entryForKey(key); @@ -884,11 +899,14 @@ class ReceivedImageStore extends ChangeNotifier { senderPrefix: key.senderPrefix, imgId: key.imgId, channelIndex: key.channelIndex, + channelId: channelId, firstSeen: now, state: ReceivedImageState.receiving, receivedChunks: result.chunkCount, totalChunks: result.chunkCount, ); + } else if (entry.channelId == null && channelId != null) { + entry = entry.copyWith(channelId: channelId); } final metadata = result.metadata; @@ -1000,6 +1018,7 @@ class ReceivedImageStore extends ChangeNotifier { /// ```dart /// final entry = await receivedImageStore.registerOutgoing( /// channelIndex: channelIndex, + /// channelId: channel.storageId, /// senderPrefix: selfPrefix, // same 16 bits the chunk header carries /// imgId: chunkSet.imgId, /// previewPng: preview.croppedPngBytes, // the 512x512 crop, NOT a decode @@ -1015,6 +1034,7 @@ class ReceivedImageStore extends ChangeNotifier { /// memory beyond the encode that already ran. Future registerOutgoing({ required int channelIndex, + String? channelId, required int senderPrefix, required int imgId, required Uint8List previewPng, @@ -1038,6 +1058,7 @@ class ReceivedImageStore extends ChangeNotifier { senderPrefix: senderPrefix, imgId: imgId, channelIndex: channelIndex, + channelId: channelId, firstSeen: now, state: ReceivedImageState.decoded, receivedChunks: chunkCount, @@ -1429,9 +1450,9 @@ class ReceivedImageStore extends ChangeNotifier { /// /// Returns the stream ids that were removed, so the caller can strip their /// sentinels from the channel's message list in one pass. - Future> deleteImagesForChannel(int channelIndex) async { + Future> deleteImagesForChannelId(String channelId) async { final doomed = _entries.values - .where((e) => e.channelIndex == channelIndex) + .where((e) => e.channelId == channelId) .map((e) => e.streamId) .toList(); for (final streamId in doomed) { @@ -1440,6 +1461,32 @@ class ReceivedImageStore extends ChangeNotifier { return doomed; } + /// Images of [channelId], newest first. + List entriesForChannel(String? channelId) { + if (channelId == null) return const []; + return entries.where((e) => e.channelId == channelId).toList(); + } + + /// Gives entries saved before channel IDs existed the ID of the channel + /// their slot held then ([slotIds], from the radio's cached channel list). + /// The store is app-wide, so with several radios the first one migrated + /// claims the unstamped images. + Future stampLegacyChannelIds(Map slotIds) async { + for (final entry in _entries.values.toList()) { + if (entry.channelId != null) continue; + final channelId = slotIds[entry.channelIndex]; + if (channelId == null) continue; + await _store(entry.copyWith(channelId: channelId)); + } + } + + /// Forgets which in-progress streams arrived on [channelIndex] after the + /// radio slot was given to another channel, so a new image on that slot + /// never continues an old one. + void forgetChannelSlot(int channelIndex) { + _byKey.removeWhere((key, _) => key.channelIndex == channelIndex); + } + /// Deletes an image for each sentinel that is still present in a channel's /// message list, and drops everything else this store holds for that channel. /// diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 3d276108..a5adc395 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -1,13 +1,11 @@ import 'dart:convert'; import 'dart:typed_data'; import 'package:meshcore_open/utils/app_logger.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import '../models/channel_message.dart'; import '../models/message.dart' show legacyAwareReceivedAt; import '../models/translation_support.dart'; import '../helpers/smaz.dart'; -import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ChannelMessageStore { @@ -30,11 +28,13 @@ class ChannelMessageStore { /// created by a screen to clear a key also resets the connector's view. static final Map> _archived = {}; + String _keyForChannel(String channelId) => '${keyFor}_$channelId'; + /// Save messages for a specific channel: [messages] is the in-memory /// window (oldest first) and is written after the archived entries that /// sit ahead of it in storage. Future saveChannelMessages( - int channelIndex, + String channelId, List messages, ) async { if (publicKeyHex.isEmpty) { @@ -44,11 +44,11 @@ class ChannelMessageStore { return; } final prefs = PrefsManager.instance; - final key = '$keyFor$channelIndex'; + final key = _keyForChannel(channelId); final visibleJson = messages.map(_messageToJson).toList(); final archived = _archived[key] ?? - _unreconciledArchive(_readStored(prefs, channelIndex), visibleJson); + _unreconciledArchive(prefs.getString(key), visibleJson); final overflow = archived.length + visibleJson.length - maxStoredMessages; if (overflow > 0) { archived.removeRange(0, overflow.clamp(0, archived.length)); @@ -59,22 +59,22 @@ class ChannelMessageStore { } /// Records [olderMessages] as the stored entries that precede the - /// in-memory window for [channelIndex]. - void setArchived(int channelIndex, List olderMessages) { - _archived['$keyFor$channelIndex'] = olderMessages + /// in-memory window for [channelId]. + void setArchived(String channelId, List olderMessages) { + _archived[_keyForChannel(channelId)] = olderMessages .map((message) => jsonEncode(_messageToJson(message))) .toList(); } /// Number of stored entries ahead of the in-memory window, or null when /// the window has not been reconciled with storage. - int? archivedCount(int channelIndex) => - _archived['$keyFor$channelIndex']?.length; + int? archivedCount(String channelId) => + _archived[_keyForChannel(channelId)]?.length; /// Removes the newest [count] archived entries after they were paged back /// into the in-memory window. - void unarchiveNewest(int channelIndex, int count) { - final archived = _archived['$keyFor$channelIndex']; + void unarchiveNewest(String channelId, int count) { + final archived = _archived[_keyForChannel(channelId)]; if (archived == null || count <= 0) return; archived.removeRange( (archived.length - count).clamp(0, archived.length), @@ -84,11 +84,11 @@ class ChannelMessageStore { /// Drops the archive bookkeeping, for one channel or all of them, when the /// matching in-memory window is discarded. - void forgetArchive([int? channelIndex]) { - if (channelIndex == null) { + void forgetArchive([String? channelId]) { + if (channelId == null) { _archived.clear(); } else { - _archived.remove('$keyFor$channelIndex'); + _archived.remove(_keyForChannel(channelId)); } } @@ -118,41 +118,17 @@ class ChannelMessageStore { return 'fallback:${json['timestamp']}:${json['senderName']}:${json['text']}'; } - /// Reads the stored JSON for [channelIndex], migrating the legacy unscoped - /// key on first access. - String? _readStored(SharedPreferences prefs, int channelIndex) { - final key = '$keyFor$channelIndex'; - final oldKey = '$_keyPrefix$channelIndex'; - final jsonString = prefs.getString(key); - if ((jsonString == null || jsonString.isEmpty) && - canMigrateLegacyKeys(publicKeyHex)) { - // Attempt migration from legacy unscoped key on first load - final legacyJsonString = prefs.getString(oldKey); - prefs.remove(oldKey); - if (legacyJsonString != null && legacyJsonString.isNotEmpty) { - appLogger.info( - 'Migrating channel messages from legacy key $oldKey to scoped key $key', - ); - prefs.setString(key, legacyJsonString); - return legacyJsonString; - } - } - return jsonString; - } - /// Load messages for a specific channel - Future> loadChannelMessages(int channelIndex) async { + Future> loadChannelMessages(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel messages.', ); return []; } - final prefs = PrefsManager.instance; - String? jsonString = _readStored(prefs, channelIndex); - if (jsonString == null || jsonString.isEmpty) { - jsonString = prefs.getString(keyFor); - } + final jsonString = PrefsManager.instance.getString( + _keyForChannel(channelId), + ); if (jsonString == null || jsonString.isEmpty) { return []; } @@ -161,7 +137,7 @@ class ChannelMessageStore { jsonList = jsonDecode(jsonString) as List; } catch (e) { appLogger.warn( - 'Stored messages for channel $channelIndex are unreadable: $e', + 'Stored messages for channel $channelId are unreadable: $e', ); return []; } @@ -177,9 +153,9 @@ class ChannelMessageStore { } /// Clear messages for a specific channel - Future clearChannelMessages(int channelIndex) async { + Future clearChannelMessages(String channelId) async { final prefs = PrefsManager.instance; - final key = '$keyFor$channelIndex'; + final key = _keyForChannel(channelId); _archived[key] = []; await prefs.remove(key); } diff --git a/lib/storage/channel_order_store.dart b/lib/storage/channel_order_store.dart index 3bc0c7dc..98eda49f 100644 --- a/lib/storage/channel_order_store.dart +++ b/lib/storage/channel_order_store.dart @@ -1,8 +1,9 @@ import 'dart:convert'; import '../utils/app_logger.dart'; -import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; +/// Persists the user's channel order as a list of channel storage IDs +/// ([Channel.storageId]), so the order follows channels across slots. class ChannelOrderStore { static const String _keyPrefix = 'channel_order_'; @@ -12,53 +13,31 @@ class ChannelOrderStore { String get keyFor => '$_keyPrefix$publicKeyHex'; - Future saveChannelOrder(List order) async { + Future saveChannelOrder(List order) async { if (publicKeyHex.isEmpty) { appLogger.warn('Public key hex is not set. Cannot save channel order.'); return; } - final prefs = PrefsManager.instance; - await prefs.setString(keyFor, jsonEncode(order)); + await PrefsManager.instance.setString(keyFor, jsonEncode(order)); } - Future> loadChannelOrder() async { + Future> loadChannelOrder() async { if (publicKeyHex.isEmpty) { appLogger.warn('Public key hex is not set. Cannot load channel order.'); return []; } - final prefs = PrefsManager.instance; - String? jsonString = prefs.getString(keyFor); - if ((jsonString == null || jsonString.isEmpty) && - canMigrateLegacyKeys(publicKeyHex)) { - // Attempt migration from legacy unscoped key on first load - final legacyJsonString = prefs.getString(_keyPrefix); - prefs.remove(_keyPrefix); - if (legacyJsonString != null && legacyJsonString.isNotEmpty) { - appLogger.info( - 'Migrating channel order from legacy key $_keyPrefix to scoped key $keyFor', - ); - await prefs.setString(keyFor, legacyJsonString); - jsonString = legacyJsonString; - } - } + final jsonString = PrefsManager.instance.getString(keyFor); if (jsonString == null || jsonString.isEmpty) { return []; } try { final decoded = jsonDecode(jsonString); if (decoded is List) { - return decoded - .map((value) => value is int ? value : int.tryParse('$value')) - .whereType() - .toList(); + return decoded.whereType().toList(); } } catch (_) { - // fall through to legacy parse + // Unreadable order: fall back to slot order. } - return jsonString - .split(',') - .map((value) => int.tryParse(value)) - .whereType() - .toList(); + return []; } } diff --git a/lib/storage/channel_region_store.dart b/lib/storage/channel_region_store.dart index caf89887..16a5a427 100644 --- a/lib/storage/channel_region_store.dart +++ b/lib/storage/channel_region_store.dart @@ -43,30 +43,31 @@ class ChannelRegionStore { await PrefsManager.instance.setString(_defaultKey, region); } - Future loadRegion(int channelIndex) async { + String _keyForChannel(String channelId) => '${keyFor}_$channelId'; + + Future loadRegion(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel settings.', ); return ''; } - final prefs = PrefsManager.instance; - final key = '$keyFor$channelIndex'; - String? region = prefs.getString(key); - return region ?? ''; + return PrefsManager.instance.getString(_keyForChannel(channelId)) ?? ''; } - Future saveRegion(int channelIndex, String region) async { + Future saveRegion(String channelId, String region) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot save channel settings.', ); return ''; } - - final prefs = PrefsManager.instance; - final key = '$keyFor$channelIndex'; - await prefs.setString(key, region); + await PrefsManager.instance.setString(_keyForChannel(channelId), region); return region; } + + Future clearRegion(String channelId) async { + if (publicKeyHex.isEmpty) return; + await PrefsManager.instance.remove(_keyForChannel(channelId)); + } } diff --git a/lib/storage/channel_settings_store.dart b/lib/storage/channel_settings_store.dart index c20daad4..c02e142e 100644 --- a/lib/storage/channel_settings_store.dart +++ b/lib/storage/channel_settings_store.dart @@ -1,5 +1,4 @@ import '../utils/app_logger.dart'; -import 'legacy_key_migration.dart'; import 'prefs_manager.dart'; class ChannelSettingsStore { @@ -15,105 +14,83 @@ class ChannelSettingsStore { String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex'; String get keyForUrlImages => '$_urlImagesKeyPrefix$publicKeyHex'; - Future loadSmazEnabled(int channelIndex) async { + String _smazKey(String channelId) => '${keyFor}_$channelId'; + String _cyr2LatKey(String channelId) => '${keyForCyr2Lat}_$channelId'; + String _cyr2LatProfileKey(String channelId) => + '${keyForCyr2Lat}_profile_$channelId'; + String _urlImagesKey(String channelId) => '${keyForUrlImages}_$channelId'; + + Future loadSmazEnabled(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel settings.', ); return false; } - final prefs = PrefsManager.instance; - final key = '$keyFor$channelIndex'; - final oldKey = '$_keyPrefix$channelIndex'; - bool? enabled = prefs.getBool(key); - if (enabled == null && canMigrateLegacyKeys(publicKeyHex)) { - // Attempt migration from legacy unscoped key on first load - enabled = prefs.getBool(oldKey); - prefs.remove(oldKey); - if (enabled != null) { - appLogger.info( - 'Migrating channel settings from legacy key $oldKey to scoped key $key', - ); - await prefs.setBool(key, enabled); - } - } - return enabled ?? false; + return PrefsManager.instance.getBool(_smazKey(channelId)) ?? false; } - Future saveSmazEnabled(int channelIndex, bool enabled) async { + Future saveSmazEnabled(String channelId, bool enabled) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot save channel settings.', ); return; } - final prefs = PrefsManager.instance; - final key = '$keyFor$channelIndex'; - await prefs.setBool(key, enabled); + await PrefsManager.instance.setBool(_smazKey(channelId), enabled); } - Future loadCyr2LatEnabled(int channelIndex) async { + Future loadCyr2LatEnabled(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel Cyr2Lat settings.', ); return false; } - final prefs = PrefsManager.instance; - final key = '$keyForCyr2Lat$channelIndex'; - return prefs.getBool(key) ?? false; + return PrefsManager.instance.getBool(_cyr2LatKey(channelId)) ?? false; } - Future saveCyr2LatEnabled(int channelIndex, bool enabled) async { + Future saveCyr2LatEnabled(String channelId, bool enabled) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot save channel Cyr2Lat settings.', ); return; } - final prefs = PrefsManager.instance; - final key = '$keyForCyr2Lat$channelIndex'; - await prefs.setBool(key, enabled); + await PrefsManager.instance.setBool(_cyr2LatKey(channelId), enabled); } - Future loadUrlImagesEnabled(int channelIndex) async { + Future loadUrlImagesEnabled(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel URL image settings.', ); return false; } - final prefs = PrefsManager.instance; - final key = '$keyForUrlImages$channelIndex'; - return prefs.getBool(key) ?? false; + return PrefsManager.instance.getBool(_urlImagesKey(channelId)) ?? false; } - Future saveUrlImagesEnabled(int channelIndex, bool enabled) async { + Future saveUrlImagesEnabled(String channelId, bool enabled) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot save channel URL image settings.', ); return; } - await PrefsManager.instance.setBool( - '$keyForUrlImages$channelIndex', - enabled, - ); + await PrefsManager.instance.setBool(_urlImagesKey(channelId), enabled); } - Future loadCyr2LatProfileId(int channelIndex) async { + Future loadCyr2LatProfileId(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel settings.', ); return null; } - final prefs = PrefsManager.instance; - final key = '${keyForCyr2Lat}profile_$channelIndex'; - return prefs.getString(key); + return PrefsManager.instance.getString(_cyr2LatProfileKey(channelId)); } - Future saveCyr2LatProfileId(int channelIndex, String? profileId) async { + Future saveCyr2LatProfileId(String channelId, String? profileId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot save channel settings.', @@ -121,11 +98,21 @@ class ChannelSettingsStore { return; } final prefs = PrefsManager.instance; - final key = '${keyForCyr2Lat}profile_$channelIndex'; + final key = _cyr2LatProfileKey(channelId); if (profileId == null) { await prefs.remove(key); } else { await prefs.setString(key, profileId); } } + + /// Removes every setting stored for [channelId]. + Future clearChannel(String channelId) async { + if (publicKeyHex.isEmpty) return; + final prefs = PrefsManager.instance; + await prefs.remove(_smazKey(channelId)); + await prefs.remove(_cyr2LatKey(channelId)); + await prefs.remove(_cyr2LatProfileKey(channelId)); + await prefs.remove(_urlImagesKey(channelId)); + } } diff --git a/lib/storage/channel_storage_migration.dart b/lib/storage/channel_storage_migration.dart new file mode 100644 index 00000000..80fb6187 --- /dev/null +++ b/lib/storage/channel_storage_migration.dart @@ -0,0 +1,186 @@ +import 'dart:convert'; + +import '../utils/app_logger.dart'; +import 'channel_message_store.dart'; +import 'channel_store.dart'; +import 'legacy_key_migration.dart'; +import 'prefs_manager.dart'; + +/// One-shot move of a radio's per-channel data from slot-index keys +/// (``) to channel-ID keys (`_`). +/// +/// The slot -> PSK mapping comes from the radio's cached channel list, which is +/// the mapping the legacy data was written under. Legacy keys of slots with no +/// cached PSK are left alone and never read again. +class ChannelStorageMigration { + static const String _doneKeyPrefix = 'channel_storage_v2_'; + + static const String _messagesPrefix = 'channel_messages_'; + static const String _smazPrefix = 'channel_smaz_'; + static const String _cyr2latPrefix = 'channel_cyr2lat_'; + static const String _urlImagesPrefix = 'channel_url_images_'; + static const String _regionPrefix = 'channel_region_'; + static const String _orderPrefix = 'channel_order_'; + + /// Migrates [scope] (first 10 hex chars of the radio's public key) and + /// returns the slot -> channel ID mapping it used. Returns an empty map when + /// the scope was already migrated or must not adopt legacy data. + static Future> migrate(String scope) async { + if (scope.isEmpty || !canMigrateLegacyKeys(scope)) return {}; + final prefs = PrefsManager.instance; + final doneKey = '$_doneKeyPrefix$scope'; + if (prefs.getBool(doneKey) == true) return {}; + + final channelStore = ChannelStore()..setPublicKeyHex = scope; + final cached = await channelStore.loadChannels(); + final slotIds = {}; + for (final channel in cached) { + final id = channel.storageId; + if (id != null) slotIds[channel.index] = id; + } + + final slots = slotIds.keys.toList()..sort(); + for (final slot in slots) { + final id = slotIds[slot]!; + await _moveMessages(scope, slot, id); + await _moveBool( + '$_smazPrefix$scope', + slot, + id, + legacyPrefix: _smazPrefix, + ); + await _moveBool('$_cyr2latPrefix$scope', slot, id); + await _moveBool('$_urlImagesPrefix$scope', slot, id); + await _moveString( + '$_cyr2latPrefix${scope}profile_$slot', + '$_cyr2latPrefix${scope}_profile_$id', + ); + await _moveString( + '$_regionPrefix$scope$slot', + '$_regionPrefix${scope}_$id', + ); + } + await _migrateOrder(scope, slotIds); + + await prefs.setBool(doneKey, true); + await channelStore.saveSlotChannelIds(slotIds); + if (slotIds.isNotEmpty) { + appLogger.info( + 'Moved channel data for ${slotIds.length} slots of $scope to channel IDs', + ); + } + return slotIds; + } + + static Future _moveMessages(String scope, int slot, String id) async { + final prefs = PrefsManager.instance; + final oldKey = '$_messagesPrefix$scope$slot'; + final legacyKey = '$_messagesPrefix$slot'; + final newKey = '$_messagesPrefix${scope}_$id'; + var json = prefs.getString(oldKey); + if (json == null || json.isEmpty) json = prefs.getString(legacyKey); + if (json != null && json.isNotEmpty) { + final existing = prefs.getString(newKey); + // Two slots holding the same PSK now share one history. + await prefs.setString( + newKey, + existing == null || existing.isEmpty + ? json + : _mergeMessages(existing, json), + ); + } + // Old keys go only after the new one is written, so an interrupted run + // loses nothing; the next launch repeats it. + await prefs.remove(oldKey); + await prefs.remove(legacyKey); + } + + static String _mergeMessages(String a, String b) { + try { + // A rerun after an interrupted migration merges a history into + // itself, so drop entries already present. + final seen = {}; + final merged = + [...jsonDecode(a) as List, ...jsonDecode(b) as List] + .whereType>() + .where((m) => seen.add(_mergeKey(m))) + .toList(); + merged.sort( + (x, y) => ((x['timestamp'] as int?) ?? 0).compareTo( + (y['timestamp'] as int?) ?? 0, + ), + ); + final overflow = merged.length - ChannelMessageStore.maxStoredMessages; + if (overflow > 0) merged.removeRange(0, overflow); + return jsonEncode(merged); + } catch (_) { + return a; + } + } + + static String _mergeKey(Map json) { + final messageId = json['messageId']; + if (messageId is String && messageId.isNotEmpty) return 'id:$messageId'; + return 'fallback:${json['timestamp']}:${json['senderName']}:${json['text']}'; + } + + static Future _moveBool( + String scopedPrefix, + int slot, + String id, { + String? legacyPrefix, + }) async { + final prefs = PrefsManager.instance; + final oldKey = '$scopedPrefix$slot'; + final newKey = '${scopedPrefix}_$id'; + final legacyKey = legacyPrefix == null ? null : '$legacyPrefix$slot'; + var value = prefs.get(oldKey); + if (value == null && legacyKey != null) value = prefs.get(legacyKey); + if (value is bool && !prefs.containsKey(newKey)) { + await prefs.setBool(newKey, value); + } + await prefs.remove(oldKey); + if (legacyKey != null) await prefs.remove(legacyKey); + } + + static Future _moveString(String oldKey, String newKey) async { + final prefs = PrefsManager.instance; + final value = prefs.get(oldKey); + if (value is String && !prefs.containsKey(newKey)) { + await prefs.setString(newKey, value); + } + await prefs.remove(oldKey); + } + + static Future _migrateOrder( + String scope, + Map slotIds, + ) async { + final prefs = PrefsManager.instance; + final key = '$_orderPrefix$scope'; + var raw = prefs.getString(key); + if (raw == null || raw.isEmpty) raw = prefs.getString(_orderPrefix); + if (raw == null || raw.isEmpty) return; + final slots = []; + try { + final decoded = jsonDecode(raw); + if (decoded is List) { + // String entries are channel IDs from an interrupted earlier run. + if (decoded.any((value) => value is String)) return; + slots.addAll(decoded.whereType()); + } else if (decoded is int) { + // A one-slot legacy comma-separated list parses as a bare number. + slots.add(decoded); + } + } catch (_) { + slots.addAll(raw.split(',').map(int.tryParse).whereType()); + } + final ids = []; + for (final slot in slots) { + final id = slotIds[slot]; + if (id != null && !ids.contains(id)) ids.add(id); + } + await prefs.setString(key, jsonEncode(ids)); + await prefs.remove(_orderPrefix); + } +} diff --git a/lib/storage/channel_store.dart b/lib/storage/channel_store.dart index 5736af1a..2de42fa5 100644 --- a/lib/storage/channel_store.dart +++ b/lib/storage/channel_store.dart @@ -8,6 +8,7 @@ import 'prefs_manager.dart'; class ChannelStore { static const String _keyPrefix = 'channels'; + static const String _slotIdsKeyPrefix = 'channel_slot_ids_'; String publicKeyHex = ''; set setPublicKeyHex(String value) => publicKeyHex = value.length >= 10 ? value.substring(0, 10) : ''; @@ -70,6 +71,38 @@ class ChannelStore { await prefs.setString(keyFor, jsonEncode(jsonList)); } + String get _slotIdsKey => '$_slotIdsKeyPrefix$publicKeyHex'; + + /// The slot -> [Channel.storageId] map confirmed by the last channel sync, + /// used to spot slots another app changed while we were away. + Future> loadSlotChannelIds() async { + if (publicKeyHex.isEmpty) return {}; + final jsonString = PrefsManager.instance.getString(_slotIdsKey); + if (jsonString == null || jsonString.isEmpty) return {}; + try { + final decoded = jsonDecode(jsonString); + if (decoded is! Map) return {}; + final ids = {}; + for (final entry in decoded.entries) { + final slot = int.tryParse('${entry.key}'); + final id = entry.value; + if (slot != null && id is String && id.isNotEmpty) ids[slot] = id; + } + return ids; + } catch (e) { + appLogger.warn('Stored channel slot map is unreadable: $e'); + return {}; + } + } + + Future saveSlotChannelIds(Map ids) async { + if (publicKeyHex.isEmpty) return; + await PrefsManager.instance.setString( + _slotIdsKey, + jsonEncode({for (final e in ids.entries) '${e.key}': e.value}), + ); + } + Map _toJson(Channel channel) { return { 'index': channel.index, diff --git a/test/connector/channel_slot_map_test.dart b/test/connector/channel_slot_map_test.dart new file mode 100644 index 00000000..acd0d19e --- /dev/null +++ b/test/connector/channel_slot_map_test.dart @@ -0,0 +1,346 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/review_mode/review_script.dart'; +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:pointycastle/export.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _scope = ReviewRadio.storagePrefix; +const _queuedHikingText = 'Planning to leave the trailhead at 8 on Saturday.'; + +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: 20)); + } +} + +Uint8List _psk(int slot) => + Channel.parsePskHex(ReviewScript.channels[slot].pskHex); + +String _id(Uint8List psk) => Channel.storageIdForPsk(psk)!; + +String _messagesKey(String channelId) => + 'channel_messages_${_scope}_$channelId'; + +List _storedTexts(String channelId) { + final raw = PrefsManager.instance.getString(_messagesKey(channelId)); + if (raw == null) return []; + return [ + for (final entry in jsonDecode(raw) as List) + (entry as Map)['text'] as String, + ]; +} + +// SharedPreferences updates its in-memory cache synchronously. +void _seedMessages(String channelId, List texts) => + PrefsManager.instance.setString( + _messagesKey(channelId), + jsonEncode([ + for (var i = 0; i < texts.length; i++) + { + 'senderName': 'Ghost', + 'text': texts[i], + 'timestamp': 1000 * (i + 1), + 'isOutgoing': false, + 'status': ChannelMessageStatus.sent.index, + 'messageId': 'seed-$channelId-$i', + 'plainText': true, + }, + ]), + ); + +void _seedSlotMap(Map slotIds) => PrefsManager.instance.setString( + 'channel_slot_ids_$_scope', + jsonEncode({for (final e in slotIds.entries) '${e.key}': e.value}), +); + +/// Review radio that records every frame the app sends and can swallow some. +class _TestRadio extends ReviewRadio { + _TestRadio({this.swallow, this.afterHandle}) + : super( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(milliseconds: 50), + replyDelay: const Duration(hours: 1), + ); + + final bool Function(Uint8List frame)? swallow; + final void Function(_TestRadio radio, Uint8List frame)? afterHandle; + final List sent = []; + + @override + void handle(Uint8List frame) { + sent.add(Uint8List.fromList(frame)); + if (swallow?.call(frame) ?? false) return; + super.handle(frame); + afterHandle?.call(this, frame); + } + + void deliver(Uint8List frame) => super.handle(frame); + + List codes() => [for (final f in sent) f.isEmpty ? -1 : f[0]]; +} + +late MeshCoreConnector _connector; + +/// Connects a fresh review radio. [seed] runs after review mode has cleared +/// its storage and before SELF_INFO, standing in for a previous session. +Future _connect(_TestRadio radio, {void Function()? seed}) async { + _connector.reviewRadioFactoryForTest = () { + // beginReviewModeSession wipes the review scope before this runs. + seed?.call(); + return radio; + }; + await _connector.connectReview(); + addTearDown(_connector.disconnect); + await _waitFor(() => _connector.channelMapConfirmed); +} + +Channel _channelAt(int slot) => + _connector.channels.firstWhere((c) => c.index == slot); + +List _texts(int slot) => + _connector.getChannelMessages(_channelAt(slot)).map((m) => m.text).toList(); + +Uint8List _logRxGroupText(Uint8List psk, String text, int timestampSecs) { + final plain = BytesBuilder() + ..add( + Uint8List(4) + ..buffer.asByteData().setUint32(0, timestampSecs, Endian.little), + ) + ..addByte(0) + ..add(utf8.encode(text)) + ..addByte(0); + final padded = Uint8List(((plain.length + 15) ~/ 16) * 16) + ..setRange(0, plain.length, plain.toBytes()); + final cipher = ECBBlockCipher(AESEngine())..init(true, KeyParameter(psk)); + final encrypted = Uint8List(padded.length); + for (var i = 0; i < padded.length; i += 16) { + cipher.processBlock(padded, i, encrypted, i); + } + final key32 = Uint8List(32)..setRange(0, 16, psk); + final mac = crypto.Hmac(crypto.sha256, key32).convert(encrypted).bytes; + final channelHash = crypto.sha256.convert(psk).bytes[0]; + return Uint8List.fromList([ + pushCodeLogRxData, + 40, // snr + 0xA0, // rssi + 0x15, // flood route, GRP_TXT payload + 0x00, // no path + channelHash, + mac[0], + mac[1], + ...encrypted, + ]); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + _connector = MeshCoreConnector(); + final retryService = MessageRetryService(); + _connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + addTearDown(() { + _connector.dispose(); + retryService.dispose(); + }); + }); + + tearDown(() => _connector.channelSyncTimeoutMs = 2000); + + final hikingId = _id(_psk(1)); + final ghostPsk = Uint8List.fromList(List.generate(16, (i) => 200 - i)); + final ghostId = _id(ghostPsk); + + test('a slot reused by another channel while away starts clean', () async { + await _connect( + _TestRadio(), + seed: () { + // Last session slot 1 held the ghost channel. + _seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))}); + _seedMessages(ghostId, ['ghost message']); + }, + ); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + + expect(_channelAt(1).name, 'Hiking Group'); + expect(_texts(1), isNot(contains('ghost message'))); + // The old channel's history is kept under its own ID. + expect(_storedTexts(ghostId), ['ghost message']); + expect(_storedTexts(hikingId), contains(_queuedHikingText)); + expect(_connector.channelIdForSlot(1), hikingId); + expect( + jsonDecode(PrefsManager.instance.getString('channel_slot_ids_$_scope')!), + containsPair('1', hikingId), + ); + }); + + test('a PSK edit in place starts clean, and re-adding the old PSK in ' + 'another slot brings its history back', () async { + await _connect(_TestRadio()); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + await _connector.setChannelSmazEnabled(1, true); + + await _connector.setChannel(1, 'Hiking Group', ghostPsk); + expect(_connector.channelIdForSlot(1), ghostId); + expect(_texts(1), isEmpty); + expect(_connector.isChannelSmazEnabled(1), isFalse); + expect(_storedTexts(hikingId), contains(_queuedHikingText)); + + await _connector.setChannel(6, 'Hiking Group', _psk(1)); + expect(_connector.channelIdForSlot(6), hikingId); + expect(_texts(6), contains(_queuedHikingText)); + expect(_connector.isChannelSmazEnabled(6), isTrue); + + // Restored history belongs to slot 6 now, so deleting from it works. + final restored = _connector + .getChannelMessages(_channelAt(6)) + .firstWhere((m) => m.text == _queuedHikingText); + expect(restored.channelIndex, 6); + await _connector.deleteChannelMessage(restored); + expect(_texts(6), isNot(contains(_queuedHikingText))); + expect(_storedTexts(hikingId), isNot(contains(_queuedHikingText))); + }); + + test( + 'a PSK edit in place keeps the channel\'s place in the custom order', + () async { + await _connect(_TestRadio()); + await _connector.setChannelOrder([1, 0, 2]); + expect(_connector.channels.first.index, 1); + + await _connector.setChannel(1, 'Hiking Group', ghostPsk); + expect(_connector.channels.first.index, 1); + }, + ); + + test('deleting a channel clears its stored history', () async { + await _connect(_TestRadio()); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + expect(_storedTexts(hikingId), isNotEmpty); + + await _connector.deleteChannel(1); + expect(_storedTexts(hikingId), isEmpty); + }); + + test('MSG_WAITING before the channel sync waits for the slot map', () async { + // DEVICE_INFO is held back so MSG_WAITING lands between SELF_INFO and the + // start of the channel sync. + late final _TestRadio radio; + var deviceInfoHeld = false; + radio = _TestRadio( + swallow: (frame) { + if (frame[0] != cmdDeviceQuery || deviceInfoHeld) return false; + deviceInfoHeld = true; + Future.delayed( + const Duration(milliseconds: 400), + () => radio.deliver(frame), + ); + return true; + }, + afterHandle: (radio, frame) { + if (frame[0] == cmdAppStart) { + radio.emitForTest(ReviewFrames.msgWaiting()); + } + }, + ); + await _connect(radio); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + + final codes = radio.codes(); + final firstSync = codes.indexOf(cmdSyncNextMessage); + final lastGetChannel = codes.lastIndexOf(cmdGetChannel); + expect(firstSync, isNonNegative); + expect(lastGetChannel, isNonNegative); + expect(firstSync, greaterThan(lastGetChannel)); + }); + + test('a slot that never answers retries the sync, then releases the ' + 'queue with the saved map', () async { + _connector.channelSyncTimeoutMs = 30; + final radio = _TestRadio( + swallow: (frame) => frame[0] == cmdGetChannel && frame[1] == 1, + ); + await _connect( + radio, + seed: () => _seedSlotMap({0: _id(_psk(0)), 1: hikingId, 2: _id(_psk(2))}), + ); + await _waitFor(() => _storedTexts(hikingId).contains(_queuedHikingText)); + + final firstSync = radio.codes().indexOf(cmdSyncNextMessage); + final passes = radio.sent + .take(firstSync) + .where((f) => f[0] == cmdGetChannel && f[1] == 0) + .length; + expect(passes, 3); + expect(_connector.channelIdForSlot(1), hikingId); + }); + + test('two slots with the same PSK share one history', () async { + final radio = _TestRadio(); + await _connect( + radio, + seed: () => radio.handle(buildSetChannelFrame(5, 'Hiking Twin', _psk(1))), + ); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + expect(_connector.channelIdForSlot(5), hikingId); + expect(_texts(5), _texts(1)); + + // Settings are stored per channel, so both slots see a change. + await _connector.setChannelSmazEnabled(5, true); + expect(_connector.isChannelSmazEnabled(1), isTrue); + await _connector.setChannelRegion(1, 'test-region'); + expect(_connector.getChannelRegion(5), 'test-region'); + + radio.emitForTest( + ReviewFrames.channelMessage( + channelIndex: 5, + sender: 'Sam', + message: 'from the twin slot', + timestampSecs: DateTime.now().millisecondsSinceEpoch ~/ 1000, + ), + ); + await _waitFor(() => _texts(1).contains('from the twin slot')); + expect(_texts(5), contains('from the twin slot')); + expect( + _storedTexts(hikingId).where((t) => t == 'from the twin slot'), + hasLength(1), + ); + }); + + test('an RX-log message is filed by its PSK-derived channel ID', () async { + final radio = _TestRadio(); + await _connect(radio); + final localId = _id(_psk(2)); + radio.emitForTest( + _logRxGroupText( + _psk(2), + 'Ranger Pat: heard over the air', + DateTime.now().millisecondsSinceEpoch ~/ 1000, + ), + ); + await _waitFor(() => _texts(2).contains('heard over the air')); + expect(_storedTexts(localId), contains('heard over the air')); + expect(_texts(1), isNot(contains('heard over the air'))); + }); +} diff --git a/test/image_chunk_transport_test.dart b/test/image_chunk_transport_test.dart index d5a2959b..83e2a919 100644 --- a/test/image_chunk_transport_test.dart +++ b/test/image_chunk_transport_test.dart @@ -330,6 +330,40 @@ void main() { ); expect(r.pendingCount, 2); }); + + test('clearChannel stops a reused slot finishing with old bytes', () { + final oldSet = buildImageChunks( + payload: payloadOf(300, seed: 1), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 9, + ); + final newPayload = payloadOf(300, seed: 2); + final newSet = buildImageChunks( + payload: newPayload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 9, + ); + expect(newSet.dataChunkCount, greaterThanOrEqualTo(2)); + final failures = []; + final r = ImageReassembler(onFailed: failures.add); + r.addChunk(oldSet.blobs[0], channelIndex: 3); + r.addChunk(oldSet.blobs[0], channelIndex: 4); + + r.clearChannel(3); + expect(failures.single.key.channelIndex, 3); + expect( + failures.single.reason, + ImageReassemblyFailureReason.channelChanged, + ); + expect(r.pendingKeys.single.channelIndex, 4); + + // Without the clear, these would complete with the old chunk 0. + final dataBlobs = newSet.blobs.sublist(0, newSet.dataChunkCount); + expect(feed(r, dataBlobs.sublist(1), channelIndex: 3), isNull); + expect(feed(r, [dataBlobs[0]], channelIndex: 3)!.data, newPayload); + }); }); group('parity recovery', () { diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index b96666e3..b2c8d698 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -604,6 +604,7 @@ void main() { () async { final store = ChannelMessageStore()..publicKeyHex = '1234567890'; final channelIndex = 1; + const channelId = '0123456789abcdef'; final rawPath = Uint8List(64) ..[0] = 0xBB @@ -623,11 +624,11 @@ void main() { final prefs = PrefsManager.instance; await prefs.setString( - '${store.keyFor}$channelIndex', + '${store.keyFor}_$channelId', jsonEncode(messageJson), ); - final messages = await store.loadChannelMessages(channelIndex); + final messages = await store.loadChannelMessages(channelId); expect(messages, hasLength(1)); expect(messages.first.pathLength, equals(1)); expect( diff --git a/test/models/received_at_test.dart b/test/models/received_at_test.dart index 4ffd05c3..3499a33f 100644 --- a/test/models/received_at_test.dart +++ b/test/models/received_at_test.dart @@ -36,6 +36,8 @@ ChannelMessage _ch( channelIndex: 0, ); +const _channelId = '0123456789abcdef'; + void main() { final base = DateTime(2026, 10, 1, 12); @@ -127,10 +129,10 @@ void main() { await _init(); final store = ChannelMessageStore()..setPublicKeyHex = _device; final received = base.add(const Duration(seconds: 42)); - await store.saveChannelMessages(0, [ + await store.saveChannelMessages(_channelId, [ _ch('one', timestamp: base, receivedAt: received), ]); - final loaded = await store.loadChannelMessages(0); + final loaded = await store.loadChannelMessages(_channelId); expect(loaded.single.receivedAt, received); expect(loaded.single.timestamp, base); }); @@ -167,14 +169,14 @@ void main() { 'plainText': true, }; await _init({ - 'channel_messages_${_device.substring(0, 10)}0': jsonEncode([ + 'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([ record('old', past), record('ahead', future), ]), }); final store = ChannelMessageStore()..setPublicKeyHex = _device; final before = DateTime.now(); - final loaded = await store.loadChannelMessages(0); + final loaded = await store.loadChannelMessages(_channelId); expect(loaded, hasLength(2)); expect( loaded[0].receivedAt.millisecondsSinceEpoch, diff --git a/test/services/received_image_store_test.dart b/test/services/received_image_store_test.dart index 6c7b2587..8dd9f0c8 100644 --- a/test/services/received_image_store_test.dart +++ b/test/services/received_image_store_test.dart @@ -210,6 +210,54 @@ void main() { expect(h.decoder.calls, 1); }); + test('a stream started before its slot had an ID picks one up', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + kImageChunkCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 5, + ); + expect(set.dataChunkCount, 3); + + final first = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + expect(first!.channelId, isNull); + // A second data chunk of three neither completes nor recovers it. + final second = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[1], channelIndex: 3), + channelIndex: 3, + channelId: 'chan-id', + ); + expect(second!.state, ReceivedImageState.receiving); + expect(second.streamId, first.streamId); + expect(second.channelId, 'chan-id'); + }); + + test('a stream completed after its slot got an ID keeps it', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 6, + ); + final first = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + expect(first!.channelId, isNull); + final done = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[1], channelIndex: 3), + channelIndex: 3, + channelId: 'chan-id', + ); + expect(done!.streamId, first.streamId); + expect(done.channelId, 'chan-id'); + }); + test('two-chunk image reports 1 of 2 while incomplete', () async { final h = _build(); final set = buildImageChunks( @@ -962,7 +1010,7 @@ void main() { group('deletion hooks', () { test( - 'deleteImagesForChannel reclaims every image of one conversation', + 'deleteImagesForChannelId reclaims every image of one conversation', () async { final h = _build(); final a = await _completeOne(h, imgId: 130); @@ -972,6 +1020,7 @@ void main() { // A third image on another channel must survive. final other = await h.store.registerOutgoing( channelIndex: 9, + channelId: 'fedcba9876543210', senderPrefix: kSelf, imgId: 5, previewPng: Uint8List.fromList(List.filled(32, 2)), @@ -979,7 +1028,7 @@ void main() { chunkCount: 1, ); - final removed = await h.store.deleteImagesForChannel(3); + final removed = await h.store.deleteImagesForChannelId(_channel3Id); expect(removed, containsAll([a.streamId, b.streamId])); expect(h.store.entryFor(a.streamId), isNull); expect(h.store.entryFor(b.streamId), isNull); @@ -1480,7 +1529,10 @@ Future _completeOne( final entry = await h.store.handleOutcome( h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()), channelIndex: 3, + channelId: _channel3Id, at: h.clock(), ); return entry!; } + +const _channel3Id = '0123456789abcdef'; diff --git a/test/storage/channel_storage_by_id_test.dart b/test/storage/channel_storage_by_id_test.dart new file mode 100644 index 00000000..ae04855f --- /dev/null +++ b/test/storage/channel_storage_by_id_test.dart @@ -0,0 +1,351 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_order_store.dart'; +import 'package:meshcore_open/storage/channel_region_store.dart'; +import 'package:meshcore_open/storage/channel_settings_store.dart'; +import 'package:meshcore_open/storage/channel_storage_migration.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; +import 'package:meshcore_open/storage/legacy_key_migration.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _deviceA = 'aaaaaaaaaa0123456789'; +const _deviceB = 'bbbbbbbbbb0123456789'; +const _scopeA = 'aaaaaaaaaa'; + +final _pskOne = Uint8List.fromList(List.generate(16, (i) => i + 1)); +final _pskTwo = Uint8List.fromList(List.generate(16, (i) => 100 + i)); +final _idOne = Channel.storageIdForPsk(_pskOne)!; +final _idTwo = Channel.storageIdForPsk(_pskTwo)!; + +Future _init([Map values = const {}]) async { + SharedPreferences.setMockInitialValues(values); + PrefsManager.reset(); + await PrefsManager.initialize(); + ChannelMessageStore().forgetArchive(); +} + +ChannelMessage _ch(String text, int i) => ChannelMessage( + senderKey: null, + senderName: 'Bob', + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i), + isOutgoing: false, + status: ChannelMessageStatus.sent, + channelIndex: 0, + messageId: '$text-$i', +); + +String _storedMessages(List texts) => jsonEncode([ + for (var i = 0; i < texts.length; i++) + { + 'senderName': 'Bob', + 'text': texts[i], + 'timestamp': 1000 * (i + 1), + 'isOutgoing': false, + 'status': ChannelMessageStatus.sent.index, + 'messageId': '${texts[i]}-$i', + 'plainText': true, + }, +]); + +String _cachedChannels(Map slots) => jsonEncode([ + for (final entry in slots.entries) + { + 'index': entry.key, + 'name': 'ch${entry.key}', + 'psk': base64Encode(entry.value), + 'unreadCount': 0, + }, +]); + +void main() { + tearDown(scopesWithoutLegacyMigration.clear); + + group('channel ID', () { + test('is stable, 16 hex chars, and absent for an empty slot', () { + expect(_idOne, hasLength(16)); + expect(_idOne, matches(RegExp(r'^[0-9a-f]{16}$'))); + expect(Channel.storageIdForPsk(Uint8List.fromList(_pskOne)), _idOne); + expect(_idOne, isNot(_idTwo)); + expect(Channel.storageIdForPsk(Uint8List(16)), isNull); + expect(Channel.empty(3).storageId, isNull); + expect(Channel(index: 5, name: 'x', psk: _pskOne).storageId, _idOne); + }); + }); + + group('ID-keyed stores', () { + test('messages save, load and clear by channel ID', () async { + await _init(); + final store = ChannelMessageStore()..setPublicKeyHex = _deviceA; + await store.saveChannelMessages(_idOne, [_ch('one', 1)]); + await store.saveChannelMessages(_idTwo, [_ch('two', 1)]); + + expect((await store.loadChannelMessages(_idOne)).single.text, 'one'); + expect((await store.loadChannelMessages(_idTwo)).single.text, 'two'); + expect( + PrefsManager.instance.containsKey( + 'channel_messages_${_scopeA}_$_idOne', + ), + isTrue, + ); + + await store.clearChannelMessages(_idOne); + expect(await store.loadChannelMessages(_idOne), isEmpty); + expect(await store.loadChannelMessages(_idTwo), hasLength(1)); + }); + + test('the same channel ID is isolated per radio scope', () async { + await _init(); + final a = ChannelMessageStore()..setPublicKeyHex = _deviceA; + final b = ChannelMessageStore()..setPublicKeyHex = _deviceB; + await a.saveChannelMessages(_idOne, [_ch('a', 1)]); + + expect(await b.loadChannelMessages(_idOne), isEmpty); + final settingsB = ChannelSettingsStore()..setPublicKeyHex = _deviceB; + final settingsA = ChannelSettingsStore()..setPublicKeyHex = _deviceA; + await settingsA.saveSmazEnabled(_idOne, true); + expect(await settingsA.loadSmazEnabled(_idOne), isTrue); + expect(await settingsB.loadSmazEnabled(_idOne), isFalse); + }); + + test('the archive follows the channel ID', () async { + await _init(); + final store = ChannelMessageStore()..setPublicKeyHex = _deviceA; + store.setArchived(_idOne, [_ch('old', 1), _ch('older', 2)]); + expect(store.archivedCount(_idOne), 2); + expect(store.archivedCount(_idTwo), isNull); + + await store.saveChannelMessages(_idOne, [_ch('new', 3)]); + expect((await store.loadChannelMessages(_idOne)).map((m) => m.text), [ + 'old', + 'older', + 'new', + ]); + store.forgetArchive(_idOne); + expect(store.archivedCount(_idOne), isNull); + }); + + test('settings, region and order are keyed by channel ID', () async { + await _init(); + final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA; + await settings.saveCyr2LatEnabled(_idOne, true); + await settings.saveUrlImagesEnabled(_idOne, true); + await settings.saveCyr2LatProfileId(_idOne, 'sr'); + expect(await settings.loadCyr2LatEnabled(_idOne), isTrue); + expect(await settings.loadUrlImagesEnabled(_idOne), isTrue); + expect(await settings.loadCyr2LatProfileId(_idOne), 'sr'); + expect(await settings.loadCyr2LatEnabled(_idTwo), isFalse); + await settings.clearChannel(_idOne); + expect(await settings.loadCyr2LatEnabled(_idOne), isFalse); + expect(await settings.loadCyr2LatProfileId(_idOne), isNull); + + final region = ChannelRegionStore()..setPublicKeyHex = _deviceA; + await region.saveRegion(_idOne, 'EU'); + expect(await region.loadRegion(_idOne), 'EU'); + expect(await region.loadRegion(_idTwo), ''); + await ChannelRegionStore.clearRegionEverywhere('EU'); + expect(await region.loadRegion(_idOne), ''); + + final order = ChannelOrderStore()..setPublicKeyHex = _deviceA; + await order.saveChannelOrder([_idTwo, _idOne]); + expect(await order.loadChannelOrder(), [_idTwo, _idOne]); + }); + }); + + group('migration', () { + Map legacyValues() => { + 'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}), + 'channel_messages_${_scopeA}0': _storedMessages(['hello']), + 'channel_messages_2': _storedMessages(['unscoped']), + 'channel_messages_${_scopeA}5': _storedMessages(['orphan']), + 'channel_smaz_${_scopeA}0': true, + 'channel_cyr2lat_${_scopeA}2': true, + 'channel_url_images_${_scopeA}2': true, + 'channel_cyr2lat_${_scopeA}profile_2': 'sr', + 'channel_region_${_scopeA}0': 'EU', + 'channel_order_$_scopeA': jsonEncode([2, 5, 0]), + }; + + test('moves messages, settings, region and order to channel IDs', () async { + await _init(legacyValues()); + final mapping = await ChannelStorageMigration.migrate(_scopeA); + expect(mapping, {0: _idOne, 2: _idTwo}); + + final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA; + expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello'); + // The unscoped legacy key migrates too. + expect( + (await messages.loadChannelMessages(_idTwo)).single.text, + 'unscoped', + ); + + final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA; + expect(await settings.loadSmazEnabled(_idOne), isTrue); + expect(await settings.loadSmazEnabled(_idTwo), isFalse); + expect(await settings.loadCyr2LatEnabled(_idTwo), isTrue); + expect(await settings.loadUrlImagesEnabled(_idTwo), isTrue); + expect(await settings.loadCyr2LatProfileId(_idTwo), 'sr'); + + final region = ChannelRegionStore()..setPublicKeyHex = _deviceA; + expect(await region.loadRegion(_idOne), 'EU'); + + final order = ChannelOrderStore()..setPublicKeyHex = _deviceA; + expect(await order.loadChannelOrder(), [_idTwo, _idOne]); + + final prefs = PrefsManager.instance; + expect(prefs.containsKey('channel_messages_${_scopeA}0'), isFalse); + expect(prefs.containsKey('channel_messages_2'), isFalse); + expect(prefs.containsKey('channel_smaz_${_scopeA}0'), isFalse); + expect(prefs.containsKey('channel_region_${_scopeA}0'), isFalse); + // A slot with no cached PSK is left alone. + expect(prefs.containsKey('channel_messages_${_scopeA}5'), isTrue); + // The slot map is seeded for the first post-migration diff. + expect( + await (ChannelStore()..setPublicKeyHex = _scopeA).loadSlotChannelIds(), + {0: _idOne, 2: _idTwo}, + ); + }); + + test('runs once per radio', () async { + await _init(legacyValues()); + await ChannelStorageMigration.migrate(_scopeA); + await PrefsManager.instance.setString( + 'channel_messages_${_scopeA}0', + _storedMessages(['late']), + ); + expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty); + final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA; + expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello'); + expect( + PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'), + isTrue, + ); + }); + + test('a rerun after an interrupted migration loses and duplicates ' + 'nothing', () async { + // Killed after the new keys were written but before the old ones + // were removed and the done flag set. + await _init({ + 'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}), + 'channel_messages_${_scopeA}0': _storedMessages(['hello']), + 'channel_messages_${_scopeA}_$_idOne': _storedMessages(['hello']), + 'channel_order_$_scopeA': jsonEncode([_idTwo, _idOne]), + }); + await ChannelStorageMigration.migrate(_scopeA); + + final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA; + expect((await messages.loadChannelMessages(_idOne)).map((m) => m.text), [ + 'hello', + ]); + final order = ChannelOrderStore()..setPublicKeyHex = _deviceA; + expect(await order.loadChannelOrder(), [_idTwo, _idOne]); + expect( + PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'), + isFalse, + ); + }); + + test('skips a scope that must not adopt legacy data', () async { + await _init(legacyValues()); + scopesWithoutLegacyMigration.add(_scopeA); + expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty); + final prefs = PrefsManager.instance; + expect(prefs.containsKey('channel_messages_${_scopeA}0'), isTrue); + expect(prefs.containsKey('channel_storage_v2_$_scopeA'), isFalse); + expect(prefs.containsKey('channel_messages_2'), isTrue); + }); + + test('two slots with the same PSK merge into one history', () async { + await _init({ + 'channels$_scopeA': _cachedChannels({1: _pskOne, 4: _pskOne}), + 'channel_messages_${_scopeA}1': _storedMessages(['first']), + 'channel_messages_${_scopeA}4': _storedMessages(['second', 'third']), + }); + expect(await ChannelStorageMigration.migrate(_scopeA), { + 1: _idOne, + 4: _idOne, + }); + final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA; + expect( + (await messages.loadChannelMessages(_idOne)).map((m) => m.text), + unorderedEquals(['first', 'second', 'third']), + ); + }); + }); + + group('received images', () { + final png = Uint8List.fromList(List.filled(32, 7)); + + Future outgoing( + ReceivedImageStore store, { + required int slot, + String? channelId, + int imgId = 1, + }) => store.registerOutgoing( + channelIndex: slot, + channelId: channelId, + senderPrefix: 0x1234, + imgId: imgId, + previewPng: png, + rate: AeicRatePoint.ft32, + chunkCount: 1, + ); + + test('an entry round-trips its channel ID', () async { + final store = ReceivedImageStore(decoder: null); + final entry = await outgoing(store, slot: 2, channelId: _idOne); + final json = entry.toJson(); + expect(json['channelId'], _idOne); + expect(ReceivedImageEntry.fromJson(json).channelId, _idOne); + expect(ReceivedImageEntry.fromJson({'streamId': 'x'}).channelId, isNull); + }); + + test('legacy entries get the ID their slot held', () async { + final blobs = InMemoryReceivedImageBlobStore(); + final first = ReceivedImageStore(blobs: blobs, decoder: null); + final onSlot2 = await outgoing(first, slot: 2, imgId: 1); + final onSlot6 = await outgoing(first, slot: 6, imgId: 2); + final stamped = await outgoing(first, slot: 2, imgId: 3, channelId: 'x'); + + final store = ReceivedImageStore(blobs: blobs, decoder: null); + await store.load(); + await store.stampLegacyChannelIds({2: _idOne, 3: _idTwo}); + + expect(store.entryFor(onSlot2.streamId)!.channelId, _idOne); + expect(store.entryFor(onSlot6.streamId)!.channelId, isNull); + expect(store.entryFor(stamped.streamId)!.channelId, 'x'); + // Persisted, so the next launch keeps the stamp. + final reloaded = ReceivedImageStore(blobs: blobs, decoder: null); + await reloaded.load(); + expect(reloaded.entryFor(onSlot2.streamId)!.channelId, _idOne); + }); + + test('delete by channel ID leaves a reused slot alone', () async { + final store = ReceivedImageStore(decoder: null); + final old = await outgoing(store, slot: 1, channelId: _idOne, imgId: 1); + final reused = await outgoing( + store, + slot: 1, + channelId: _idTwo, + imgId: 2, + ); + + expect(store.entriesForChannel(_idTwo).map((e) => e.streamId), [ + reused.streamId, + ]); + final removed = await store.deleteImagesForChannelId(_idOne); + expect(removed, [old.streamId]); + expect(store.entryFor(old.streamId), isNull); + expect(store.entryFor(reused.streamId), isNotNull); + }); + }); +} diff --git a/test/storage/message_store_archive_test.dart b/test/storage/message_store_archive_test.dart index e87ccc28..51908258 100644 --- a/test/storage/message_store_archive_test.dart +++ b/test/storage/message_store_archive_test.dart @@ -43,6 +43,8 @@ ChannelMessage _ch(int i) => ChannelMessage( MessageStore _messageStore() => MessageStore()..setPublicKeyHex = _device; +const _channelId = '0123456789abcdef'; + void main() { group('MessageStore window persistence', () { test('saving the window keeps archived history ahead of it', () async { @@ -179,27 +181,30 @@ void main() { await _init(); final store = ChannelMessageStore()..setPublicKeyHex = _device; final all = [for (var i = 0; i < 8; i++) _ch(i)]; - await store.saveChannelMessages(0, all); + await store.saveChannelMessages(_channelId, all); - final loaded = await store.loadChannelMessages(0); - store.setArchived(0, loaded.sublist(0, 5)); - await store.saveChannelMessages(0, [...loaded.sublist(5), _ch(8)]); + final loaded = await store.loadChannelMessages(_channelId); + store.setArchived(_channelId, loaded.sublist(0, 5)); + await store.saveChannelMessages(_channelId, [ + ...loaded.sublist(5), + _ch(8), + ]); - final reloaded = await store.loadChannelMessages(0); + final reloaded = await store.loadChannelMessages(_channelId); expect(reloaded.map((m) => m.text), [for (var i = 0; i <= 8; i++) 'c$i']); }); test('clearing through another instance resets the archive', () async { await _init(); final store = ChannelMessageStore()..setPublicKeyHex = _device; - store.setArchived(0, [_ch(0), _ch(1)]); - await store.saveChannelMessages(0, [_ch(2)]); + store.setArchived(_channelId, [_ch(0), _ch(1)]); + await store.saveChannelMessages(_channelId, [_ch(2)]); await (ChannelMessageStore()..setPublicKeyHex = _device) - .clearChannelMessages(0); - await store.saveChannelMessages(0, [_ch(3)]); + .clearChannelMessages(_channelId); + await store.saveChannelMessages(_channelId, [_ch(3)]); - final reloaded = await store.loadChannelMessages(0); + final reloaded = await store.loadChannelMessages(_channelId); expect(reloaded.map((m) => m.text), ['c3']); }); }); diff --git a/test/storage/store_tolerant_parsing_test.dart b/test/storage/store_tolerant_parsing_test.dart index d74d00d6..4defbcd3 100644 --- a/test/storage/store_tolerant_parsing_test.dart +++ b/test/storage/store_tolerant_parsing_test.dart @@ -17,6 +17,8 @@ Future _init(Map values) async { await PrefsManager.initialize(); } +const _channelId = '0123456789abcdef'; + void main() { test( 'message store skips a malformed record instead of dropping all', @@ -42,13 +44,13 @@ void main() { test('channel message store skips a malformed record', () async { await _init({ - 'channel_messages_${_device.substring(0, 10)}0': jsonEncode([ + 'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([ {'text': 'hi', 'timestamp': 1000, 'status': 1}, 'garbage', ]), }); final store = ChannelMessageStore()..setPublicKeyHex = _device; - final messages = await store.loadChannelMessages(0); + final messages = await store.loadChannelMessages(_channelId); expect(messages.map((m) => m.text), ['hi']); }); From 6a8df764bb7ad4ab2679d740a6f0cd4e8ab2e11a Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 18:04:53 -0700 Subject: [PATCH 4/8] Stamp legacy images inside the migration; hold early channel frames - Image entries are stamped with their channel ID before the migration is marked done, so an interrupted run repeats it instead of leaving them unstamped (and invisible) forever. - Channel message/data frames that arrive before this session's slot map is confirmed are held and replayed once it is. Current firmware only sends them in reply to SYNC_NEXT_MESSAGE, which already waits; this guards against a stale saved map filing them under the wrong channel. --- lib/connector/meshcore_connector.dart | 35 +++++++++++++++++--- lib/storage/channel_storage_migration.dart | 10 +++++- test/connector/channel_slot_map_test.dart | 26 +++++++++++++++ test/storage/channel_storage_by_id_test.dart | 21 ++++++++++++ 4 files changed, 87 insertions(+), 5 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index bf4d7005..e62e60e9 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -379,6 +379,12 @@ class MeshCoreConnector extends ChangeNotifier { bool _isProcessingDeferredQueuedContactMessages = false; bool _queuedMessageSyncInFlight = false; final List _deferredQueuedContactMessageFrames = []; + + /// Channel frames that arrived before this session's slot map was + /// confirmed. The firmware only sends them in reply to SYNC_NEXT_MESSAGE, + /// which waits for the map, so this is a guard: their slot index cannot be + /// resolved yet, and they are replayed once it can. + final List _channelFramesAwaitingMap = []; 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 @@ -3431,6 +3437,7 @@ class MeshCoreConnector extends ChangeNotifier { _isProcessingDeferredQueuedContactMessages = false; _queuedMessageSyncInFlight = false; _deferredQueuedContactMessageFrames.clear(); + _channelFramesAwaitingMap.clear(); _pendingQueueSync = false; _resetSyncFlowState(); _queueSyncTimeout?.cancel(); @@ -5682,6 +5689,19 @@ class MeshCoreConnector extends ChangeNotifier { _finishChannelSync(); } + void _replayChannelFramesAwaitingMap() { + if (_channelFramesAwaitingMap.isEmpty) return; + final frames = List.of(_channelFramesAwaitingMap); + _channelFramesAwaitingMap.clear(); + for (final frame in frames) { + if (frame[0] != respCodeChannelDataRecv) { + _handleIncomingChannelMessage(frame); + } else if (_appSettingsService?.settings.imageMessagesEnabled ?? false) { + _handleIncomingChannelData(frame); + } + } + } + /// A channel whose key changed in place keeps its position in the custom /// order: [after] takes [before]'s place when no slot holds [before] any /// more. Returns true when the order changed. @@ -5714,6 +5734,7 @@ class MeshCoreConnector extends ChangeNotifier { } void _finishChannelSync() { + if (_channelMapConfirmed) _replayChannelFramesAwaitingMap(); final completer = _channelSyncCompleter; _channelSyncCompleter = null; if (completer != null && !completer.isCompleted) completer.complete(); @@ -5745,12 +5766,11 @@ class MeshCoreConnector extends ChangeNotifier { // First: the channel sync is already running and carries unread counts // over from these. The migration never touches the channel cache. await loadCachedChannels(); - final migrated = await ChannelStorageMigration.migrate( + await ChannelStorageMigration.migrate( _channelStore.publicKeyHex, + beforeDone: (slotIds) async => + _receivedImageStore?.stampLegacyChannelIds(slotIds), ); - if (migrated.isNotEmpty) { - await _receivedImageStore?.stampLegacyChannelIds(migrated); - } await _loadChannelOrder(); final saved = await _channelStore.loadSlotChannelIds(); _slotChannelIds @@ -5967,6 +5987,13 @@ class MeshCoreConnector extends ChangeNotifier { unawaited(_handleIncomingMessage(frame)); } break; + case respCodeChannelMsgRecv || + respCodeChannelMsgRecvV3 || + respCodeChannelDataRecv + when !_channelMapConfirmed: + if (_isSyncingQueuedMessages) _handleQueuedMessageReceived(); + _channelFramesAwaitingMap.add(frame); + break; case respCodeChannelMsgRecv: case respCodeChannelMsgRecvV3: _handleIncomingChannelMessage(frame); diff --git a/lib/storage/channel_storage_migration.dart b/lib/storage/channel_storage_migration.dart index 80fb6187..ec4afbbb 100644 --- a/lib/storage/channel_storage_migration.dart +++ b/lib/storage/channel_storage_migration.dart @@ -25,7 +25,14 @@ class ChannelStorageMigration { /// Migrates [scope] (first 10 hex chars of the radio's public key) and /// returns the slot -> channel ID mapping it used. Returns an empty map when /// the scope was already migrated or must not adopt legacy data. - static Future> migrate(String scope) async { + /// + /// [beforeDone] runs with that mapping before the migration is marked done, + /// so data kept elsewhere (images) is moved on the same one-shot terms: an + /// interrupted run repeats it on the next launch. + static Future> migrate( + String scope, { + Future Function(Map slotIds)? beforeDone, + }) async { if (scope.isEmpty || !canMigrateLegacyKeys(scope)) return {}; final prefs = PrefsManager.instance; final doneKey = '$_doneKeyPrefix$scope'; @@ -61,6 +68,7 @@ class ChannelStorageMigration { ); } await _migrateOrder(scope, slotIds); + if (slotIds.isNotEmpty) await beforeDone?.call(slotIds); await prefs.setBool(doneKey, true); await channelStore.saveSlotChannelIds(slotIds); diff --git a/test/connector/channel_slot_map_test.dart b/test/connector/channel_slot_map_test.dart index acd0d19e..65097f67 100644 --- a/test/connector/channel_slot_map_test.dart +++ b/test/connector/channel_slot_map_test.dart @@ -243,6 +243,32 @@ void main() { expect(_storedTexts(hikingId), isEmpty); }); + test('a channel frame that arrives before the slot map is held, then filed ' + 'by the confirmed map', () async { + final radio = _TestRadio( + afterHandle: (radio, frame) { + if (frame[0] == cmdAppStart) { + radio.emitForTest( + ReviewFrames.channelMessage( + channelIndex: 1, + sender: 'Sam', + message: 'before the map', + timestampSecs: DateTime.now().millisecondsSinceEpoch ~/ 1000, + ), + ); + } + }, + ); + await _connect( + radio, + // A stale map from last session would file it under the ghost channel. + seed: () => _seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))}), + ); + await _waitFor(() => _texts(1).contains('before the map')); + expect(_storedTexts(hikingId), contains('before the map')); + expect(_storedTexts(ghostId), isNot(contains('before the map'))); + }); + test('MSG_WAITING before the channel sync waits for the slot map', () async { // DEVICE_INFO is held back so MSG_WAITING lands between SELF_INFO and the // start of the channel sync. diff --git a/test/storage/channel_storage_by_id_test.dart b/test/storage/channel_storage_by_id_test.dart index ae04855f..ec7a376c 100644 --- a/test/storage/channel_storage_by_id_test.dart +++ b/test/storage/channel_storage_by_id_test.dart @@ -254,6 +254,27 @@ void main() { ); }); + test('images are stamped before the migration is marked done', () async { + await _init(legacyValues()); + await expectLater( + ChannelStorageMigration.migrate( + _scopeA, + beforeDone: (_) async => throw StateError('killed'), + ), + throwsStateError, + ); + // Not marked done, so the next launch stamps again. + Map? stamped; + await ChannelStorageMigration.migrate( + _scopeA, + beforeDone: (slotIds) async => stamped = slotIds, + ); + expect(stamped, {0: _idOne, 2: _idTwo}); + // Data moved by the first run is still there. + final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA; + expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello'); + }); + test('skips a scope that must not adopt legacy data', () async { await _init(legacyValues()); scopesWithoutLegacyMigration.add(_scopeA); From bc14de586fa035d279b5de4560dfa22213290a4b Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 21:54:16 -0700 Subject: [PATCH 5/8] Add opt-in network map uploads and online map view - Opt-in upload of header-only packet records and repeater/room server adverts to map.meshcoreopen.org about once a minute; payloads, channel and DM hashes and transport codes are stripped on the phone, locations snapped to a ~2 km grid, install ID rotates daily - One-time opt-in dialog on first radio connection; toggle and status in App settings - Local / Online / Both switch on the map screen with online repeater hexagons, links, add-to-contacts and manage - Node purchase banner on the connect screen (affiliate link, disclosed) - Privacy policy and network map documentation - Translations for all locales --- docs/PRIVACY_POLICY.md | 44 +- documentation/README.md | 2 + documentation/network-map.md | 50 ++ lib/connector/meshcore_connector.dart | 42 +- lib/connector/raw_packet.dart | 29 ++ lib/l10n/app_bg.arb | 52 +- lib/l10n/app_de.arb | 52 +- lib/l10n/app_en.arb | 43 +- lib/l10n/app_es.arb | 52 +- lib/l10n/app_fr.arb | 52 +- lib/l10n/app_hu.arb | 52 +- lib/l10n/app_it.arb | 52 +- lib/l10n/app_ja.arb | 52 +- lib/l10n/app_ko.arb | 52 +- lib/l10n/app_localizations.dart | 240 +++++++++ lib/l10n/app_localizations_bg.dart | 135 +++++ lib/l10n/app_localizations_de.dart | 133 +++++ lib/l10n/app_localizations_en.dart | 129 +++++ lib/l10n/app_localizations_es.dart | 134 +++++ lib/l10n/app_localizations_fr.dart | 135 +++++ lib/l10n/app_localizations_hu.dart | 133 +++++ lib/l10n/app_localizations_it.dart | 134 +++++ lib/l10n/app_localizations_ja.dart | 127 +++++ lib/l10n/app_localizations_ko.dart | 127 +++++ lib/l10n/app_localizations_nl.dart | 130 +++++ lib/l10n/app_localizations_pl.dart | 132 +++++ lib/l10n/app_localizations_pt.dart | 132 +++++ lib/l10n/app_localizations_ru.dart | 133 +++++ lib/l10n/app_localizations_sk.dart | 132 +++++ lib/l10n/app_localizations_sl.dart | 132 +++++ lib/l10n/app_localizations_sv.dart | 131 +++++ lib/l10n/app_localizations_uk.dart | 133 +++++ lib/l10n/app_localizations_zh.dart | 124 +++++ lib/l10n/app_nl.arb | 52 +- lib/l10n/app_pl.arb | 52 +- lib/l10n/app_pt.arb | 52 +- lib/l10n/app_ru.arb | 52 +- lib/l10n/app_sk.arb | 52 +- lib/l10n/app_sl.arb | 52 +- lib/l10n/app_sv.arb | 52 +- lib/l10n/app_uk.arb | 52 +- lib/l10n/app_zh.arb | 52 +- lib/main.dart | 10 + lib/models/app_settings.dart | 19 + lib/screens/app_settings_screen.dart | 8 + lib/screens/channels_screen.dart | 2 + lib/screens/map_screen.dart | 186 ++++++- lib/screens/scanner_screen.dart | 2 + lib/services/app_settings_service.dart | 8 + .../network_map/network_map_api_client.dart | 236 +++++++++ .../network_map/network_map_gzip.dart | 2 + .../network_map/network_map_gzip_io.dart | 3 + .../network_map/network_map_gzip_stub.dart | 2 + .../network_map/network_map_records.dart | 414 +++++++++++++++ .../network_map_upload_service.dart | 389 ++++++++++++++ lib/services/ui_view_state_service.dart | 22 + lib/utils/location_grid.dart | 22 + lib/widgets/get_node_banner.dart | 98 ++++ lib/widgets/network_map_online_layer.dart | 493 ++++++++++++++++++ lib/widgets/network_map_opt_in_dialog.dart | 95 ++++ lib/widgets/network_map_settings_section.dart | 75 +++ .../network_map_api_client_test.dart | 191 +++++++ .../network_map/network_map_records_test.dart | 378 ++++++++++++++ .../network_map_upload_service_test.dart | 48 ++ .../network_map/network_map_upload_test.dart | 216 ++++++++ test/utils/location_grid_test.dart | 29 ++ test/widgets/get_node_banner_test.dart | 48 ++ .../network_map_opt_in_dialog_test.dart | 99 ++++ 68 files changed, 6719 insertions(+), 76 deletions(-) create mode 100644 documentation/network-map.md create mode 100644 lib/connector/raw_packet.dart create mode 100644 lib/services/network_map/network_map_api_client.dart create mode 100644 lib/services/network_map/network_map_gzip.dart create mode 100644 lib/services/network_map/network_map_gzip_io.dart create mode 100644 lib/services/network_map/network_map_gzip_stub.dart create mode 100644 lib/services/network_map/network_map_records.dart create mode 100644 lib/services/network_map/network_map_upload_service.dart create mode 100644 lib/utils/location_grid.dart create mode 100644 lib/widgets/get_node_banner.dart create mode 100644 lib/widgets/network_map_online_layer.dart create mode 100644 lib/widgets/network_map_opt_in_dialog.dart create mode 100644 lib/widgets/network_map_settings_section.dart create mode 100644 test/services/network_map/network_map_api_client_test.dart create mode 100644 test/services/network_map/network_map_records_test.dart create mode 100644 test/services/network_map/network_map_upload_service_test.dart create mode 100644 test/services/network_map/network_map_upload_test.dart create mode 100644 test/utils/location_grid_test.dart create mode 100644 test/widgets/get_node_banner_test.dart create mode 100644 test/widgets/network_map_opt_in_dialog_test.dart diff --git a/docs/PRIVACY_POLICY.md b/docs/PRIVACY_POLICY.md index 6737012e..bd7bf6de 100644 --- a/docs/PRIVACY_POLICY.md +++ b/docs/PRIVACY_POLICY.md @@ -1,6 +1,6 @@ # Privacy Policy for MeshCore Open -**Last Updated:** September 27, 2026 +**Last Updated:** October 11, 2026 ## Introduction @@ -11,7 +11,7 @@ MeshCore Open ("the App") is an open-source Flutter application for communicatin ### Data We Do NOT Collect MeshCore Open does **not**: -- Collect personal information for the developer +- Collect personal information for the developer. The optional network map upload described below sends anonymized radio data only if you turn it on - Track your usage or behavior - Use analytics services - Require account creation @@ -54,7 +54,7 @@ Required by Android for BLE scanning on Android 11 and below. MeshCore Open does ### Internet Permission - **INTERNET** -Used for features that access third-party internet services, including map tiles, Line-of-Sight elevation lookups, optional model downloads, GIF search/display, and optional URL image previews. +Used for features that access third-party internet services, including map tiles, the MeshCore Open network map, Line-of-Sight elevation lookups, optional model downloads, GIF search/display, and optional URL image previews. ### Notification Permission - **POST_NOTIFICATIONS** (Android 13+) @@ -70,6 +70,39 @@ Used to maintain BLE connection with your MeshCore device while the app is in th Camera access is used for contact and community QR scanning. Photo-library access is used when you select a photo for mesh image messaging. Selected photos are encoded locally for transmission over the mesh; the App does not upload them to a model service for inference. +## MeshCore Open Network Map + +The MeshCore Open project runs a public network map at [map.meshcoreopen.org](https://map.meshcoreopen.org). It shows MeshCore repeaters, room servers, the links between them, traffic and measured coverage. + +### Viewing the map +When you use the Online or Both view on the App's map, the App requests map data for the area on screen from `map.meshcoreopen.org`. These requests include the visible map area and expose your device's IP address to the server as part of normal internet communication. Viewing the map never uploads anything. + +### Sharing data (opt-in) +Uploading is **off by default**. The first time a radio connects, the App asks once whether you want to share; you can also turn it on or off at any time in **Settings → App settings → Network map**. Turning it off stops uploads immediately and discards anything waiting to be sent. + +While sharing is on and a radio is connected, the App sends the following about once a minute: + +- **Packet headers** for packets your radio hears: payload type, route type, the repeater path hashes, hop count, signal strength (SNR/RSSI), size rounded to 16 bytes, a one-way packet fingerprint used to count duplicates, and the time rounded to the minute. +- **Repeater and room server adverts** with a valid signature: public key, name, node type and advertised location. +- **Your radio's position and settings**, if the radio has a position: rounded to a grid of about 2 km, plus its frequency, bandwidth, spreading factor and coding rate. +- **A random install ID** that changes every 24 hours. + +All locations are rounded to the ~2 km grid on your phone before upload, and the map shows them only as hexagons. + +The App never uploads message text or payloads, channel or community names, keys or hashes, direct-message sender or recipient hashes, region transport codes, exact coordinates, your contact list, or information about chat or sensor nodes beyond the header-only packet records above. + +### How the server handles uploads +- **IP addresses are not stored or logged.** The server uses your IP address in memory to rate-limit uploads and to check whether a request comes from a hosting provider. To count how many independent people reported something, it keeps a keyed hash of your network prefix (the /24 IPv4 or /48 IPv6 block) until the end of the day. The key changes daily and is discarded, after which these hashes cannot be linked to an address; they are then deleted. +- **Retention:** individual packet and advert records are deleted after 7 days. Hourly and daily totals (for example, the number of packets a link carried in a day) are kept longer to draw 30-day views. +- **Public data:** repeater names, rough locations, links, traffic totals and coverage are shown publicly on the map and in the App. + +Uploaded records are not linked to an account, name or device identity, so the project cannot find or delete a particular person's records; they expire on the schedule above. + +### Hiding a repeater +Repeater and room server owners can remove their node from the map by putting the 🚫 emoji anywhere in its name and sending a flood advert. Its name and location are then removed from the map, and the packet viewer shows it only as an anonymous repeater with its public key. Location traces tied to it, such as which areas heard it, are deleted too. To show it again, remove the emoji; it reappears with its first advert after 7 days without one. + +See the map's [privacy page](https://map.meshcoreopen.org/privacy) for more detail. + ## Third-Party Services ### Map Tiles @@ -99,6 +132,9 @@ The App includes a GIF picker feature powered by Giphy. When you use the GIF sea GIF search is optional and activated through the picker. Displaying a GIF reference received in a chat also requests image content from Giphy’s CDN, even if you did not perform a search. See [Giphy's Privacy Policy](https://support.giphy.com/hc/en-us/articles/360032872931-GIPHY-Privacy-Policy) for more information about how they handle data. +### Device Purchase Link (Seeed Studio) +The connection screen shows a link to buy a MeshCore device from Seeed Studio. The link contains a MeshCore Open affiliate code, so the project may earn a commission on purchases made through it, at no extra cost to you. The App sends nothing to Seeed Studio unless you tap the link; tapping it opens Seeed Studio's website in your browser, where Seeed Studio's own privacy policy applies. + ### URL Image Previews and Custom Model URLs When URL images are enabled for a contact or channel, supported links in messages can cause requests to the referenced image host, sharing-page provider, or IPFS gateway. These services receive the requested URL and normal connection information, including your IP address. Requests may occur when chat content is displayed rather than only after tapping the link. Disable URL images in the contact/channel settings to disable this preview feature. @@ -131,4 +167,4 @@ If you have questions about this Privacy Policy or the App's privacy practices, --- -**Summary**: MeshCore Open does not use the phone's GPS for location, does not include analytics, and does not collect personal information for the developer. Some optional features communicate with third-party services, including map tile providers, Open-Meteo for LOS elevation lookups, Hugging Face for model downloads, Giphy for GIF search/display, and image hosts/gateways for enabled URL previews. +**Summary**: MeshCore Open does not use the phone's GPS for location, does not include analytics, and does not collect personal information for the developer. If you opt in, the App uploads anonymized packet headers, repeater adverts and ~2 km rounded locations to the MeshCore Open network map; the server does not store IP addresses and deletes raw records after 7 days. Some optional features communicate with third-party services, including map tile providers, Open-Meteo for LOS elevation lookups, Hugging Face for model downloads, Giphy for GIF search/display, and image hosts/gateways for enabled URL previews. diff --git a/documentation/README.md b/documentation/README.md index 5198c08f..9053cf05 100644 --- a/documentation/README.md +++ b/documentation/README.md @@ -28,6 +28,7 @@ MeshCore Open is an open-source Flutter client for MeshCore LoRa mesh networking 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 +18. [Network Map](network-map.md) - Online repeater map, adding and managing repeaters from it, opt-in uploads, and hiding a repeater ## App Overview @@ -55,6 +56,7 @@ MeshCore Open connects to MeshCore LoRa mesh radios over BLE, USB, or TCP. Once | Model downloads | Internet required | | GIF search/display and URL image previews | Internet required to retrieve content | | Map display | Cached tiles work offline; uncached tiles need internet | +| Online network map and opt-in uploads | Internet required | | Terrain LOS analysis | Elevation lookup needs internet unless the required data is already cached | ## Keeping documentation current diff --git a/documentation/network-map.md b/documentation/network-map.md new file mode 100644 index 00000000..d98d526e --- /dev/null +++ b/documentation/network-map.md @@ -0,0 +1,50 @@ +# Network Map + +The online network map at [map.meshcoreopen.org](https://map.meshcoreopen.org) shows MeshCore repeaters, room servers, links between them, traffic and measured coverage. It is built from header-only packet records that opted-in MeshCore Open users upload. Viewing the map never requires uploading. + +## Viewing the map in the app + +Open the map and use the **Local / Online / Both** switch at the top. + +| View | Shows | +|---|---| +| Local | Your contacts at the positions their adverts give. This data stays on the device. | +| Online | Repeater and room server hexagons and links from the network map. | +| Both | Online hexagons under your local markers. Repeaters already in your contacts are marked "In your contacts". | + +Hexagons are about 2–3 km across and never show a node's exact position. A dashed outline means the repeater has only been reported by one uploader so far ("single source"). When the visible area is larger than 20° the map asks you to zoom in. + +Tap a hexagon to see the repeater's name, type, status and last-seen time, plus a reachability hint: + +- **Heard by your radio**: your radio knows this node. +- **In your area**: it is within about 50 km of your radio's position. +- **Far away**: management requests won't reach it over the mesh. + +**Add to contacts** saves the repeater with flood routing and no location. Its real location arrives with its next advert. **Manage** adds it if needed and opens the normal repeater or room server login. + +## Contributing data (opt-in) + +Turn on **Settings → App settings → Network map** to upload while a radio is connected. Uploading is off by default. + +The first time a radio connects, the app asks once whether to share. **Share** turns uploading on and **No thanks** leaves it off. Either way the question is not asked again; the setting can be changed at any time. + +What is uploaded, about once a minute: + +- For every packet your radio hears: payload type, route type, path hashes, hop count, SNR, RSSI, size rounded to 16 bytes, a packet hash, and the time rounded to the minute. +- For repeater and room server adverts with a valid signature: public key, name, type and the advertised location snapped to a ~2 km grid. +- Your radio's own position snapped to the same grid (if the radio has one) and its frequency, bandwidth, spreading factor and coding rate. +- A random install ID that changes every 24 hours. + +What is never uploaded: message text or payloads, channel or community names and hashes, direct-message sender/recipient hashes, region transport codes, exact coordinates, and anything about chat or sensor nodes beyond the header-only packet record. + +The server does not store IP addresses and keeps raw records for 7 days. See the map's [privacy page](https://map.meshcoreopen.org/privacy) for details. + +## Hiding a repeater + +Repeater and room server owners can hide their node by putting 🚫 anywhere in its name and sending a flood advert. It disappears from the map and appears in the packet viewer only as "Anonymous repeater". To show it again, remove the emoji; it reappears with its first advert after 7 days without one. The delay stops anyone from undoing an owner's opt-out with a faked advert. The emoji uses 4 of the name's 32 bytes. + +## Limitations + +- Uploading only happens while the app is connected to a radio. On iOS most contributions come from foreground use. +- Packets larger than the companion frame limit (172 bytes) are never forwarded to the app, so they are not counted. +- Coverage shows how well phones hear repeaters; a handheld's own transmissions reach repeaters less reliably. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index bf05ab44..03ccd9bf 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -63,6 +63,7 @@ import '../utils/platform_info.dart'; import 'meshcore_uuids.dart'; import 'meshcore_protocol.dart'; import 'pending_command_replies.dart'; +import 'raw_packet.dart'; class DirectRepeater { static const int maxAgeMinutes = 30; // Max age for direct repeater info @@ -7044,10 +7045,7 @@ class MeshCoreConnector extends ChangeNotifier { return; } - final pktHash = _computePacketHash( - packet.payloadType, - packet.payload, - ); + final pktHash = computePacketHash(packet.payloadType, packet.payload); final message = ChannelMessage( senderKey: null, @@ -7635,7 +7633,7 @@ class MeshCoreConnector extends ChangeNotifier { routeType == _routeTransportDirect; final transportCodes = hasTransport ? reader.readBytes(4) : null; final pathLenRaw = reader.readByte(); - final pathByteLen = _decodePathByteLen(pathLenRaw); + final pathByteLen = decodePathByteLen(pathLenRaw); final pathBytes = reader.readBytes(pathByteLen); final payload = reader.readBytes(reader.remaining); @@ -7707,18 +7705,6 @@ class MeshCoreConnector extends ChangeNotifier { return match; } - /// Firmware-compatible packet hash: SHA256(payloadType + payload) -> first 8 bytes as hex. - String _computePacketHash(int payloadType, Uint8List payload) { - final input = Uint8List(1 + payload.length); - input[0] = payloadType; - input.setRange(1, input.length, payload); - final digest = crypto.sha256.convert(input).bytes; - return digest - .sublist(0, 8) - .map((b) => b.toRadixString(16).padLeft(2, '0')) - .join(); - } - /// Content-based dedup hash for sync queue messages (no raw payload available). /// Prefixed with 'c:' to avoid collisions with packet hashes. String _computeContentHash( @@ -8314,8 +8300,8 @@ class MeshCoreConnector extends ChangeNotifier { } //final payloadVer = (header >> 6) & 0x03; final pathLenRaw = packet.readByte(); - final pathByteLen = _decodePathByteLen(pathLenRaw); - final pathHashWidth = _decodePathHashWidth(pathLenRaw); + final pathByteLen = decodePathByteLen(pathLenRaw); + final pathHashWidth = decodePathHashWidth(pathLenRaw); final pathBytes = packet.readBytes(pathByteLen); final payload = packet.readBytes(packet.remaining); @@ -8357,8 +8343,8 @@ class MeshCoreConnector extends ChangeNotifier { } //final payloadVer = (header >> 6) & 0x03; final pathLenRaw = packet.readByte(); - final pathByteLen = _decodePathByteLen(pathLenRaw); - pathHashWidth = _decodePathHashWidth(pathLenRaw); + final pathByteLen = decodePathByteLen(pathLenRaw); + pathHashWidth = decodePathHashWidth(pathLenRaw); pathBytes = packet.readBytes(pathByteLen); } catch (e) { appLogger.warn('Malformed RX frame: $e', tag: 'Connector'); @@ -8861,20 +8847,6 @@ const int _routeTransportDirect = 0x03; const int _payloadTypeGroupText = 0x05; const int _cipherMacSize = 2; -/// Decodes the firmware's encoded path_len byte into actual byte length. -/// Bits 0-5: hash count (0-63), Bits 6-7: hash size code (0=1byte ... 3=4bytes). -int _decodePathByteLen(int pathLenRaw) { - if (pathLenRaw == 0xFF || pathLenRaw == 0) return 0; - final hashCount = pathLenRaw & 63; - final hashSize = _decodePathHashWidth(pathLenRaw); - return hashCount * hashSize; -} - -int _decodePathHashWidth(int pathLenRaw) { - if (pathLenRaw == 0xFF) return 1; - return ((pathLenRaw >> 6) & 0x03) + 1; -} - bool _isPathLenValidForMode( int pathLen, List pathBytes, diff --git a/lib/connector/raw_packet.dart b/lib/connector/raw_packet.dart new file mode 100644 index 00000000..d4627afb --- /dev/null +++ b/lib/connector/raw_packet.dart @@ -0,0 +1,29 @@ +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; + +/// Decodes the firmware's encoded path_len byte into actual byte length. +/// Bits 0-5: hash count (0-63), Bits 6-7: hash size code (0=1byte ... 3=4bytes). +int decodePathByteLen(int pathLenRaw) { + if (pathLenRaw == 0xFF || pathLenRaw == 0) return 0; + final hashCount = pathLenRaw & 63; + final hashSize = decodePathHashWidth(pathLenRaw); + return hashCount * hashSize; +} + +int decodePathHashWidth(int pathLenRaw) { + if (pathLenRaw == 0xFF) return 1; + return ((pathLenRaw >> 6) & 0x03) + 1; +} + +/// Firmware-compatible packet hash: SHA256(payloadType + payload) -> first 8 bytes as hex. +String computePacketHash(int payloadType, Uint8List payload) { + final input = Uint8List(1 + payload.length); + input[0] = payloadType; + input.setRange(1, input.length, payload); + final digest = crypto.sha256.convert(input).bytes; + return digest + .sublist(0, 8) + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(); +} diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 0bf147d4..2c4dde5b 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3260,5 +3260,55 @@ "usbChooseSerialPort": "Изберете сериен порт", "neighbors_durationSeconds": "{seconds}с", "neighbors_durationMinutes": "{minutes}м {seconds}с", - "neighbors_durationHours": "{hours}ч {minutes}м" + "neighbors_durationHours": "{hours}ч {minutes}м", + "scanner_getNodeTitle": "Нуждаете се от нов възел?", + "scanner_getNodeBody": "Колкото портфейл, работи с MeshCore, двулентов GPS, водоустойчив, батерия за 5 дни.", + "scanner_getNodeAction": "Вземете го тук", + "scanner_getNodeDisclosure": "Партньорска връзка: всяка покупка подкрепя MeshCore Open.", + "networkMap_settingsSection": "Мрежова карта", + "networkMap_uploadTitle": "Споделяне на това, което чува моето радио", + "networkMap_uploadExplanation": "Когато това е включено и радиото е свързано, приложението изпраща към мрежовата карта на MeshCore Open кратко обобщение на пакетите, които радиото ви чува, за да може всеки да вижда кои повторители съществуват и как са свързани. Изпращат се типът, маршрутът, броят хопове, силата на сигнала и размерът на всеки пакет, както и имената на повторителите и приблизителното им местоположение от техните собствени обяви. Никога не се изпращат текст на съобщения, кой с кого говори, имена на канали, вашите контакти или точното ви местоположение: координатите се закръглят до около 2 км, а приложението получава нов случаен ID всеки ден.", + "networkMap_whatWeCollect": "Какво събираме", + "networkMap_promptTitle": "Ще помогнете ли за мрежовата карта?", + "networkMap_promptBody": "MeshCore Open може да споделя това, което радиото ви чува, с публичната мрежова карта на map.meshcoreopen.org, за да може всеки да вижда кои повторители съществуват и как са свързани.\n\nНикога не се изпращат текст на съобщения, кой с кого говори, имена на канали, вашите контакти или точното ви местоположение. Координатите се закръглят до около 2 км.", + "networkMap_promptSettingsHint": "Можете да промените това по всяко време в Настройки → Настройки на приложението → Мрежова карта.", + "networkMap_promptAccept": "Споделям", + "networkMap_promptDecline": "Не, благодаря", + "networkMap_statusOff": "Изключено. Нищо не се изпраща.", + "networkMap_statusWaiting": "Включено. Изчакване на връзка с радио.", + "networkMap_statusNothingSent": "Включено. Още нищо не е изпратено.", + "networkMap_statusLastSent": "Последно изпращане: {time}. Пакети днес: {count}.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Локална", + "networkMap_sourceOnline": "Онлайн", + "networkMap_sourceBoth": "И двете", + "networkMap_zoomInHint": "Увеличете, за да видите онлайн мрежовата карта", + "networkMap_loadFailed": "Онлайн мрежовата карта не можа да се зареди", + "networkMap_inYourContacts": "В контактите ви", + "networkMap_status": "Статус", + "networkMap_statusActive": "Активен през последния час", + "networkMap_statusRecent": "Чут през последното денонощие", + "networkMap_statusStale": "Отдавна не е чут", + "networkMap_confirmed": "Потвърден", + "networkMap_singleSource": "Един източник, още непотвърден", + "networkMap_reports": "Доклади", + "networkMap_locationEstimated": "Приблизително местоположение, изчислено по тези, които са го чули", + "networkMap_locationAdvertised": "Приблизително местоположение, от собствената му обява", + "networkMap_heardByRadio": "Чут от вашето радио", + "networkMap_inYourArea": "Във вашия район", + "networkMap_farAway": "Далече. Управлението няма да стигне до него.", + "networkMap_addToContacts": "Добави към контактите", + "networkMap_manage": "Управление", + "networkMap_addedToContacts": "Добавено към контактите", + "networkMap_addFailed": "Неуспешно добавяне към контактите", + "networkMap_unnamed": "Неназован повторител" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index ebd007b5..1d12ad59 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3395,5 +3395,55 @@ "usbChooseSerialPort": "Serielle Schnittstelle wählen", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} Min. {seconds} s", - "neighbors_durationHours": "{hours} Std. {minutes} Min." + "neighbors_durationHours": "{hours} Std. {minutes} Min.", + "scanner_getNodeTitle": "Brauchst du einen neuen Node?", + "scanner_getNodeBody": "Im Hosentaschenformat, mit MeshCore, Dualband-GPS, wasserdicht und 5 Tage Akkulaufzeit.", + "scanner_getNodeAction": "Hier holen", + "scanner_getNodeDisclosure": "Affiliate-Link: Jeder Kauf unterstützt MeshCore Open.", + "networkMap_settingsSection": "Netzwerkkarte", + "networkMap_uploadTitle": "Teilen, was mein Funkgerät hört", + "networkMap_uploadExplanation": "Wenn dies aktiviert und dein Funkgerät verbunden ist, sendet die App eine kurze Zusammenfassung der Pakete, die dein Funkgerät empfängt, an die MeshCore-Open-Netzwerkkarte, damit alle sehen können, welche Repeater es gibt und wie sie verbunden sind. Gesendet werden Typ, Route, Hops, Signalstärke und Größe jedes Pakets sowie Repeater-Namen und ungefähre Standorte aus deren eigenen Adverts. Nie gesendet werden Nachrichtentexte, wer mit wem spricht, Kanalnamen, deine Kontakte oder dein genauer Standort: Standorte werden auf etwa 2 km gerundet, und deine App erhält jeden Tag eine neue zufällige ID.", + "networkMap_whatWeCollect": "Was wir erfassen", + "networkMap_promptTitle": "Beim Aufbau der Netzwerkkarte helfen?", + "networkMap_promptBody": "MeshCore Open kann teilen, was dein Funkgerät hört, und zwar mit der öffentlichen Netzwerkkarte unter map.meshcoreopen.org, damit alle sehen können, welche Repeater es gibt und wie sie verbunden sind.\n\nEs werden nie Nachrichtentexte, wer mit wem spricht, Kanalnamen, deine Kontakte oder dein genauer Standort gesendet. Standorte werden auf etwa 2 km gerundet.", + "networkMap_promptSettingsHint": "Du kannst dies jederzeit unter Einstellungen → App-Einstellungen → Netzwerkkarte ändern.", + "networkMap_promptAccept": "Teilen", + "networkMap_promptDecline": "Nein danke", + "networkMap_statusOff": "Aus. Es wird nichts gesendet.", + "networkMap_statusWaiting": "An. Warte auf eine Funkgerät-Verbindung.", + "networkMap_statusNothingSent": "An. Noch nichts gesendet.", + "networkMap_statusLastSent": "Zuletzt gesendet {time}. Heute {count} Pakete.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Lokal", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Beides", + "networkMap_zoomInHint": "Zoome hinein, um die Online-Netzwerkkarte zu sehen", + "networkMap_loadFailed": "Online-Netzwerkkarte konnte nicht geladen werden", + "networkMap_inYourContacts": "In deinen Kontakten", + "networkMap_status": "Status", + "networkMap_statusActive": "Aktiv in der letzten Stunde", + "networkMap_statusRecent": "Am letzten Tag gehört", + "networkMap_statusStale": "Zuletzt nicht gehört", + "networkMap_confirmed": "Bestätigt", + "networkMap_singleSource": "Einzelne Quelle, noch nicht bestätigt", + "networkMap_reports": "Meldungen", + "networkMap_locationEstimated": "Ungefährer Standort, geschätzt anhand der Empfänger", + "networkMap_locationAdvertised": "Ungefährer Standort, aus dem eigenen Advert", + "networkMap_heardByRadio": "Von deinem Funkgerät gehört", + "networkMap_inYourArea": "In deiner Nähe", + "networkMap_farAway": "Weit entfernt. Verwaltung ist nicht möglich.", + "networkMap_addToContacts": "Zu Kontakten hinzufügen", + "networkMap_manage": "Verwalten", + "networkMap_addedToContacts": "Zu Kontakten hinzugefügt", + "networkMap_addFailed": "Hinzufügen zu Kontakten fehlgeschlagen", + "networkMap_unnamed": "Unbenannter Repeater" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4f02a208..f62a038b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -178,6 +178,10 @@ "scanner_chromeRequired": "Chrome Browser Required", "scanner_chromeRequiredMessage": "This web application requires Google Chrome or a Chromium-based browser for Bluetooth support.", "scanner_enableBluetooth": "Enable Bluetooth", + "scanner_getNodeTitle": "Need a new node?", + "scanner_getNodeBody": "Wallet-sized, runs MeshCore, dual-band GPS, waterproof, 5-day battery.", + "scanner_getNodeAction": "Get one here", + "scanner_getNodeDisclosure": "Affiliate link: each purchase supports MeshCore Open.", "scanner_bluetoothWebUnsupported": "Bluetooth isn't available in the browser. Connect over USB instead.", "device_quickSwitch": "Quick switch", "device_meshcore": "MeshCore", @@ -3443,5 +3447,42 @@ "neighbors_durationMinutes": "{minutes}m {seconds}s", "@neighbors_durationMinutes": {"placeholders": {"minutes": {"type": "int"}, "seconds": {"type": "String"}}}, "neighbors_durationHours": "{hours}h {minutes}m", - "@neighbors_durationHours": {"placeholders": {"hours": {"type": "int"}, "minutes": {"type": "int"}}} + "@neighbors_durationHours": {"placeholders": {"hours": {"type": "int"}, "minutes": {"type": "int"}}}, + "networkMap_settingsSection": "Network map", + "networkMap_uploadTitle": "Share what my radio hears", + "networkMap_uploadExplanation": "When this is on and your radio is connected, the app sends a short summary of the packets your radio hears to the MeshCore Open network map, so everyone can see which repeaters exist and how they link up. It sends each packet's type, route, hops, signal strength and size, plus repeater names and rough locations from their own adverts. It never sends message text, who is talking to whom, channel names, your contacts or your exact position: locations are rounded to about 2 km, and your app gets a new random ID every day.", + "networkMap_whatWeCollect": "What we collect", + "networkMap_promptTitle": "Help build the network map?", + "networkMap_promptBody": "MeshCore Open can share what your radio hears with the public network map at map.meshcoreopen.org, so everyone can see which repeaters exist and how they link up.\n\nIt never sends message text, who is talking to whom, channel names, your contacts or your exact position. Locations are rounded to about 2 km.", + "networkMap_promptSettingsHint": "You can change this any time in Settings → App settings → Network map.", + "networkMap_promptAccept": "Share", + "networkMap_promptDecline": "No thanks", + "networkMap_statusOff": "Off. Nothing is sent.", + "networkMap_statusWaiting": "On. Waiting for a radio connection.", + "networkMap_statusNothingSent": "On. Nothing sent yet.", + "networkMap_statusLastSent": "Last sent {time}. {count} packets today.", + "@networkMap_statusLastSent": {"placeholders": {"time": {"type": "String"}, "count": {"type": "int"}}}, + "networkMap_sourceLocal": "Local", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Both", + "networkMap_zoomInHint": "Zoom in to see the online network map", + "networkMap_loadFailed": "Couldn't load the online network map", + "networkMap_inYourContacts": "In your contacts", + "networkMap_status": "Status", + "networkMap_statusActive": "Active in the last hour", + "networkMap_statusRecent": "Heard in the last day", + "networkMap_statusStale": "Not heard lately", + "networkMap_confirmed": "Confirmed", + "networkMap_singleSource": "Single source, not yet confirmed", + "networkMap_reports": "Reports", + "networkMap_locationEstimated": "Rough location, estimated from who heard it", + "networkMap_locationAdvertised": "Rough location, from its own advert", + "networkMap_heardByRadio": "Heard by your radio", + "networkMap_inYourArea": "In your area", + "networkMap_farAway": "Far away. Management won't reach it.", + "networkMap_addToContacts": "Add to contacts", + "networkMap_manage": "Manage", + "networkMap_addedToContacts": "Added to contacts", + "networkMap_addFailed": "Couldn't add to contacts", + "networkMap_unnamed": "Unnamed repeater" } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 3b8e8a94..9023e268 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3394,5 +3394,55 @@ "usbChooseSerialPort": "Elegir puerto serie", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} min {seconds} s", - "neighbors_durationHours": "{hours} h {minutes} min" + "neighbors_durationHours": "{hours} h {minutes} min", + "scanner_getNodeTitle": "¿Necesitas un nodo nuevo?", + "scanner_getNodeBody": "Tamaño cartera, funciona con MeshCore, GPS de doble banda, resistente al agua y 5 días de batería.", + "scanner_getNodeAction": "Consíguelo aquí", + "scanner_getNodeDisclosure": "Enlace de afiliado: cada compra apoya a MeshCore Open.", + "networkMap_settingsSection": "Mapa de la red", + "networkMap_uploadTitle": "Compartir lo que escucha mi radio", + "networkMap_uploadExplanation": "Cuando esto está activado y tu radio está conectada, la app envía un breve resumen de los paquetes que escucha tu radio al mapa de la red de MeshCore Open, para que todos puedan ver qué repetidores existen y cómo se conectan. Envía el tipo, la ruta, los saltos, la intensidad de señal y el tamaño de cada paquete, además de los nombres y ubicaciones aproximadas de los repetidores a partir de sus propios adverts. Nunca envía el texto de los mensajes, quién habla con quién, nombres de canales, tus contactos ni tu posición exacta: las ubicaciones se redondean a unos 2 km y tu app recibe un ID aleatorio nuevo cada día.", + "networkMap_whatWeCollect": "Qué recopilamos", + "networkMap_promptTitle": "¿Ayudar a construir el mapa de la red?", + "networkMap_promptBody": "MeshCore Open puede compartir lo que escucha tu radio con el mapa público de la red en map.meshcoreopen.org, para que todos puedan ver qué repetidores existen y cómo se conectan.\n\nNunca envía el texto de los mensajes, quién habla con quién, nombres de canales, tus contactos ni tu posición exacta. Las ubicaciones se redondean a unos 2 km.", + "networkMap_promptSettingsHint": "Puedes cambiarlo cuando quieras en Configuración → Configuración de la App → Mapa de la red.", + "networkMap_promptAccept": "Compartir", + "networkMap_promptDecline": "No, gracias", + "networkMap_statusOff": "Desactivado. No se envía nada.", + "networkMap_statusWaiting": "Activado. Esperando conexión con la radio.", + "networkMap_statusNothingSent": "Activado. Aún no se ha enviado nada.", + "networkMap_statusLastSent": "Último envío {time}. {count} paquetes hoy.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Local", + "networkMap_sourceOnline": "En línea", + "networkMap_sourceBoth": "Ambos", + "networkMap_zoomInHint": "Acerca el zoom para ver el mapa de la red en línea", + "networkMap_loadFailed": "No se pudo cargar el mapa de la red en línea", + "networkMap_inYourContacts": "En tus contactos", + "networkMap_status": "Estado", + "networkMap_statusActive": "Activo en la última hora", + "networkMap_statusRecent": "Escuchado en el último día", + "networkMap_statusStale": "No escuchado recientemente", + "networkMap_confirmed": "Confirmado", + "networkMap_singleSource": "Fuente única, aún sin confirmar", + "networkMap_reports": "Reportes", + "networkMap_locationEstimated": "Ubicación aproximada, estimada según quién lo escuchó", + "networkMap_locationAdvertised": "Ubicación aproximada, de su propio advert", + "networkMap_heardByRadio": "Escuchado por tu radio", + "networkMap_inYourArea": "En tu zona", + "networkMap_farAway": "Muy lejos. La administración no podrá alcanzarlo.", + "networkMap_addToContacts": "Añadir a contactos", + "networkMap_manage": "Administrar", + "networkMap_addedToContacts": "Añadido a contactos", + "networkMap_addFailed": "No se pudo añadir a contactos", + "networkMap_unnamed": "Repetidor sin nombre" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 8323736d..f42ce6d6 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3394,5 +3394,55 @@ "usbChooseSerialPort": "Choisir le port série", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} min {seconds} s", - "neighbors_durationHours": "{hours} h {minutes} min" + "neighbors_durationHours": "{hours} h {minutes} min", + "scanner_getNodeTitle": "Besoin d'un nouveau nœud ?", + "scanner_getNodeBody": "Format portefeuille, fonctionne avec MeshCore, GPS bi-bande, étanche, 5 jours d'autonomie.", + "scanner_getNodeAction": "Obtenez-le ici", + "scanner_getNodeDisclosure": "Lien d'affiliation : chaque achat soutient MeshCore Open.", + "networkMap_settingsSection": "Carte du réseau", + "networkMap_uploadTitle": "Partager ce que ma radio entend", + "networkMap_uploadExplanation": "Lorsque cette option est activée et que votre radio est connectée, l'application envoie un court résumé des paquets entendus par votre radio à la carte du réseau MeshCore Open, afin que chacun puisse voir quels répéteurs existent et comment ils sont reliés. Elle envoie le type, la route, les sauts, la puissance du signal et la taille de chaque paquet, ainsi que les noms et les positions approximatives des répéteurs issus de leurs propres adverts. Elle n'envoie jamais le texte des messages, qui parle à qui, les noms des canaux, vos contacts ni votre position exacte : les positions sont arrondies à environ 2 km, et votre application reçoit chaque jour un nouvel identifiant aléatoire.", + "networkMap_whatWeCollect": "Ce que nous collectons", + "networkMap_promptTitle": "Aider à construire la carte du réseau ?", + "networkMap_promptBody": "MeshCore Open peut partager ce que votre radio entend avec la carte publique du réseau sur map.meshcoreopen.org, afin que chacun puisse voir quels répéteurs existent et comment ils sont reliés.\n\nElle n'envoie jamais le texte des messages, qui parle à qui, les noms des canaux, vos contacts ni votre position exacte. Les positions sont arrondies à environ 2 km.", + "networkMap_promptSettingsHint": "Vous pouvez modifier cela à tout moment dans Paramètres → Paramètres de l'application → Carte du réseau.", + "networkMap_promptAccept": "Partager", + "networkMap_promptDecline": "Non merci", + "networkMap_statusOff": "Désactivé. Rien n'est envoyé.", + "networkMap_statusWaiting": "Activé. En attente d'une connexion radio.", + "networkMap_statusNothingSent": "Activé. Rien n'a encore été envoyé.", + "networkMap_statusLastSent": "Dernier envoi {time}. {count} paquets aujourd'hui.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Local", + "networkMap_sourceOnline": "En ligne", + "networkMap_sourceBoth": "Les deux", + "networkMap_zoomInHint": "Zoomez pour voir la carte du réseau en ligne", + "networkMap_loadFailed": "Impossible de charger la carte du réseau en ligne", + "networkMap_inYourContacts": "Dans vos contacts", + "networkMap_status": "Statut", + "networkMap_statusActive": "Actif durant la dernière heure", + "networkMap_statusRecent": "Entendu durant le dernier jour", + "networkMap_statusStale": "Pas entendu récemment", + "networkMap_confirmed": "Confirmé", + "networkMap_singleSource": "Source unique, pas encore confirmé", + "networkMap_reports": "Rapports", + "networkMap_locationEstimated": "Position approximative, estimée d'après ceux qui l'ont entendu", + "networkMap_locationAdvertised": "Position approximative, issue de son propre advert", + "networkMap_heardByRadio": "Entendu par votre radio", + "networkMap_inYourArea": "Dans votre zone", + "networkMap_farAway": "Trop loin. La gestion ne pourra pas l'atteindre.", + "networkMap_addToContacts": "Ajouter aux contacts", + "networkMap_manage": "Gérer", + "networkMap_addedToContacts": "Ajouté aux contacts", + "networkMap_addFailed": "Impossible d'ajouter aux contacts", + "networkMap_unnamed": "Répéteur sans nom" } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index dbebcfd0..9f0bfee3 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3299,5 +3299,55 @@ "usbChooseSerialPort": "Soros port kiválasztása", "neighbors_durationSeconds": "{seconds} mp", "neighbors_durationMinutes": "{minutes} p {seconds} mp", - "neighbors_durationHours": "{hours} ó {minutes} p" + "neighbors_durationHours": "{hours} ó {minutes} p", + "scanner_getNodeTitle": "Új csomópontra van szükséged?", + "scanner_getNodeBody": "Pénztárca méretű, MeshCore-t futtat, kétsávos GPS, vízálló, 5 napos akkumulátor.", + "scanner_getNodeAction": "Itt szerezhetsz egyet", + "scanner_getNodeDisclosure": "Partnerlink: minden vásárlás a MeshCore Opent támogatja.", + "networkMap_settingsSection": "Hálózati térkép", + "networkMap_uploadTitle": "Megosztom, amit a rádióm hall", + "networkMap_uploadExplanation": "Ha ez be van kapcsolva és a rádió csatlakozik, az alkalmazás rövid összefoglalót küld a rádió által hallott csomagokról a MeshCore Open hálózati térképére, hogy mindenki lássa, milyen repeaterek léteznek és hogyan kapcsolódnak egymáshoz. Elküldi az egyes csomagok típusát, útvonalát, ugrásszámát, jelerősségét és méretét, valamint a repeaterek nevét és hozzávetőleges helyét a saját advertjeikből. Soha nem küld üzenetszöveget, azt, hogy ki kivel beszélget, csatornaneveket, a kapcsolataidat vagy a pontos helyzetedet: a helyek kb. 2 km-re kerekítettek, az alkalmazásod pedig naponta új véletlenszerű azonosítót kap.", + "networkMap_whatWeCollect": "Mit gyűjtünk", + "networkMap_promptTitle": "Segítesz a hálózati térkép építésében?", + "networkMap_promptBody": "A MeshCore Open megoszthatja, amit a rádiód hall, a nyilvános hálózati térképpel a map.meshcoreopen.org oldalon, hogy mindenki lássa, milyen repeaterek léteznek és hogyan kapcsolódnak egymáshoz.\n\nSoha nem küld üzenetszöveget, azt, hogy ki kivel beszélget, csatornaneveket, a kapcsolataidat vagy a pontos helyzetedet. A helyek kb. 2 km-re kerekítettek.", + "networkMap_promptSettingsHint": "Ezt bármikor módosíthatod: Beállítások → Alkalmazásbeállítások → Hálózati térkép.", + "networkMap_promptAccept": "Megosztás", + "networkMap_promptDecline": "Köszönöm, nem", + "networkMap_statusOff": "Kikapcsolva. Semmi sem kerül elküldésre.", + "networkMap_statusWaiting": "Bekapcsolva. Várakozás a rádiókapcsolatra.", + "networkMap_statusNothingSent": "Bekapcsolva. Még nem ment el semmi.", + "networkMap_statusLastSent": "Utoljára elküldve: {time}. Ma {count} csomag.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Helyi", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Mindkettő", + "networkMap_zoomInHint": "Nagyíts rá az online hálózati térkép megtekintéséhez", + "networkMap_loadFailed": "Nem sikerült betölteni az online hálózati térképet", + "networkMap_inYourContacts": "A kapcsolataid között", + "networkMap_status": "Állapot", + "networkMap_statusActive": "Aktív az elmúlt órában", + "networkMap_statusRecent": "Hallva az elmúlt napban", + "networkMap_statusStale": "Mostanában nem hallható", + "networkMap_confirmed": "Megerősítve", + "networkMap_singleSource": "Egyetlen forrás, még nem megerősített", + "networkMap_reports": "Jelentések", + "networkMap_locationEstimated": "Hozzávetőleges hely, a hallók alapján becsülve", + "networkMap_locationAdvertised": "Hozzávetőleges hely, a saját advertjéből", + "networkMap_heardByRadio": "A rádiód hallja", + "networkMap_inYourArea": "A közeledben", + "networkMap_farAway": "Messze van. A kezelés nem éri el.", + "networkMap_addToContacts": "Hozzáadás a kapcsolatokhoz", + "networkMap_manage": "Kezelés", + "networkMap_addedToContacts": "Hozzáadva a kapcsolatokhoz", + "networkMap_addFailed": "Nem sikerült hozzáadni a kapcsolatokhoz", + "networkMap_unnamed": "Névtelen repeater" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 5bc6ff80..89a86aad 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3394,5 +3394,55 @@ "usbChooseSerialPort": "Scegli porta seriale", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} min {seconds} s", - "neighbors_durationHours": "{hours} h {minutes} min" + "neighbors_durationHours": "{hours} h {minutes} min", + "scanner_getNodeTitle": "Ti serve un nuovo nodo?", + "scanner_getNodeBody": "Grande come un portafoglio, funziona con MeshCore, GPS dual-band, impermeabile, 5 giorni di batteria.", + "scanner_getNodeAction": "Prendilo qui", + "scanner_getNodeDisclosure": "Link di affiliazione: ogni acquisto sostiene MeshCore Open.", + "networkMap_settingsSection": "Mappa della rete", + "networkMap_uploadTitle": "Condividi ciò che sente la mia radio", + "networkMap_uploadExplanation": "Quando è attivo e la tua radio è connessa, l'app invia un breve riepilogo dei pacchetti sentiti dalla tua radio alla mappa della rete di MeshCore Open, così tutti possono vedere quali ripetitori esistono e come sono collegati. Invia tipo, percorso, hop, intensità del segnale e dimensione di ogni pacchetto, oltre a nomi e posizioni approssimative dei ripetitori ricavati dai loro advert. Non invia mai il testo dei messaggi, chi parla con chi, i nomi dei canali, i tuoi contatti né la tua posizione esatta: le posizioni sono arrotondate a circa 2 km e la tua app riceve ogni giorno un nuovo ID casuale.", + "networkMap_whatWeCollect": "Cosa raccogliamo", + "networkMap_promptTitle": "Vuoi aiutare a costruire la mappa della rete?", + "networkMap_promptBody": "MeshCore Open può condividere ciò che sente la tua radio con la mappa pubblica della rete su map.meshcoreopen.org, così tutti possono vedere quali ripetitori esistono e come sono collegati.\n\nNon invia mai il testo dei messaggi, chi parla con chi, i nomi dei canali, i tuoi contatti né la tua posizione esatta. Le posizioni sono arrotondate a circa 2 km.", + "networkMap_promptSettingsHint": "Puoi cambiarlo in qualsiasi momento in Impostazioni → Impostazioni App → Mappa della rete.", + "networkMap_promptAccept": "Condividi", + "networkMap_promptDecline": "No, grazie", + "networkMap_statusOff": "Disattivato. Non viene inviato nulla.", + "networkMap_statusWaiting": "Attivo. In attesa della connessione con la radio.", + "networkMap_statusNothingSent": "Attivo. Ancora nulla inviato.", + "networkMap_statusLastSent": "Ultimo invio {time}. {count} pacchetti oggi.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Locale", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Entrambi", + "networkMap_zoomInHint": "Ingrandisci per vedere la mappa della rete online", + "networkMap_loadFailed": "Impossibile caricare la mappa della rete online", + "networkMap_inYourContacts": "Nei tuoi contatti", + "networkMap_status": "Stato", + "networkMap_statusActive": "Attivo nell'ultima ora", + "networkMap_statusRecent": "Sentito nell'ultimo giorno", + "networkMap_statusStale": "Non sentito di recente", + "networkMap_confirmed": "Confermato", + "networkMap_singleSource": "Fonte singola, non ancora confermato", + "networkMap_reports": "Segnalazioni", + "networkMap_locationEstimated": "Posizione approssimativa, stimata in base a chi l'ha sentito", + "networkMap_locationAdvertised": "Posizione approssimativa, dal suo advert", + "networkMap_heardByRadio": "Sentito dalla tua radio", + "networkMap_inYourArea": "Nella tua zona", + "networkMap_farAway": "Troppo lontano. La gestione non lo raggiungerà.", + "networkMap_addToContacts": "Aggiungi ai contatti", + "networkMap_manage": "Gestisci", + "networkMap_addedToContacts": "Aggiunto ai contatti", + "networkMap_addFailed": "Impossibile aggiungere ai contatti", + "networkMap_unnamed": "Ripetitore senza nome" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index f4fd5e12..468d0d16 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -3394,5 +3394,55 @@ "usbChooseSerialPort": "シリアルポートを選択", "neighbors_durationSeconds": "{seconds}秒", "neighbors_durationMinutes": "{minutes}分{seconds}秒", - "neighbors_durationHours": "{hours}時間{minutes}分" + "neighbors_durationHours": "{hours}時間{minutes}分", + "scanner_getNodeTitle": "新しいノードが必要ですか?", + "scanner_getNodeBody": "財布サイズで MeshCore が動作。デュアルバンドGPS、防水、バッテリー5日間。", + "scanner_getNodeAction": "こちらで入手", + "scanner_getNodeDisclosure": "アフィリエイトリンク: 購入のたびに MeshCore Open を応援できます。", + "networkMap_settingsSection": "ネットワークマップ", + "networkMap_uploadTitle": "ラジオが受信した情報を共有", + "networkMap_uploadExplanation": "オンにしてラジオが接続されている間、ラジオが受信したパケットの概要をアプリが MeshCore Open のネットワークマップに送信します。これにより、どんなリピータがあり、どうつながっているかを誰でも見られます。送信するのは、各パケットの種類、経路、ホップ数、信号強度、サイズと、リピータ自身のアドバートに含まれる名前とおおよその位置です。メッセージの本文、誰が誰と話しているか、チャンネル名、連絡先、正確な位置は送信しません。位置は約2km単位に丸められ、アプリのIDは毎日ランダムに新しくなります。", + "networkMap_whatWeCollect": "収集する情報", + "networkMap_promptTitle": "ネットワークマップの作成にご協力いただけますか?", + "networkMap_promptBody": "MeshCore Open は、ラジオが受信した情報を map.meshcoreopen.org の公開ネットワークマップと共有できます。これにより、どんなリピータがあり、どうつながっているかを誰でも見られます。\n\nメッセージの本文、誰が誰と話しているか、チャンネル名、連絡先、正確な位置は送信しません。位置は約2km単位に丸められます。", + "networkMap_promptSettingsHint": "この設定はいつでも「設定」→「アプリ設定」→「ネットワークマップ」で変更できます。", + "networkMap_promptAccept": "共有する", + "networkMap_promptDecline": "いいえ、結構です", + "networkMap_statusOff": "オフ。何も送信されません。", + "networkMap_statusWaiting": "オン。ラジオの接続を待っています。", + "networkMap_statusNothingSent": "オン。まだ何も送信されていません。", + "networkMap_statusLastSent": "最終送信: {time}。今日は{count}パケット。", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "ローカル", + "networkMap_sourceOnline": "オンライン", + "networkMap_sourceBoth": "両方", + "networkMap_zoomInHint": "ズームインするとオンラインのネットワークマップが表示されます", + "networkMap_loadFailed": "オンラインのネットワークマップを読み込めませんでした", + "networkMap_inYourContacts": "連絡先にあります", + "networkMap_status": "ステータス", + "networkMap_statusActive": "直近1時間にアクティブ", + "networkMap_statusRecent": "直近1日以内に受信", + "networkMap_statusStale": "最近受信されていません", + "networkMap_confirmed": "確認済み", + "networkMap_singleSource": "情報源が1つのみで、未確認", + "networkMap_reports": "レポート", + "networkMap_locationEstimated": "おおよその位置(受信したノードから推定)", + "networkMap_locationAdvertised": "おおよその位置(自身のアドバートより)", + "networkMap_heardByRadio": "ラジオが受信", + "networkMap_inYourArea": "お近く", + "networkMap_farAway": "遠すぎます。管理はできません。", + "networkMap_addToContacts": "連絡先に追加", + "networkMap_manage": "管理", + "networkMap_addedToContacts": "連絡先に追加しました", + "networkMap_addFailed": "連絡先に追加できませんでした", + "networkMap_unnamed": "名前のないリピータ" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 33414974..38869f9a 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3394,5 +3394,55 @@ "usbChooseSerialPort": "시리얼 포트 선택", "neighbors_durationSeconds": "{seconds}초", "neighbors_durationMinutes": "{minutes}분 {seconds}초", - "neighbors_durationHours": "{hours}시간 {minutes}분" + "neighbors_durationHours": "{hours}시간 {minutes}분", + "scanner_getNodeTitle": "새 노드가 필요하신가요?", + "scanner_getNodeBody": "지갑 크기에 MeshCore 구동, 듀얼 밴드 GPS, 방수, 5일 배터리.", + "scanner_getNodeAction": "여기서 구하기", + "scanner_getNodeDisclosure": "제휴 링크: 구매할 때마다 MeshCore Open을 후원하게 됩니다.", + "networkMap_settingsSection": "네트워크 지도", + "networkMap_uploadTitle": "내 라디오가 수신한 정보 공유", + "networkMap_uploadExplanation": "이 기능을 켜고 라디오가 연결되어 있으면, 앱이 라디오가 수신한 패킷의 요약 정보를 MeshCore Open 네트워크 지도로 보내 어떤 리피터가 있고 서로 어떻게 연결되는지 모두가 볼 수 있게 합니다. 각 패킷의 종류, 경로, 홉 수, 신호 세기, 크기와 함께 리피터 자체 어드버트에 담긴 이름과 대략적인 위치를 보냅니다. 메시지 내용, 누가 누구와 대화하는지, 채널 이름, 연락처, 정확한 위치는 절대 보내지 않습니다. 위치는 약 2km 단위로 반올림되며, 앱 ID는 매일 새로운 무작위 값으로 바뀝니다.", + "networkMap_whatWeCollect": "수집하는 정보", + "networkMap_promptTitle": "네트워크 지도 만들기에 참여하시겠어요?", + "networkMap_promptBody": "MeshCore Open은 라디오가 수신한 정보를 map.meshcoreopen.org의 공개 네트워크 지도와 공유하여, 어떤 리피터가 있고 서로 어떻게 연결되는지 모두가 볼 수 있게 할 수 있습니다.\n\n메시지 내용, 누가 누구와 대화하는지, 채널 이름, 연락처, 정확한 위치는 절대 보내지 않습니다. 위치는 약 2km 단위로 반올림됩니다.", + "networkMap_promptSettingsHint": "설정 → 앱 설정 → 네트워크 지도에서 언제든지 변경할 수 있습니다.", + "networkMap_promptAccept": "공유", + "networkMap_promptDecline": "괜찮아요", + "networkMap_statusOff": "꺼짐. 아무것도 전송되지 않습니다.", + "networkMap_statusWaiting": "켜짐. 라디오 연결을 기다리는 중입니다.", + "networkMap_statusNothingSent": "켜짐. 아직 전송한 내용이 없습니다.", + "networkMap_statusLastSent": "마지막 전송 {time}. 오늘 패킷 {count}개.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "로컬", + "networkMap_sourceOnline": "온라인", + "networkMap_sourceBoth": "모두", + "networkMap_zoomInHint": "온라인 네트워크 지도를 보려면 확대하세요", + "networkMap_loadFailed": "온라인 네트워크 지도를 불러오지 못했습니다", + "networkMap_inYourContacts": "내 연락처에 있음", + "networkMap_status": "상태", + "networkMap_statusActive": "최근 1시간 이내 활동", + "networkMap_statusRecent": "최근 하루 이내 수신", + "networkMap_statusStale": "최근 수신 없음", + "networkMap_confirmed": "확인됨", + "networkMap_singleSource": "단일 출처, 아직 확인되지 않음", + "networkMap_reports": "보고", + "networkMap_locationEstimated": "대략적인 위치, 수신한 노드를 기준으로 추정", + "networkMap_locationAdvertised": "대략적인 위치, 자체 어드버트 기준", + "networkMap_heardByRadio": "내 라디오가 수신함", + "networkMap_inYourArea": "내 주변 지역", + "networkMap_farAway": "멀리 떨어져 있어 관리할 수 없습니다.", + "networkMap_addToContacts": "연락처에 추가", + "networkMap_manage": "관리", + "networkMap_addedToContacts": "연락처에 추가됨", + "networkMap_addFailed": "연락처에 추가하지 못했습니다", + "networkMap_unnamed": "이름 없는 리피터" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 64af168c..b5e7efc5 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -742,6 +742,30 @@ abstract class AppLocalizations { /// **'Enable Bluetooth'** String get scanner_enableBluetooth; + /// No description provided for @scanner_getNodeTitle. + /// + /// In en, this message translates to: + /// **'Need a new node?'** + String get scanner_getNodeTitle; + + /// No description provided for @scanner_getNodeBody. + /// + /// In en, this message translates to: + /// **'Wallet-sized, runs MeshCore, dual-band GPS, waterproof, 5-day battery.'** + String get scanner_getNodeBody; + + /// No description provided for @scanner_getNodeAction. + /// + /// In en, this message translates to: + /// **'Get one here'** + String get scanner_getNodeAction; + + /// No description provided for @scanner_getNodeDisclosure. + /// + /// In en, this message translates to: + /// **'Affiliate link: each purchase supports MeshCore Open.'** + String get scanner_getNodeDisclosure; + /// No description provided for @scanner_bluetoothWebUnsupported. /// /// In en, this message translates to: @@ -10350,6 +10374,222 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'{hours}h {minutes}m'** String neighbors_durationHours(int hours, int minutes); + + /// No description provided for @networkMap_settingsSection. + /// + /// In en, this message translates to: + /// **'Network map'** + String get networkMap_settingsSection; + + /// No description provided for @networkMap_uploadTitle. + /// + /// In en, this message translates to: + /// **'Share what my radio hears'** + String get networkMap_uploadTitle; + + /// No description provided for @networkMap_uploadExplanation. + /// + /// In en, this message translates to: + /// **'When this is on and your radio is connected, the app sends a short summary of the packets your radio hears to the MeshCore Open network map, so everyone can see which repeaters exist and how they link up. It sends each packet\'s type, route, hops, signal strength and size, plus repeater names and rough locations from their own adverts. It never sends message text, who is talking to whom, channel names, your contacts or your exact position: locations are rounded to about 2 km, and your app gets a new random ID every day.'** + String get networkMap_uploadExplanation; + + /// No description provided for @networkMap_whatWeCollect. + /// + /// In en, this message translates to: + /// **'What we collect'** + String get networkMap_whatWeCollect; + + /// No description provided for @networkMap_promptTitle. + /// + /// In en, this message translates to: + /// **'Help build the network map?'** + String get networkMap_promptTitle; + + /// No description provided for @networkMap_promptBody. + /// + /// In en, this message translates to: + /// **'MeshCore Open can share what your radio hears with the public network map at map.meshcoreopen.org, so everyone can see which repeaters exist and how they link up.\n\nIt never sends message text, who is talking to whom, channel names, your contacts or your exact position. Locations are rounded to about 2 km.'** + String get networkMap_promptBody; + + /// No description provided for @networkMap_promptSettingsHint. + /// + /// In en, this message translates to: + /// **'You can change this any time in Settings → App settings → Network map.'** + String get networkMap_promptSettingsHint; + + /// No description provided for @networkMap_promptAccept. + /// + /// In en, this message translates to: + /// **'Share'** + String get networkMap_promptAccept; + + /// No description provided for @networkMap_promptDecline. + /// + /// In en, this message translates to: + /// **'No thanks'** + String get networkMap_promptDecline; + + /// No description provided for @networkMap_statusOff. + /// + /// In en, this message translates to: + /// **'Off. Nothing is sent.'** + String get networkMap_statusOff; + + /// No description provided for @networkMap_statusWaiting. + /// + /// In en, this message translates to: + /// **'On. Waiting for a radio connection.'** + String get networkMap_statusWaiting; + + /// No description provided for @networkMap_statusNothingSent. + /// + /// In en, this message translates to: + /// **'On. Nothing sent yet.'** + String get networkMap_statusNothingSent; + + /// No description provided for @networkMap_statusLastSent. + /// + /// In en, this message translates to: + /// **'Last sent {time}. {count} packets today.'** + String networkMap_statusLastSent(String time, int count); + + /// No description provided for @networkMap_sourceLocal. + /// + /// In en, this message translates to: + /// **'Local'** + String get networkMap_sourceLocal; + + /// No description provided for @networkMap_sourceOnline. + /// + /// In en, this message translates to: + /// **'Online'** + String get networkMap_sourceOnline; + + /// No description provided for @networkMap_sourceBoth. + /// + /// In en, this message translates to: + /// **'Both'** + String get networkMap_sourceBoth; + + /// No description provided for @networkMap_zoomInHint. + /// + /// In en, this message translates to: + /// **'Zoom in to see the online network map'** + String get networkMap_zoomInHint; + + /// No description provided for @networkMap_loadFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t load the online network map'** + String get networkMap_loadFailed; + + /// No description provided for @networkMap_inYourContacts. + /// + /// In en, this message translates to: + /// **'In your contacts'** + String get networkMap_inYourContacts; + + /// No description provided for @networkMap_status. + /// + /// In en, this message translates to: + /// **'Status'** + String get networkMap_status; + + /// No description provided for @networkMap_statusActive. + /// + /// In en, this message translates to: + /// **'Active in the last hour'** + String get networkMap_statusActive; + + /// No description provided for @networkMap_statusRecent. + /// + /// In en, this message translates to: + /// **'Heard in the last day'** + String get networkMap_statusRecent; + + /// No description provided for @networkMap_statusStale. + /// + /// In en, this message translates to: + /// **'Not heard lately'** + String get networkMap_statusStale; + + /// No description provided for @networkMap_confirmed. + /// + /// In en, this message translates to: + /// **'Confirmed'** + String get networkMap_confirmed; + + /// No description provided for @networkMap_singleSource. + /// + /// In en, this message translates to: + /// **'Single source, not yet confirmed'** + String get networkMap_singleSource; + + /// No description provided for @networkMap_reports. + /// + /// In en, this message translates to: + /// **'Reports'** + String get networkMap_reports; + + /// No description provided for @networkMap_locationEstimated. + /// + /// In en, this message translates to: + /// **'Rough location, estimated from who heard it'** + String get networkMap_locationEstimated; + + /// No description provided for @networkMap_locationAdvertised. + /// + /// In en, this message translates to: + /// **'Rough location, from its own advert'** + String get networkMap_locationAdvertised; + + /// No description provided for @networkMap_heardByRadio. + /// + /// In en, this message translates to: + /// **'Heard by your radio'** + String get networkMap_heardByRadio; + + /// No description provided for @networkMap_inYourArea. + /// + /// In en, this message translates to: + /// **'In your area'** + String get networkMap_inYourArea; + + /// No description provided for @networkMap_farAway. + /// + /// In en, this message translates to: + /// **'Far away. Management won\'t reach it.'** + String get networkMap_farAway; + + /// No description provided for @networkMap_addToContacts. + /// + /// In en, this message translates to: + /// **'Add to contacts'** + String get networkMap_addToContacts; + + /// No description provided for @networkMap_manage. + /// + /// In en, this message translates to: + /// **'Manage'** + String get networkMap_manage; + + /// No description provided for @networkMap_addedToContacts. + /// + /// In en, this message translates to: + /// **'Added to contacts'** + String get networkMap_addedToContacts; + + /// No description provided for @networkMap_addFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t add to contacts'** + String get networkMap_addFailed; + + /// No description provided for @networkMap_unnamed. + /// + /// In en, this message translates to: + /// **'Unnamed repeater'** + String get networkMap_unnamed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 7e143c2a..b9f79a6f 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -358,6 +358,20 @@ class AppLocalizationsBg extends AppLocalizations { @override String get scanner_enableBluetooth => 'Активирайте Bluetooth'; + @override + String get scanner_getNodeTitle => 'Нуждаете се от нов възел?'; + + @override + String get scanner_getNodeBody => + 'Колкото портфейл, работи с MeshCore, двулентов GPS, водоустойчив, батерия за 5 дни.'; + + @override + String get scanner_getNodeAction => 'Вземете го тук'; + + @override + String get scanner_getNodeDisclosure => + 'Партньорска връзка: всяка покупка подкрепя MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Функцията Bluetooth не е налична в браузъра. Моля, свържете се чрез USB вместо това.'; @@ -6180,4 +6194,125 @@ class AppLocalizationsBg extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hoursч $minutesм'; } + + @override + String get networkMap_settingsSection => 'Мрежова карта'; + + @override + String get networkMap_uploadTitle => + 'Споделяне на това, което чува моето радио'; + + @override + String get networkMap_uploadExplanation => + 'Когато това е включено и радиото е свързано, приложението изпраща към мрежовата карта на MeshCore Open кратко обобщение на пакетите, които радиото ви чува, за да може всеки да вижда кои повторители съществуват и как са свързани. Изпращат се типът, маршрутът, броят хопове, силата на сигнала и размерът на всеки пакет, както и имената на повторителите и приблизителното им местоположение от техните собствени обяви. Никога не се изпращат текст на съобщения, кой с кого говори, имена на канали, вашите контакти или точното ви местоположение: координатите се закръглят до около 2 км, а приложението получава нов случаен ID всеки ден.'; + + @override + String get networkMap_whatWeCollect => 'Какво събираме'; + + @override + String get networkMap_promptTitle => 'Ще помогнете ли за мрежовата карта?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open може да споделя това, което радиото ви чува, с публичната мрежова карта на map.meshcoreopen.org, за да може всеки да вижда кои повторители съществуват и как са свързани.\n\nНикога не се изпращат текст на съобщения, кой с кого говори, имена на канали, вашите контакти или точното ви местоположение. Координатите се закръглят до около 2 км.'; + + @override + String get networkMap_promptSettingsHint => + 'Можете да промените това по всяко време в Настройки → Настройки на приложението → Мрежова карта.'; + + @override + String get networkMap_promptAccept => 'Споделям'; + + @override + String get networkMap_promptDecline => 'Не, благодаря'; + + @override + String get networkMap_statusOff => 'Изключено. Нищо не се изпраща.'; + + @override + String get networkMap_statusWaiting => + 'Включено. Изчакване на връзка с радио.'; + + @override + String get networkMap_statusNothingSent => + 'Включено. Още нищо не е изпратено.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Последно изпращане: $time. Пакети днес: $count.'; + } + + @override + String get networkMap_sourceLocal => 'Локална'; + + @override + String get networkMap_sourceOnline => 'Онлайн'; + + @override + String get networkMap_sourceBoth => 'И двете'; + + @override + String get networkMap_zoomInHint => + 'Увеличете, за да видите онлайн мрежовата карта'; + + @override + String get networkMap_loadFailed => + 'Онлайн мрежовата карта не можа да се зареди'; + + @override + String get networkMap_inYourContacts => 'В контактите ви'; + + @override + String get networkMap_status => 'Статус'; + + @override + String get networkMap_statusActive => 'Активен през последния час'; + + @override + String get networkMap_statusRecent => 'Чут през последното денонощие'; + + @override + String get networkMap_statusStale => 'Отдавна не е чут'; + + @override + String get networkMap_confirmed => 'Потвърден'; + + @override + String get networkMap_singleSource => 'Един източник, още непотвърден'; + + @override + String get networkMap_reports => 'Доклади'; + + @override + String get networkMap_locationEstimated => + 'Приблизително местоположение, изчислено по тези, които са го чули'; + + @override + String get networkMap_locationAdvertised => + 'Приблизително местоположение, от собствената му обява'; + + @override + String get networkMap_heardByRadio => 'Чут от вашето радио'; + + @override + String get networkMap_inYourArea => 'Във вашия район'; + + @override + String get networkMap_farAway => + 'Далече. Управлението няма да стигне до него.'; + + @override + String get networkMap_addToContacts => 'Добави към контактите'; + + @override + String get networkMap_manage => 'Управление'; + + @override + String get networkMap_addedToContacts => 'Добавено към контактите'; + + @override + String get networkMap_addFailed => 'Неуспешно добавяне към контактите'; + + @override + String get networkMap_unnamed => 'Неназован повторител'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 92b6653a..d7893ccf 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -361,6 +361,20 @@ class AppLocalizationsDe extends AppLocalizations { @override String get scanner_enableBluetooth => 'Bluetooth aktivieren'; + @override + String get scanner_getNodeTitle => 'Brauchst du einen neuen Node?'; + + @override + String get scanner_getNodeBody => + 'Im Hosentaschenformat, mit MeshCore, Dualband-GPS, wasserdicht und 5 Tage Akkulaufzeit.'; + + @override + String get scanner_getNodeAction => 'Hier holen'; + + @override + String get scanner_getNodeDisclosure => + 'Affiliate-Link: Jeder Kauf unterstützt MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth ist im Browser nicht verfügbar. Verwenden Sie stattdessen eine USB-Verbindung.'; @@ -6195,4 +6209,123 @@ class AppLocalizationsDe extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours Std. $minutes Min.'; } + + @override + String get networkMap_settingsSection => 'Netzwerkkarte'; + + @override + String get networkMap_uploadTitle => 'Teilen, was mein Funkgerät hört'; + + @override + String get networkMap_uploadExplanation => + 'Wenn dies aktiviert und dein Funkgerät verbunden ist, sendet die App eine kurze Zusammenfassung der Pakete, die dein Funkgerät empfängt, an die MeshCore-Open-Netzwerkkarte, damit alle sehen können, welche Repeater es gibt und wie sie verbunden sind. Gesendet werden Typ, Route, Hops, Signalstärke und Größe jedes Pakets sowie Repeater-Namen und ungefähre Standorte aus deren eigenen Adverts. Nie gesendet werden Nachrichtentexte, wer mit wem spricht, Kanalnamen, deine Kontakte oder dein genauer Standort: Standorte werden auf etwa 2 km gerundet, und deine App erhält jeden Tag eine neue zufällige ID.'; + + @override + String get networkMap_whatWeCollect => 'Was wir erfassen'; + + @override + String get networkMap_promptTitle => 'Beim Aufbau der Netzwerkkarte helfen?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open kann teilen, was dein Funkgerät hört, und zwar mit der öffentlichen Netzwerkkarte unter map.meshcoreopen.org, damit alle sehen können, welche Repeater es gibt und wie sie verbunden sind.\n\nEs werden nie Nachrichtentexte, wer mit wem spricht, Kanalnamen, deine Kontakte oder dein genauer Standort gesendet. Standorte werden auf etwa 2 km gerundet.'; + + @override + String get networkMap_promptSettingsHint => + 'Du kannst dies jederzeit unter Einstellungen → App-Einstellungen → Netzwerkkarte ändern.'; + + @override + String get networkMap_promptAccept => 'Teilen'; + + @override + String get networkMap_promptDecline => 'Nein danke'; + + @override + String get networkMap_statusOff => 'Aus. Es wird nichts gesendet.'; + + @override + String get networkMap_statusWaiting => + 'An. Warte auf eine Funkgerät-Verbindung.'; + + @override + String get networkMap_statusNothingSent => 'An. Noch nichts gesendet.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Zuletzt gesendet $time. Heute $count Pakete.'; + } + + @override + String get networkMap_sourceLocal => 'Lokal'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Beides'; + + @override + String get networkMap_zoomInHint => + 'Zoome hinein, um die Online-Netzwerkkarte zu sehen'; + + @override + String get networkMap_loadFailed => + 'Online-Netzwerkkarte konnte nicht geladen werden'; + + @override + String get networkMap_inYourContacts => 'In deinen Kontakten'; + + @override + String get networkMap_status => 'Status'; + + @override + String get networkMap_statusActive => 'Aktiv in der letzten Stunde'; + + @override + String get networkMap_statusRecent => 'Am letzten Tag gehört'; + + @override + String get networkMap_statusStale => 'Zuletzt nicht gehört'; + + @override + String get networkMap_confirmed => 'Bestätigt'; + + @override + String get networkMap_singleSource => 'Einzelne Quelle, noch nicht bestätigt'; + + @override + String get networkMap_reports => 'Meldungen'; + + @override + String get networkMap_locationEstimated => + 'Ungefährer Standort, geschätzt anhand der Empfänger'; + + @override + String get networkMap_locationAdvertised => + 'Ungefährer Standort, aus dem eigenen Advert'; + + @override + String get networkMap_heardByRadio => 'Von deinem Funkgerät gehört'; + + @override + String get networkMap_inYourArea => 'In deiner Nähe'; + + @override + String get networkMap_farAway => + 'Weit entfernt. Verwaltung ist nicht möglich.'; + + @override + String get networkMap_addToContacts => 'Zu Kontakten hinzufügen'; + + @override + String get networkMap_manage => 'Verwalten'; + + @override + String get networkMap_addedToContacts => 'Zu Kontakten hinzugefügt'; + + @override + String get networkMap_addFailed => 'Hinzufügen zu Kontakten fehlgeschlagen'; + + @override + String get networkMap_unnamed => 'Unbenannter Repeater'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 76da02cd..0265ac8b 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -355,6 +355,20 @@ class AppLocalizationsEn extends AppLocalizations { @override String get scanner_enableBluetooth => 'Enable Bluetooth'; + @override + String get scanner_getNodeTitle => 'Need a new node?'; + + @override + String get scanner_getNodeBody => + 'Wallet-sized, runs MeshCore, dual-band GPS, waterproof, 5-day battery.'; + + @override + String get scanner_getNodeAction => 'Get one here'; + + @override + String get scanner_getNodeDisclosure => + 'Affiliate link: each purchase supports MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth isn\'t available in the browser. Connect over USB instead.'; @@ -6094,4 +6108,119 @@ class AppLocalizationsEn extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '${hours}h ${minutes}m'; } + + @override + String get networkMap_settingsSection => 'Network map'; + + @override + String get networkMap_uploadTitle => 'Share what my radio hears'; + + @override + String get networkMap_uploadExplanation => + 'When this is on and your radio is connected, the app sends a short summary of the packets your radio hears to the MeshCore Open network map, so everyone can see which repeaters exist and how they link up. It sends each packet\'s type, route, hops, signal strength and size, plus repeater names and rough locations from their own adverts. It never sends message text, who is talking to whom, channel names, your contacts or your exact position: locations are rounded to about 2 km, and your app gets a new random ID every day.'; + + @override + String get networkMap_whatWeCollect => 'What we collect'; + + @override + String get networkMap_promptTitle => 'Help build the network map?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open can share what your radio hears with the public network map at map.meshcoreopen.org, so everyone can see which repeaters exist and how they link up.\n\nIt never sends message text, who is talking to whom, channel names, your contacts or your exact position. Locations are rounded to about 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'You can change this any time in Settings → App settings → Network map.'; + + @override + String get networkMap_promptAccept => 'Share'; + + @override + String get networkMap_promptDecline => 'No thanks'; + + @override + String get networkMap_statusOff => 'Off. Nothing is sent.'; + + @override + String get networkMap_statusWaiting => 'On. Waiting for a radio connection.'; + + @override + String get networkMap_statusNothingSent => 'On. Nothing sent yet.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Last sent $time. $count packets today.'; + } + + @override + String get networkMap_sourceLocal => 'Local'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Both'; + + @override + String get networkMap_zoomInHint => 'Zoom in to see the online network map'; + + @override + String get networkMap_loadFailed => 'Couldn\'t load the online network map'; + + @override + String get networkMap_inYourContacts => 'In your contacts'; + + @override + String get networkMap_status => 'Status'; + + @override + String get networkMap_statusActive => 'Active in the last hour'; + + @override + String get networkMap_statusRecent => 'Heard in the last day'; + + @override + String get networkMap_statusStale => 'Not heard lately'; + + @override + String get networkMap_confirmed => 'Confirmed'; + + @override + String get networkMap_singleSource => 'Single source, not yet confirmed'; + + @override + String get networkMap_reports => 'Reports'; + + @override + String get networkMap_locationEstimated => + 'Rough location, estimated from who heard it'; + + @override + String get networkMap_locationAdvertised => + 'Rough location, from its own advert'; + + @override + String get networkMap_heardByRadio => 'Heard by your radio'; + + @override + String get networkMap_inYourArea => 'In your area'; + + @override + String get networkMap_farAway => 'Far away. Management won\'t reach it.'; + + @override + String get networkMap_addToContacts => 'Add to contacts'; + + @override + String get networkMap_manage => 'Manage'; + + @override + String get networkMap_addedToContacts => 'Added to contacts'; + + @override + String get networkMap_addFailed => 'Couldn\'t add to contacts'; + + @override + String get networkMap_unnamed => 'Unnamed repeater'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index ed53314a..75c2ab0e 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -359,6 +359,20 @@ class AppLocalizationsEs extends AppLocalizations { @override String get scanner_enableBluetooth => 'Habilitar Bluetooth'; + @override + String get scanner_getNodeTitle => '¿Necesitas un nodo nuevo?'; + + @override + String get scanner_getNodeBody => + 'Tamaño cartera, funciona con MeshCore, GPS de doble banda, resistente al agua y 5 días de batería.'; + + @override + String get scanner_getNodeAction => 'Consíguelo aquí'; + + @override + String get scanner_getNodeDisclosure => + 'Enlace de afiliado: cada compra apoya a MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'La funcionalidad Bluetooth no está disponible en el navegador. Conéctese mediante USB en su lugar.'; @@ -6183,4 +6197,124 @@ class AppLocalizationsEs extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours h $minutes min'; } + + @override + String get networkMap_settingsSection => 'Mapa de la red'; + + @override + String get networkMap_uploadTitle => 'Compartir lo que escucha mi radio'; + + @override + String get networkMap_uploadExplanation => + 'Cuando esto está activado y tu radio está conectada, la app envía un breve resumen de los paquetes que escucha tu radio al mapa de la red de MeshCore Open, para que todos puedan ver qué repetidores existen y cómo se conectan. Envía el tipo, la ruta, los saltos, la intensidad de señal y el tamaño de cada paquete, además de los nombres y ubicaciones aproximadas de los repetidores a partir de sus propios adverts. Nunca envía el texto de los mensajes, quién habla con quién, nombres de canales, tus contactos ni tu posición exacta: las ubicaciones se redondean a unos 2 km y tu app recibe un ID aleatorio nuevo cada día.'; + + @override + String get networkMap_whatWeCollect => 'Qué recopilamos'; + + @override + String get networkMap_promptTitle => '¿Ayudar a construir el mapa de la red?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open puede compartir lo que escucha tu radio con el mapa público de la red en map.meshcoreopen.org, para que todos puedan ver qué repetidores existen y cómo se conectan.\n\nNunca envía el texto de los mensajes, quién habla con quién, nombres de canales, tus contactos ni tu posición exacta. Las ubicaciones se redondean a unos 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Puedes cambiarlo cuando quieras en Configuración → Configuración de la App → Mapa de la red.'; + + @override + String get networkMap_promptAccept => 'Compartir'; + + @override + String get networkMap_promptDecline => 'No, gracias'; + + @override + String get networkMap_statusOff => 'Desactivado. No se envía nada.'; + + @override + String get networkMap_statusWaiting => + 'Activado. Esperando conexión con la radio.'; + + @override + String get networkMap_statusNothingSent => + 'Activado. Aún no se ha enviado nada.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Último envío $time. $count paquetes hoy.'; + } + + @override + String get networkMap_sourceLocal => 'Local'; + + @override + String get networkMap_sourceOnline => 'En línea'; + + @override + String get networkMap_sourceBoth => 'Ambos'; + + @override + String get networkMap_zoomInHint => + 'Acerca el zoom para ver el mapa de la red en línea'; + + @override + String get networkMap_loadFailed => + 'No se pudo cargar el mapa de la red en línea'; + + @override + String get networkMap_inYourContacts => 'En tus contactos'; + + @override + String get networkMap_status => 'Estado'; + + @override + String get networkMap_statusActive => 'Activo en la última hora'; + + @override + String get networkMap_statusRecent => 'Escuchado en el último día'; + + @override + String get networkMap_statusStale => 'No escuchado recientemente'; + + @override + String get networkMap_confirmed => 'Confirmado'; + + @override + String get networkMap_singleSource => 'Fuente única, aún sin confirmar'; + + @override + String get networkMap_reports => 'Reportes'; + + @override + String get networkMap_locationEstimated => + 'Ubicación aproximada, estimada según quién lo escuchó'; + + @override + String get networkMap_locationAdvertised => + 'Ubicación aproximada, de su propio advert'; + + @override + String get networkMap_heardByRadio => 'Escuchado por tu radio'; + + @override + String get networkMap_inYourArea => 'En tu zona'; + + @override + String get networkMap_farAway => + 'Muy lejos. La administración no podrá alcanzarlo.'; + + @override + String get networkMap_addToContacts => 'Añadir a contactos'; + + @override + String get networkMap_manage => 'Administrar'; + + @override + String get networkMap_addedToContacts => 'Añadido a contactos'; + + @override + String get networkMap_addFailed => 'No se pudo añadir a contactos'; + + @override + String get networkMap_unnamed => 'Repetidor sin nombre'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 7a18939c..85de8bbb 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -361,6 +361,20 @@ class AppLocalizationsFr extends AppLocalizations { @override String get scanner_enableBluetooth => 'Activer le Bluetooth'; + @override + String get scanner_getNodeTitle => 'Besoin d\'un nouveau nœud ?'; + + @override + String get scanner_getNodeBody => + 'Format portefeuille, fonctionne avec MeshCore, GPS bi-bande, étanche, 5 jours d\'autonomie.'; + + @override + String get scanner_getNodeAction => 'Obtenez-le ici'; + + @override + String get scanner_getNodeDisclosure => + 'Lien d\'affiliation : chaque achat soutient MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'La fonctionnalité Bluetooth n\'est pas disponible dans le navigateur. Veuillez vous connecter via USB à la place.'; @@ -6208,4 +6222,125 @@ class AppLocalizationsFr extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours h $minutes min'; } + + @override + String get networkMap_settingsSection => 'Carte du réseau'; + + @override + String get networkMap_uploadTitle => 'Partager ce que ma radio entend'; + + @override + String get networkMap_uploadExplanation => + 'Lorsque cette option est activée et que votre radio est connectée, l\'application envoie un court résumé des paquets entendus par votre radio à la carte du réseau MeshCore Open, afin que chacun puisse voir quels répéteurs existent et comment ils sont reliés. Elle envoie le type, la route, les sauts, la puissance du signal et la taille de chaque paquet, ainsi que les noms et les positions approximatives des répéteurs issus de leurs propres adverts. Elle n\'envoie jamais le texte des messages, qui parle à qui, les noms des canaux, vos contacts ni votre position exacte : les positions sont arrondies à environ 2 km, et votre application reçoit chaque jour un nouvel identifiant aléatoire.'; + + @override + String get networkMap_whatWeCollect => 'Ce que nous collectons'; + + @override + String get networkMap_promptTitle => + 'Aider à construire la carte du réseau ?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open peut partager ce que votre radio entend avec la carte publique du réseau sur map.meshcoreopen.org, afin que chacun puisse voir quels répéteurs existent et comment ils sont reliés.\n\nElle n\'envoie jamais le texte des messages, qui parle à qui, les noms des canaux, vos contacts ni votre position exacte. Les positions sont arrondies à environ 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Vous pouvez modifier cela à tout moment dans Paramètres → Paramètres de l\'application → Carte du réseau.'; + + @override + String get networkMap_promptAccept => 'Partager'; + + @override + String get networkMap_promptDecline => 'Non merci'; + + @override + String get networkMap_statusOff => 'Désactivé. Rien n\'est envoyé.'; + + @override + String get networkMap_statusWaiting => + 'Activé. En attente d\'une connexion radio.'; + + @override + String get networkMap_statusNothingSent => + 'Activé. Rien n\'a encore été envoyé.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Dernier envoi $time. $count paquets aujourd\'hui.'; + } + + @override + String get networkMap_sourceLocal => 'Local'; + + @override + String get networkMap_sourceOnline => 'En ligne'; + + @override + String get networkMap_sourceBoth => 'Les deux'; + + @override + String get networkMap_zoomInHint => + 'Zoomez pour voir la carte du réseau en ligne'; + + @override + String get networkMap_loadFailed => + 'Impossible de charger la carte du réseau en ligne'; + + @override + String get networkMap_inYourContacts => 'Dans vos contacts'; + + @override + String get networkMap_status => 'Statut'; + + @override + String get networkMap_statusActive => 'Actif durant la dernière heure'; + + @override + String get networkMap_statusRecent => 'Entendu durant le dernier jour'; + + @override + String get networkMap_statusStale => 'Pas entendu récemment'; + + @override + String get networkMap_confirmed => 'Confirmé'; + + @override + String get networkMap_singleSource => 'Source unique, pas encore confirmé'; + + @override + String get networkMap_reports => 'Rapports'; + + @override + String get networkMap_locationEstimated => + 'Position approximative, estimée d\'après ceux qui l\'ont entendu'; + + @override + String get networkMap_locationAdvertised => + 'Position approximative, issue de son propre advert'; + + @override + String get networkMap_heardByRadio => 'Entendu par votre radio'; + + @override + String get networkMap_inYourArea => 'Dans votre zone'; + + @override + String get networkMap_farAway => + 'Trop loin. La gestion ne pourra pas l\'atteindre.'; + + @override + String get networkMap_addToContacts => 'Ajouter aux contacts'; + + @override + String get networkMap_manage => 'Gérer'; + + @override + String get networkMap_addedToContacts => 'Ajouté aux contacts'; + + @override + String get networkMap_addFailed => 'Impossible d\'ajouter aux contacts'; + + @override + String get networkMap_unnamed => 'Répéteur sans nom'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 5c7eb236..ef4b3d9b 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -357,6 +357,20 @@ class AppLocalizationsHu extends AppLocalizations { @override String get scanner_enableBluetooth => 'Bluetooth engedélyezése'; + @override + String get scanner_getNodeTitle => 'Új csomópontra van szükséged?'; + + @override + String get scanner_getNodeBody => + 'Pénztárca méretű, MeshCore-t futtat, kétsávos GPS, vízálló, 5 napos akkumulátor.'; + + @override + String get scanner_getNodeAction => 'Itt szerezhetsz egyet'; + + @override + String get scanner_getNodeDisclosure => + 'Partnerlink: minden vásárlás a MeshCore Opent támogatja.'; + @override String get scanner_bluetoothWebUnsupported => 'A Bluetooth nem érhető el a böngészőben. Inkább csatlakoztasson USB-n keresztül.'; @@ -6171,4 +6185,123 @@ class AppLocalizationsHu extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours ó $minutes p'; } + + @override + String get networkMap_settingsSection => 'Hálózati térkép'; + + @override + String get networkMap_uploadTitle => 'Megosztom, amit a rádióm hall'; + + @override + String get networkMap_uploadExplanation => + 'Ha ez be van kapcsolva és a rádió csatlakozik, az alkalmazás rövid összefoglalót küld a rádió által hallott csomagokról a MeshCore Open hálózati térképére, hogy mindenki lássa, milyen repeaterek léteznek és hogyan kapcsolódnak egymáshoz. Elküldi az egyes csomagok típusát, útvonalát, ugrásszámát, jelerősségét és méretét, valamint a repeaterek nevét és hozzávetőleges helyét a saját advertjeikből. Soha nem küld üzenetszöveget, azt, hogy ki kivel beszélget, csatornaneveket, a kapcsolataidat vagy a pontos helyzetedet: a helyek kb. 2 km-re kerekítettek, az alkalmazásod pedig naponta új véletlenszerű azonosítót kap.'; + + @override + String get networkMap_whatWeCollect => 'Mit gyűjtünk'; + + @override + String get networkMap_promptTitle => 'Segítesz a hálózati térkép építésében?'; + + @override + String get networkMap_promptBody => + 'A MeshCore Open megoszthatja, amit a rádiód hall, a nyilvános hálózati térképpel a map.meshcoreopen.org oldalon, hogy mindenki lássa, milyen repeaterek léteznek és hogyan kapcsolódnak egymáshoz.\n\nSoha nem küld üzenetszöveget, azt, hogy ki kivel beszélget, csatornaneveket, a kapcsolataidat vagy a pontos helyzetedet. A helyek kb. 2 km-re kerekítettek.'; + + @override + String get networkMap_promptSettingsHint => + 'Ezt bármikor módosíthatod: Beállítások → Alkalmazásbeállítások → Hálózati térkép.'; + + @override + String get networkMap_promptAccept => 'Megosztás'; + + @override + String get networkMap_promptDecline => 'Köszönöm, nem'; + + @override + String get networkMap_statusOff => 'Kikapcsolva. Semmi sem kerül elküldésre.'; + + @override + String get networkMap_statusWaiting => + 'Bekapcsolva. Várakozás a rádiókapcsolatra.'; + + @override + String get networkMap_statusNothingSent => + 'Bekapcsolva. Még nem ment el semmi.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Utoljára elküldve: $time. Ma $count csomag.'; + } + + @override + String get networkMap_sourceLocal => 'Helyi'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Mindkettő'; + + @override + String get networkMap_zoomInHint => + 'Nagyíts rá az online hálózati térkép megtekintéséhez'; + + @override + String get networkMap_loadFailed => + 'Nem sikerült betölteni az online hálózati térképet'; + + @override + String get networkMap_inYourContacts => 'A kapcsolataid között'; + + @override + String get networkMap_status => 'Állapot'; + + @override + String get networkMap_statusActive => 'Aktív az elmúlt órában'; + + @override + String get networkMap_statusRecent => 'Hallva az elmúlt napban'; + + @override + String get networkMap_statusStale => 'Mostanában nem hallható'; + + @override + String get networkMap_confirmed => 'Megerősítve'; + + @override + String get networkMap_singleSource => 'Egyetlen forrás, még nem megerősített'; + + @override + String get networkMap_reports => 'Jelentések'; + + @override + String get networkMap_locationEstimated => + 'Hozzávetőleges hely, a hallók alapján becsülve'; + + @override + String get networkMap_locationAdvertised => + 'Hozzávetőleges hely, a saját advertjéből'; + + @override + String get networkMap_heardByRadio => 'A rádiód hallja'; + + @override + String get networkMap_inYourArea => 'A közeledben'; + + @override + String get networkMap_farAway => 'Messze van. A kezelés nem éri el.'; + + @override + String get networkMap_addToContacts => 'Hozzáadás a kapcsolatokhoz'; + + @override + String get networkMap_manage => 'Kezelés'; + + @override + String get networkMap_addedToContacts => 'Hozzáadva a kapcsolatokhoz'; + + @override + String get networkMap_addFailed => 'Nem sikerült hozzáadni a kapcsolatokhoz'; + + @override + String get networkMap_unnamed => 'Névtelen repeater'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 17b87f24..50bb49d9 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -361,6 +361,20 @@ class AppLocalizationsIt extends AppLocalizations { @override String get scanner_enableBluetooth => 'Abilita il Bluetooth'; + @override + String get scanner_getNodeTitle => 'Ti serve un nuovo nodo?'; + + @override + String get scanner_getNodeBody => + 'Grande come un portafoglio, funziona con MeshCore, GPS dual-band, impermeabile, 5 giorni di batteria.'; + + @override + String get scanner_getNodeAction => 'Prendilo qui'; + + @override + String get scanner_getNodeDisclosure => + 'Link di affiliazione: ogni acquisto sostiene MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'La funzionalità Bluetooth non è disponibile nel browser. Connettetevi tramite USB invece.'; @@ -6190,4 +6204,124 @@ class AppLocalizationsIt extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours h $minutes min'; } + + @override + String get networkMap_settingsSection => 'Mappa della rete'; + + @override + String get networkMap_uploadTitle => 'Condividi ciò che sente la mia radio'; + + @override + String get networkMap_uploadExplanation => + 'Quando è attivo e la tua radio è connessa, l\'app invia un breve riepilogo dei pacchetti sentiti dalla tua radio alla mappa della rete di MeshCore Open, così tutti possono vedere quali ripetitori esistono e come sono collegati. Invia tipo, percorso, hop, intensità del segnale e dimensione di ogni pacchetto, oltre a nomi e posizioni approssimative dei ripetitori ricavati dai loro advert. Non invia mai il testo dei messaggi, chi parla con chi, i nomi dei canali, i tuoi contatti né la tua posizione esatta: le posizioni sono arrotondate a circa 2 km e la tua app riceve ogni giorno un nuovo ID casuale.'; + + @override + String get networkMap_whatWeCollect => 'Cosa raccogliamo'; + + @override + String get networkMap_promptTitle => + 'Vuoi aiutare a costruire la mappa della rete?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open può condividere ciò che sente la tua radio con la mappa pubblica della rete su map.meshcoreopen.org, così tutti possono vedere quali ripetitori esistono e come sono collegati.\n\nNon invia mai il testo dei messaggi, chi parla con chi, i nomi dei canali, i tuoi contatti né la tua posizione esatta. Le posizioni sono arrotondate a circa 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Puoi cambiarlo in qualsiasi momento in Impostazioni → Impostazioni App → Mappa della rete.'; + + @override + String get networkMap_promptAccept => 'Condividi'; + + @override + String get networkMap_promptDecline => 'No, grazie'; + + @override + String get networkMap_statusOff => 'Disattivato. Non viene inviato nulla.'; + + @override + String get networkMap_statusWaiting => + 'Attivo. In attesa della connessione con la radio.'; + + @override + String get networkMap_statusNothingSent => 'Attivo. Ancora nulla inviato.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Ultimo invio $time. $count pacchetti oggi.'; + } + + @override + String get networkMap_sourceLocal => 'Locale'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Entrambi'; + + @override + String get networkMap_zoomInHint => + 'Ingrandisci per vedere la mappa della rete online'; + + @override + String get networkMap_loadFailed => + 'Impossibile caricare la mappa della rete online'; + + @override + String get networkMap_inYourContacts => 'Nei tuoi contatti'; + + @override + String get networkMap_status => 'Stato'; + + @override + String get networkMap_statusActive => 'Attivo nell\'ultima ora'; + + @override + String get networkMap_statusRecent => 'Sentito nell\'ultimo giorno'; + + @override + String get networkMap_statusStale => 'Non sentito di recente'; + + @override + String get networkMap_confirmed => 'Confermato'; + + @override + String get networkMap_singleSource => 'Fonte singola, non ancora confermato'; + + @override + String get networkMap_reports => 'Segnalazioni'; + + @override + String get networkMap_locationEstimated => + 'Posizione approssimativa, stimata in base a chi l\'ha sentito'; + + @override + String get networkMap_locationAdvertised => + 'Posizione approssimativa, dal suo advert'; + + @override + String get networkMap_heardByRadio => 'Sentito dalla tua radio'; + + @override + String get networkMap_inYourArea => 'Nella tua zona'; + + @override + String get networkMap_farAway => + 'Troppo lontano. La gestione non lo raggiungerà.'; + + @override + String get networkMap_addToContacts => 'Aggiungi ai contatti'; + + @override + String get networkMap_manage => 'Gestisci'; + + @override + String get networkMap_addedToContacts => 'Aggiunto ai contatti'; + + @override + String get networkMap_addFailed => 'Impossibile aggiungere ai contatti'; + + @override + String get networkMap_unnamed => 'Ripetitore senza nome'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 7f59a6f5..2aabf56e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -344,6 +344,20 @@ class AppLocalizationsJa extends AppLocalizations { @override String get scanner_enableBluetooth => 'Bluetooth を有効にする'; + @override + String get scanner_getNodeTitle => '新しいノードが必要ですか?'; + + @override + String get scanner_getNodeBody => + '財布サイズで MeshCore が動作。デュアルバンドGPS、防水、バッテリー5日間。'; + + @override + String get scanner_getNodeAction => 'こちらで入手'; + + @override + String get scanner_getNodeDisclosure => + 'アフィリエイトリンク: 購入のたびに MeshCore Open を応援できます。'; + @override String get scanner_bluetoothWebUnsupported => 'ブラウザでは Bluetooth は利用できません。代わりに USB で接続してください。'; @@ -5892,4 +5906,117 @@ class AppLocalizationsJa extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours時間$minutes分'; } + + @override + String get networkMap_settingsSection => 'ネットワークマップ'; + + @override + String get networkMap_uploadTitle => 'ラジオが受信した情報を共有'; + + @override + String get networkMap_uploadExplanation => + 'オンにしてラジオが接続されている間、ラジオが受信したパケットの概要をアプリが MeshCore Open のネットワークマップに送信します。これにより、どんなリピータがあり、どうつながっているかを誰でも見られます。送信するのは、各パケットの種類、経路、ホップ数、信号強度、サイズと、リピータ自身のアドバートに含まれる名前とおおよその位置です。メッセージの本文、誰が誰と話しているか、チャンネル名、連絡先、正確な位置は送信しません。位置は約2km単位に丸められ、アプリのIDは毎日ランダムに新しくなります。'; + + @override + String get networkMap_whatWeCollect => '収集する情報'; + + @override + String get networkMap_promptTitle => 'ネットワークマップの作成にご協力いただけますか?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open は、ラジオが受信した情報を map.meshcoreopen.org の公開ネットワークマップと共有できます。これにより、どんなリピータがあり、どうつながっているかを誰でも見られます。\n\nメッセージの本文、誰が誰と話しているか、チャンネル名、連絡先、正確な位置は送信しません。位置は約2km単位に丸められます。'; + + @override + String get networkMap_promptSettingsHint => + 'この設定はいつでも「設定」→「アプリ設定」→「ネットワークマップ」で変更できます。'; + + @override + String get networkMap_promptAccept => '共有する'; + + @override + String get networkMap_promptDecline => 'いいえ、結構です'; + + @override + String get networkMap_statusOff => 'オフ。何も送信されません。'; + + @override + String get networkMap_statusWaiting => 'オン。ラジオの接続を待っています。'; + + @override + String get networkMap_statusNothingSent => 'オン。まだ何も送信されていません。'; + + @override + String networkMap_statusLastSent(String time, int count) { + return '最終送信: $time。今日は$countパケット。'; + } + + @override + String get networkMap_sourceLocal => 'ローカル'; + + @override + String get networkMap_sourceOnline => 'オンライン'; + + @override + String get networkMap_sourceBoth => '両方'; + + @override + String get networkMap_zoomInHint => 'ズームインするとオンラインのネットワークマップが表示されます'; + + @override + String get networkMap_loadFailed => 'オンラインのネットワークマップを読み込めませんでした'; + + @override + String get networkMap_inYourContacts => '連絡先にあります'; + + @override + String get networkMap_status => 'ステータス'; + + @override + String get networkMap_statusActive => '直近1時間にアクティブ'; + + @override + String get networkMap_statusRecent => '直近1日以内に受信'; + + @override + String get networkMap_statusStale => '最近受信されていません'; + + @override + String get networkMap_confirmed => '確認済み'; + + @override + String get networkMap_singleSource => '情報源が1つのみで、未確認'; + + @override + String get networkMap_reports => 'レポート'; + + @override + String get networkMap_locationEstimated => 'おおよその位置(受信したノードから推定)'; + + @override + String get networkMap_locationAdvertised => 'おおよその位置(自身のアドバートより)'; + + @override + String get networkMap_heardByRadio => 'ラジオが受信'; + + @override + String get networkMap_inYourArea => 'お近く'; + + @override + String get networkMap_farAway => '遠すぎます。管理はできません。'; + + @override + String get networkMap_addToContacts => '連絡先に追加'; + + @override + String get networkMap_manage => '管理'; + + @override + String get networkMap_addedToContacts => '連絡先に追加しました'; + + @override + String get networkMap_addFailed => '連絡先に追加できませんでした'; + + @override + String get networkMap_unnamed => '名前のないリピータ'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 658abee7..98a81ac1 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -344,6 +344,20 @@ class AppLocalizationsKo extends AppLocalizations { @override String get scanner_enableBluetooth => '블루투스 켜기'; + @override + String get scanner_getNodeTitle => '새 노드가 필요하신가요?'; + + @override + String get scanner_getNodeBody => + '지갑 크기에 MeshCore 구동, 듀얼 밴드 GPS, 방수, 5일 배터리.'; + + @override + String get scanner_getNodeAction => '여기서 구하기'; + + @override + String get scanner_getNodeDisclosure => + '제휴 링크: 구매할 때마다 MeshCore Open을 후원하게 됩니다.'; + @override String get scanner_bluetoothWebUnsupported => '브라우저에서는 블루투스를 사용할 수 없습니다. 대신 USB로 연결하세요.'; @@ -5902,4 +5916,117 @@ class AppLocalizationsKo extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours시간 $minutes분'; } + + @override + String get networkMap_settingsSection => '네트워크 지도'; + + @override + String get networkMap_uploadTitle => '내 라디오가 수신한 정보 공유'; + + @override + String get networkMap_uploadExplanation => + '이 기능을 켜고 라디오가 연결되어 있으면, 앱이 라디오가 수신한 패킷의 요약 정보를 MeshCore Open 네트워크 지도로 보내 어떤 리피터가 있고 서로 어떻게 연결되는지 모두가 볼 수 있게 합니다. 각 패킷의 종류, 경로, 홉 수, 신호 세기, 크기와 함께 리피터 자체 어드버트에 담긴 이름과 대략적인 위치를 보냅니다. 메시지 내용, 누가 누구와 대화하는지, 채널 이름, 연락처, 정확한 위치는 절대 보내지 않습니다. 위치는 약 2km 단위로 반올림되며, 앱 ID는 매일 새로운 무작위 값으로 바뀝니다.'; + + @override + String get networkMap_whatWeCollect => '수집하는 정보'; + + @override + String get networkMap_promptTitle => '네트워크 지도 만들기에 참여하시겠어요?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open은 라디오가 수신한 정보를 map.meshcoreopen.org의 공개 네트워크 지도와 공유하여, 어떤 리피터가 있고 서로 어떻게 연결되는지 모두가 볼 수 있게 할 수 있습니다.\n\n메시지 내용, 누가 누구와 대화하는지, 채널 이름, 연락처, 정확한 위치는 절대 보내지 않습니다. 위치는 약 2km 단위로 반올림됩니다.'; + + @override + String get networkMap_promptSettingsHint => + '설정 → 앱 설정 → 네트워크 지도에서 언제든지 변경할 수 있습니다.'; + + @override + String get networkMap_promptAccept => '공유'; + + @override + String get networkMap_promptDecline => '괜찮아요'; + + @override + String get networkMap_statusOff => '꺼짐. 아무것도 전송되지 않습니다.'; + + @override + String get networkMap_statusWaiting => '켜짐. 라디오 연결을 기다리는 중입니다.'; + + @override + String get networkMap_statusNothingSent => '켜짐. 아직 전송한 내용이 없습니다.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return '마지막 전송 $time. 오늘 패킷 $count개.'; + } + + @override + String get networkMap_sourceLocal => '로컬'; + + @override + String get networkMap_sourceOnline => '온라인'; + + @override + String get networkMap_sourceBoth => '모두'; + + @override + String get networkMap_zoomInHint => '온라인 네트워크 지도를 보려면 확대하세요'; + + @override + String get networkMap_loadFailed => '온라인 네트워크 지도를 불러오지 못했습니다'; + + @override + String get networkMap_inYourContacts => '내 연락처에 있음'; + + @override + String get networkMap_status => '상태'; + + @override + String get networkMap_statusActive => '최근 1시간 이내 활동'; + + @override + String get networkMap_statusRecent => '최근 하루 이내 수신'; + + @override + String get networkMap_statusStale => '최근 수신 없음'; + + @override + String get networkMap_confirmed => '확인됨'; + + @override + String get networkMap_singleSource => '단일 출처, 아직 확인되지 않음'; + + @override + String get networkMap_reports => '보고'; + + @override + String get networkMap_locationEstimated => '대략적인 위치, 수신한 노드를 기준으로 추정'; + + @override + String get networkMap_locationAdvertised => '대략적인 위치, 자체 어드버트 기준'; + + @override + String get networkMap_heardByRadio => '내 라디오가 수신함'; + + @override + String get networkMap_inYourArea => '내 주변 지역'; + + @override + String get networkMap_farAway => '멀리 떨어져 있어 관리할 수 없습니다.'; + + @override + String get networkMap_addToContacts => '연락처에 추가'; + + @override + String get networkMap_manage => '관리'; + + @override + String get networkMap_addedToContacts => '연락처에 추가됨'; + + @override + String get networkMap_addFailed => '연락처에 추가하지 못했습니다'; + + @override + String get networkMap_unnamed => '이름 없는 리피터'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 47bf573c..082f2a18 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -357,6 +357,20 @@ class AppLocalizationsNl extends AppLocalizations { @override String get scanner_enableBluetooth => 'Activeer Bluetooth'; + @override + String get scanner_getNodeTitle => 'Een nieuwe node nodig?'; + + @override + String get scanner_getNodeBody => + 'Zo klein als een portemonnee, draait MeshCore, dual-band GPS, waterdicht, 5 dagen accuduur.'; + + @override + String get scanner_getNodeAction => 'Haal er hier een'; + + @override + String get scanner_getNodeDisclosure => + 'Affiliatelink: elke aankoop steunt MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth is niet beschikbaar in de browser. Verbind in plaats daarvan via USB.'; @@ -6150,4 +6164,120 @@ class AppLocalizationsNl extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '${hours}u ${minutes}m'; } + + @override + String get networkMap_settingsSection => 'Netwerkkaart'; + + @override + String get networkMap_uploadTitle => 'Delen wat mijn radio hoort'; + + @override + String get networkMap_uploadExplanation => + 'Als dit aan staat en je radio verbonden is, stuurt de app een korte samenvatting van de pakketten die je radio hoort naar de MeshCore Open-netwerkkaart, zodat iedereen kan zien welke repeaters er zijn en hoe ze met elkaar verbonden zijn. Per pakket wordt het type, de route, het aantal hops, de signaalsterkte en de grootte verstuurd, plus repeaternamen en globale locaties uit hun eigen adverts. Er worden nooit berichttekst, wie met wie praat, kanaalnamen, je contacten of je exacte positie verstuurd: locaties worden afgerond op ongeveer 2 km en je app krijgt elke dag een nieuw willekeurig ID.'; + + @override + String get networkMap_whatWeCollect => 'Wat we verzamelen'; + + @override + String get networkMap_promptTitle => 'Helpen de netwerkkaart te bouwen?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open kan delen wat je radio hoort met de openbare netwerkkaart op map.meshcoreopen.org, zodat iedereen kan zien welke repeaters er zijn en hoe ze met elkaar verbonden zijn.\n\nEr worden nooit berichttekst, wie met wie praat, kanaalnamen, je contacten of je exacte positie verstuurd. Locaties worden afgerond op ongeveer 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Je kunt dit op elk moment wijzigen via Instellingen → App Instellingen → Netwerkkaart.'; + + @override + String get networkMap_promptAccept => 'Delen'; + + @override + String get networkMap_promptDecline => 'Nee, bedankt'; + + @override + String get networkMap_statusOff => 'Uit. Er wordt niets verstuurd.'; + + @override + String get networkMap_statusWaiting => 'Aan. Wachten op een radioverbinding.'; + + @override + String get networkMap_statusNothingSent => 'Aan. Nog niets verstuurd.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Laatst verstuurd $time. $count pakketten vandaag.'; + } + + @override + String get networkMap_sourceLocal => 'Lokaal'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Beide'; + + @override + String get networkMap_zoomInHint => + 'Zoom in om de online netwerkkaart te zien'; + + @override + String get networkMap_loadFailed => 'Kan de online netwerkkaart niet laden'; + + @override + String get networkMap_inYourContacts => 'In je contacten'; + + @override + String get networkMap_status => 'Status'; + + @override + String get networkMap_statusActive => 'Actief in het laatste uur'; + + @override + String get networkMap_statusRecent => 'Gehoord in de afgelopen dag'; + + @override + String get networkMap_statusStale => 'Onlangs niet gehoord'; + + @override + String get networkMap_confirmed => 'Bevestigd'; + + @override + String get networkMap_singleSource => 'Eén bron, nog niet bevestigd'; + + @override + String get networkMap_reports => 'Meldingen'; + + @override + String get networkMap_locationEstimated => + 'Globale locatie, geschat op basis van wie het hoorde'; + + @override + String get networkMap_locationAdvertised => + 'Globale locatie, uit zijn eigen advert'; + + @override + String get networkMap_heardByRadio => 'Gehoord door je radio'; + + @override + String get networkMap_inYourArea => 'In jouw omgeving'; + + @override + String get networkMap_farAway => 'Ver weg. Beheer bereikt het niet.'; + + @override + String get networkMap_addToContacts => 'Toevoegen aan contacten'; + + @override + String get networkMap_manage => 'Beheren'; + + @override + String get networkMap_addedToContacts => 'Toegevoegd aan contacten'; + + @override + String get networkMap_addFailed => 'Kan niet aan contacten toevoegen'; + + @override + String get networkMap_unnamed => 'Naamloze repeater'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 452ea7d1..3db02722 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -364,6 +364,20 @@ class AppLocalizationsPl extends AppLocalizations { @override String get scanner_enableBluetooth => 'Włącz Bluetooth'; + @override + String get scanner_getNodeTitle => 'Potrzebujesz nowego węzła?'; + + @override + String get scanner_getNodeBody => + 'Wielkości portfela, z MeshCore, dwuzakresowy GPS, wodoodporny, bateria na 5 dni.'; + + @override + String get scanner_getNodeAction => 'Kup tutaj'; + + @override + String get scanner_getNodeDisclosure => + 'Link partnerski: każdy zakup wspiera MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth nie jest dostępny w przeglądarce. Połącz się przez USB.'; @@ -6214,4 +6228,122 @@ class AppLocalizationsPl extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours godz. $minutes min'; } + + @override + String get networkMap_settingsSection => 'Mapa sieci'; + + @override + String get networkMap_uploadTitle => 'Udostępniaj to, co słyszy moje radio'; + + @override + String get networkMap_uploadExplanation => + 'Gdy ta opcja jest włączona, a radio połączone, aplikacja wysyła krótkie podsumowanie pakietów słyszanych przez radio do mapy sieci MeshCore Open, aby każdy mógł zobaczyć, jakie repeatery istnieją i jak się łączą. Wysyłany jest typ, trasa, liczba skoków, siła sygnału i rozmiar każdego pakietu oraz nazwy repeaterów i przybliżone lokalizacje z ich własnych rozgłoszeń. Nigdy nie wysyła treści wiadomości, informacji o tym, kto z kim rozmawia, nazw kanałów, Twoich kontaktów ani Twojej dokładnej pozycji: lokalizacje są zaokrąglane do około 2 km, a aplikacja co dzień dostaje nowy losowy identyfikator.'; + + @override + String get networkMap_whatWeCollect => 'Co zbieramy'; + + @override + String get networkMap_promptTitle => 'Pomóc w budowie mapy sieci?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open może udostępniać to, co słyszy Twoje radio, publicznej mapie sieci na map.meshcoreopen.org, aby każdy mógł zobaczyć, jakie repeatery istnieją i jak się łączą.\n\nNigdy nie wysyła treści wiadomości, informacji o tym, kto z kim rozmawia, nazw kanałów, Twoich kontaktów ani Twojej dokładnej pozycji. Lokalizacje są zaokrąglane do około 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Możesz to zmienić w dowolnym momencie w Ustawienia → Ustawienia aplikacji → Mapa sieci.'; + + @override + String get networkMap_promptAccept => 'Udostępnij'; + + @override + String get networkMap_promptDecline => 'Nie, dziękuję'; + + @override + String get networkMap_statusOff => 'Wyłączone. Nic nie jest wysyłane.'; + + @override + String get networkMap_statusWaiting => + 'Włączone. Oczekiwanie na połączenie z radiem.'; + + @override + String get networkMap_statusNothingSent => + 'Włączone. Nic jeszcze nie wysłano.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Ostatnio wysłano $time. Pakiety dzisiaj: $count.'; + } + + @override + String get networkMap_sourceLocal => 'Lokalna'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Obie'; + + @override + String get networkMap_zoomInHint => + 'Przybliż, aby zobaczyć mapę sieci online'; + + @override + String get networkMap_loadFailed => 'Nie udało się wczytać mapy sieci online'; + + @override + String get networkMap_inYourContacts => 'W Twoich kontaktach'; + + @override + String get networkMap_status => 'Stan'; + + @override + String get networkMap_statusActive => 'Aktywny w ostatniej godzinie'; + + @override + String get networkMap_statusRecent => 'Słyszany w ostatniej dobie'; + + @override + String get networkMap_statusStale => 'Dawno niesłyszany'; + + @override + String get networkMap_confirmed => 'Potwierdzony'; + + @override + String get networkMap_singleSource => 'Jedno źródło, jeszcze niepotwierdzone'; + + @override + String get networkMap_reports => 'Raporty'; + + @override + String get networkMap_locationEstimated => + 'Przybliżona lokalizacja, oszacowana na podstawie tego, kto go słyszał'; + + @override + String get networkMap_locationAdvertised => + 'Przybliżona lokalizacja, z jego własnego rozgłoszenia'; + + @override + String get networkMap_heardByRadio => 'Słyszany przez Twoje radio'; + + @override + String get networkMap_inYourArea => 'W Twojej okolicy'; + + @override + String get networkMap_farAway => 'Daleko. Zarządzanie tam nie dotrze.'; + + @override + String get networkMap_addToContacts => 'Dodaj do kontaktów'; + + @override + String get networkMap_manage => 'Zarządzaj'; + + @override + String get networkMap_addedToContacts => 'Dodano do kontaktów'; + + @override + String get networkMap_addFailed => 'Nie udało się dodać do kontaktów'; + + @override + String get networkMap_unnamed => 'Repeater bez nazwy'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 3f234aa4..9b89ff31 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -360,6 +360,20 @@ class AppLocalizationsPt extends AppLocalizations { @override String get scanner_enableBluetooth => 'Ative o Bluetooth'; + @override + String get scanner_getNodeTitle => 'Precisa de um novo nó?'; + + @override + String get scanner_getNodeBody => + 'Do tamanho de uma carteira, roda MeshCore, GPS dual-band, à prova d\'água, bateria para 5 dias.'; + + @override + String get scanner_getNodeAction => 'Compre aqui'; + + @override + String get scanner_getNodeDisclosure => + 'Link de afiliado: cada compra apoia o MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'A funcionalidade Bluetooth não está disponível no navegador. Conecte-se via USB em vez disso.'; @@ -6179,4 +6193,122 @@ class AppLocalizationsPt extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '${hours}h ${minutes}m'; } + + @override + String get networkMap_settingsSection => 'Mapa da rede'; + + @override + String get networkMap_uploadTitle => 'Compartilhar o que meu rádio ouve'; + + @override + String get networkMap_uploadExplanation => + 'Quando isto está ativado e o seu rádio está conectado, o app envia um breve resumo dos pacotes que o seu rádio ouve para o mapa da rede do MeshCore Open, para que todos possam ver quais repetidores existem e como se conectam. Ele envia o tipo, a rota, os saltos, a intensidade do sinal e o tamanho de cada pacote, além dos nomes e localizações aproximadas dos repetidores, obtidos dos próprios anúncios. Nunca envia o texto das mensagens, quem fala com quem, nomes de canais, seus contactos nem a sua posição exata: as localizações são arredondadas para cerca de 2 km, e o seu app recebe um novo ID aleatório todos os dias.'; + + @override + String get networkMap_whatWeCollect => 'O que coletamos'; + + @override + String get networkMap_promptTitle => 'Ajudar a construir o mapa da rede?'; + + @override + String get networkMap_promptBody => + 'O MeshCore Open pode compartilhar o que o seu rádio ouve com o mapa público da rede em map.meshcoreopen.org, para que todos possam ver quais repetidores existem e como se conectam.\n\nNunca envia o texto das mensagens, quem fala com quem, nomes de canais, seus contactos nem a sua posição exata. As localizações são arredondadas para cerca de 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Você pode mudar isso a qualquer momento em Configurações → Configurações do App → Mapa da rede.'; + + @override + String get networkMap_promptAccept => 'Compartilhar'; + + @override + String get networkMap_promptDecline => 'Não, obrigado'; + + @override + String get networkMap_statusOff => 'Desativado. Nada é enviado.'; + + @override + String get networkMap_statusWaiting => + 'Ativado. Aguardando conexão com o rádio.'; + + @override + String get networkMap_statusNothingSent => 'Ativado. Nada enviado ainda.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Último envio $time. $count pacotes hoje.'; + } + + @override + String get networkMap_sourceLocal => 'Local'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Ambos'; + + @override + String get networkMap_zoomInHint => + 'Aproxime o zoom para ver o mapa da rede online'; + + @override + String get networkMap_loadFailed => + 'Não foi possível carregar o mapa da rede online'; + + @override + String get networkMap_inYourContacts => 'Nos seus contactos'; + + @override + String get networkMap_status => 'Estado'; + + @override + String get networkMap_statusActive => 'Ativo na última hora'; + + @override + String get networkMap_statusRecent => 'Ouvido no último dia'; + + @override + String get networkMap_statusStale => 'Não ouvido recentemente'; + + @override + String get networkMap_confirmed => 'Confirmado'; + + @override + String get networkMap_singleSource => 'Fonte única, ainda não confirmado'; + + @override + String get networkMap_reports => 'Relatórios'; + + @override + String get networkMap_locationEstimated => + 'Localização aproximada, estimada a partir de quem o ouviu'; + + @override + String get networkMap_locationAdvertised => + 'Localização aproximada, do próprio anúncio'; + + @override + String get networkMap_heardByRadio => 'Ouvido pelo seu rádio'; + + @override + String get networkMap_inYourArea => 'Na sua área'; + + @override + String get networkMap_farAway => 'Muito longe. A gestão não chegará até ele.'; + + @override + String get networkMap_addToContacts => 'Adicionar aos contactos'; + + @override + String get networkMap_manage => 'Gerenciar'; + + @override + String get networkMap_addedToContacts => 'Adicionado aos contactos'; + + @override + String get networkMap_addFailed => 'Não foi possível adicionar aos contactos'; + + @override + String get networkMap_unnamed => 'Repetidor sem nome'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 018549ec..a1686804 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -360,6 +360,20 @@ class AppLocalizationsRu extends AppLocalizations { @override String get scanner_enableBluetooth => 'Включите Bluetooth'; + @override + String get scanner_getNodeTitle => 'Нужна новая нода?'; + + @override + String get scanner_getNodeBody => + 'Размером с кошелёк, работает на MeshCore, двухдиапазонный GPS, водонепроницаемая, батареи хватает на 5 дней.'; + + @override + String get scanner_getNodeAction => 'Купить здесь'; + + @override + String get scanner_getNodeDisclosure => + 'Партнёрская ссылка: каждая покупка поддерживает MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth недоступен в браузере. Подключитесь через USB.'; @@ -6200,4 +6214,123 @@ class AppLocalizationsRu extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hoursч $minutesм'; } + + @override + String get networkMap_settingsSection => 'Карта сети'; + + @override + String get networkMap_uploadTitle => + 'Делиться тем, что слышит мой радиомодуль'; + + @override + String get networkMap_uploadExplanation => + 'Когда это включено и радиомодуль подключён, приложение отправляет на карту сети MeshCore Open краткую сводку о пакетах, которые слышит ваш радиомодуль, чтобы все могли видеть, какие репитеры существуют и как они связаны. Отправляются тип, маршрут, число хопов, уровень сигнала и размер каждого пакета, а также названия репитеров и их примерное местоположение из их собственных анонсов. Никогда не отправляются текст сообщений, кто с кем общается, названия каналов, ваши контакты и ваше точное местоположение: координаты округляются примерно до 2 км, а приложение каждый день получает новый случайный ID.'; + + @override + String get networkMap_whatWeCollect => 'Что мы собираем'; + + @override + String get networkMap_promptTitle => 'Помочь построить карту сети?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open может делиться тем, что слышит ваш радиомодуль, с публичной картой сети на map.meshcoreopen.org, чтобы все могли видеть, какие репитеры существуют и как они связаны.\n\nНикогда не отправляются текст сообщений, кто с кем общается, названия каналов, ваши контакты и ваше точное местоположение. Координаты округляются примерно до 2 км.'; + + @override + String get networkMap_promptSettingsHint => + 'Это можно изменить в любой момент: Настройки → Настройки приложения → Карта сети.'; + + @override + String get networkMap_promptAccept => 'Делиться'; + + @override + String get networkMap_promptDecline => 'Нет, спасибо'; + + @override + String get networkMap_statusOff => 'Выключено. Ничего не отправляется.'; + + @override + String get networkMap_statusWaiting => + 'Включено. Ожидание подключения радиомодуля.'; + + @override + String get networkMap_statusNothingSent => + 'Включено. Пока ничего не отправлено.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Последняя отправка: $time. Пакетов сегодня: $count.'; + } + + @override + String get networkMap_sourceLocal => 'Локальная'; + + @override + String get networkMap_sourceOnline => 'Онлайн'; + + @override + String get networkMap_sourceBoth => 'Обе'; + + @override + String get networkMap_zoomInHint => + 'Приблизьте, чтобы увидеть онлайн-карту сети'; + + @override + String get networkMap_loadFailed => 'Не удалось загрузить онлайн-карту сети'; + + @override + String get networkMap_inYourContacts => 'В ваших контактах'; + + @override + String get networkMap_status => 'Статус'; + + @override + String get networkMap_statusActive => 'Активен за последний час'; + + @override + String get networkMap_statusRecent => 'Слышен за последние сутки'; + + @override + String get networkMap_statusStale => 'Давно не слышен'; + + @override + String get networkMap_confirmed => 'Подтверждён'; + + @override + String get networkMap_singleSource => 'Один источник, пока не подтверждён'; + + @override + String get networkMap_reports => 'Отчёты'; + + @override + String get networkMap_locationEstimated => + 'Примерное местоположение, оценено по тем, кто его слышал'; + + @override + String get networkMap_locationAdvertised => + 'Примерное местоположение, из собственного анонса'; + + @override + String get networkMap_heardByRadio => 'Слышен вашим радиомодулем'; + + @override + String get networkMap_inYourArea => 'В вашем районе'; + + @override + String get networkMap_farAway => 'Далеко. Управление недоступно.'; + + @override + String get networkMap_addToContacts => 'Добавить в контакты'; + + @override + String get networkMap_manage => 'Управлять'; + + @override + String get networkMap_addedToContacts => 'Добавлено в контакты'; + + @override + String get networkMap_addFailed => 'Не удалось добавить в контакты'; + + @override + String get networkMap_unnamed => 'Репитер без имени'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 78a12f67..9cd7cc6d 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -360,6 +360,20 @@ class AppLocalizationsSk extends AppLocalizations { @override String get scanner_enableBluetooth => 'Povolte Bluetooth'; + @override + String get scanner_getNodeTitle => 'Potrebujete nový uzol?'; + + @override + String get scanner_getNodeBody => + 'Veľkosti peňaženky, beží na MeshCore, dvojpásmové GPS, vodotesný, batéria vydrží 5 dní.'; + + @override + String get scanner_getNodeAction => 'Kúpte si ho tu'; + + @override + String get scanner_getNodeDisclosure => + 'Partnerský odkaz: každý nákup podporuje MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Funkcia Bluetooth nie je dostupná v prehliadači. Prepojte sa pomocou USB.'; @@ -6162,4 +6176,122 @@ class AppLocalizationsSk extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '${hours}h ${minutes}m'; } + + @override + String get networkMap_settingsSection => 'Sieťová mapa'; + + @override + String get networkMap_uploadTitle => 'Zdieľať, čo počuje moje rádio'; + + @override + String get networkMap_uploadExplanation => + 'Keď je to zapnuté a rádio je pripojené, aplikácia odosiela na sieťovú mapu MeshCore Open stručný súhrn paketov, ktoré vaše rádio počuje, aby každý videl, aké opakovače existujú a ako sú prepojené. Odosiela typ, trasu, počet skokov, silu signálu a veľkosť každého paketu, ako aj názvy opakovačov a ich približnú polohu z ich vlastných inzerátov. Nikdy neodosiela text správ, kto s kým komunikuje, názvy kanálov, vaše kontakty ani vašu presnú polohu: polohy sa zaokrúhľujú na približne 2 km a aplikácia dostáva nové náhodné ID každý deň.'; + + @override + String get networkMap_whatWeCollect => 'Čo zbierame'; + + @override + String get networkMap_promptTitle => 'Pomôcť budovať sieťovú mapu?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open môže zdieľať, čo vaše rádio počuje, s verejnou sieťovou mapou na map.meshcoreopen.org, aby každý videl, aké opakovače existujú a ako sú prepojené.\n\nNikdy neodosiela text správ, kto s kým komunikuje, názvy kanálov, vaše kontakty ani vašu presnú polohu. Polohy sa zaokrúhľujú na približne 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Môžete to kedykoľvek zmeniť v Nastavenia → Nastavenia aplikácie → Sieťová mapa.'; + + @override + String get networkMap_promptAccept => 'Zdieľať'; + + @override + String get networkMap_promptDecline => 'Nie, ďakujem'; + + @override + String get networkMap_statusOff => 'Vypnuté. Nič sa neodosiela.'; + + @override + String get networkMap_statusWaiting => + 'Zapnuté. Čaká sa na pripojenie rádia.'; + + @override + String get networkMap_statusNothingSent => 'Zapnuté. Zatiaľ nič neodoslané.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Naposledy odoslané $time. Dnes paketov: $count.'; + } + + @override + String get networkMap_sourceLocal => 'Lokálna'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Obe'; + + @override + String get networkMap_zoomInHint => + 'Priblížte, aby ste videli online sieťovú mapu'; + + @override + String get networkMap_loadFailed => + 'Online sieťovú mapu sa nepodarilo načítať'; + + @override + String get networkMap_inYourContacts => 'Vo vašich kontaktoch'; + + @override + String get networkMap_status => 'Stav'; + + @override + String get networkMap_statusActive => 'Aktívny za poslednú hodinu'; + + @override + String get networkMap_statusRecent => 'Počuť za posledný deň'; + + @override + String get networkMap_statusStale => 'Dlho nepočuť'; + + @override + String get networkMap_confirmed => 'Potvrdený'; + + @override + String get networkMap_singleSource => 'Jeden zdroj, zatiaľ nepotvrdený'; + + @override + String get networkMap_reports => 'Hlásenia'; + + @override + String get networkMap_locationEstimated => + 'Približná poloha, odhadnutá podľa toho, kto ho počul'; + + @override + String get networkMap_locationAdvertised => + 'Približná poloha, z vlastného inzerátu'; + + @override + String get networkMap_heardByRadio => 'Počuté vaším rádiom'; + + @override + String get networkMap_inYourArea => 'Vo vašej oblasti'; + + @override + String get networkMap_farAway => 'Ďaleko. Správa ho nedosiahne.'; + + @override + String get networkMap_addToContacts => 'Pridať do kontaktov'; + + @override + String get networkMap_manage => 'Spravovať'; + + @override + String get networkMap_addedToContacts => 'Pridané do kontaktov'; + + @override + String get networkMap_addFailed => 'Nepodarilo sa pridať do kontaktov'; + + @override + String get networkMap_unnamed => 'Nepomenovaný opakovač'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 88583058..8602eb0d 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -359,6 +359,20 @@ class AppLocalizationsSl extends AppLocalizations { @override String get scanner_enableBluetooth => 'Omogočite Bluetooth'; + @override + String get scanner_getNodeTitle => 'Potrebujete nov node?'; + + @override + String get scanner_getNodeBody => + 'Velikosti denarnice, poganja MeshCore, dvopasovni GPS, vodoodporen, baterija za 5 dni.'; + + @override + String get scanner_getNodeAction => 'Oglejte si ga tukaj'; + + @override + String get scanner_getNodeDisclosure => + 'Partnerska povezava: vsak nakup podpira MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Funkcija Bluetooth v brskalniku ni na voljo. Povežite se preko USB-ja namesto tega.'; @@ -6164,4 +6178,122 @@ class AppLocalizationsSl extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours h $minutes min'; } + + @override + String get networkMap_settingsSection => 'Omrežni zemljevid'; + + @override + String get networkMap_uploadTitle => 'Deli, kaj sliši moj radio'; + + @override + String get networkMap_uploadExplanation => + 'Ko je to vklopljeno in je radio povezan, aplikacija na omrežni zemljevid MeshCore Open pošlje kratek povzetek paketov, ki jih sliši vaš radio, tako da vsi vidijo, kateri repeaterji obstajajo in kako so povezani. Pošlje vrsto, pot, število skokov, moč signala in velikost vsakega paketa ter imena in približne lokacije repeaterjev iz njihovih lastnih advertov. Nikoli ne pošlje besedila sporočil, kdo se s kom pogovarja, imen kanalov, vaših stikov ali vašega natančnega položaja: lokacije so zaokrožene na približno 2 km, aplikacija pa vsak dan dobi nov naključni ID.'; + + @override + String get networkMap_whatWeCollect => 'Kaj zbiramo'; + + @override + String get networkMap_promptTitle => 'Pomagate graditi omrežni zemljevid?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open lahko deli, kaj sliši vaš radio, z javnim omrežnim zemljevidom na map.meshcoreopen.org, tako da vsi vidijo, kateri repeaterji obstajajo in kako so povezani.\n\nNikoli ne pošlje besedila sporočil, kdo se s kom pogovarja, imen kanalov, vaših stikov ali vašega natančnega položaja. Lokacije so zaokrožene na približno 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'To lahko kadar koli spremenite v Nastavitve → Nastavitve aplikacije → Omrežni zemljevid.'; + + @override + String get networkMap_promptAccept => 'Deli'; + + @override + String get networkMap_promptDecline => 'Ne, hvala'; + + @override + String get networkMap_statusOff => 'Izklopljeno. Nič se ne pošilja.'; + + @override + String get networkMap_statusWaiting => + 'Vklopljeno. Čakanje na povezavo z radiem.'; + + @override + String get networkMap_statusNothingSent => 'Vklopljeno. Še nič poslanega.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Nazadnje poslano $time. Paketov danes: $count.'; + } + + @override + String get networkMap_sourceLocal => 'Lokalno'; + + @override + String get networkMap_sourceOnline => 'Na spletu'; + + @override + String get networkMap_sourceBoth => 'Oboje'; + + @override + String get networkMap_zoomInHint => + 'Povečajte, da vidite spletni omrežni zemljevid'; + + @override + String get networkMap_loadFailed => + 'Spletnega omrežnega zemljevida ni bilo mogoče naložiti'; + + @override + String get networkMap_inYourContacts => 'V vaših stikih'; + + @override + String get networkMap_status => 'Stanje'; + + @override + String get networkMap_statusActive => 'Aktiven v zadnji uri'; + + @override + String get networkMap_statusRecent => 'Slišan v zadnjem dnevu'; + + @override + String get networkMap_statusStale => 'V zadnjem času ni bil slišan'; + + @override + String get networkMap_confirmed => 'Potrjeno'; + + @override + String get networkMap_singleSource => 'En vir, še ni potrjeno'; + + @override + String get networkMap_reports => 'Poročila'; + + @override + String get networkMap_locationEstimated => + 'Približna lokacija, ocenjena glede na to, kdo ga je slišal'; + + @override + String get networkMap_locationAdvertised => + 'Približna lokacija, iz njegovega lastnega adverta'; + + @override + String get networkMap_heardByRadio => 'Sliši ga vaš radio'; + + @override + String get networkMap_inYourArea => 'V vaši bližini'; + + @override + String get networkMap_farAway => 'Daleč stran. Upravljanje ne bo doseglo.'; + + @override + String get networkMap_addToContacts => 'Dodaj med stike'; + + @override + String get networkMap_manage => 'Upravljaj'; + + @override + String get networkMap_addedToContacts => 'Dodano med stike'; + + @override + String get networkMap_addFailed => 'Dodajanje med stike ni uspelo'; + + @override + String get networkMap_unnamed => 'Repeater brez imena'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index f6be1117..1d87483d 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -356,6 +356,20 @@ class AppLocalizationsSv extends AppLocalizations { @override String get scanner_enableBluetooth => 'Aktivera Bluetooth'; + @override + String get scanner_getNodeTitle => 'Behöver du en ny nod?'; + + @override + String get scanner_getNodeBody => + 'Plånboksstorlek, kör MeshCore, GPS med dubbla band, vattentät, 5 dagars batteritid.'; + + @override + String get scanner_getNodeAction => 'Skaffa en här'; + + @override + String get scanner_getNodeDisclosure => + 'Affiliatelänk: varje köp stöder MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth är inte tillgängligt i webbläsaren. Anslut istället via USB.'; @@ -6130,4 +6144,121 @@ class AppLocalizationsSv extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours h $minutes min'; } + + @override + String get networkMap_settingsSection => 'Nätverkskarta'; + + @override + String get networkMap_uploadTitle => 'Dela vad min radio hör'; + + @override + String get networkMap_uploadExplanation => + 'När detta är på och din radio är ansluten skickar appen en kort sammanfattning av paketen som din radio hör till MeshCore Opens nätverkskarta, så att alla kan se vilka repeaters som finns och hur de hänger ihop. Den skickar varje pakets typ, rutt, antal hopp, signalstyrka och storlek, plus repeaternamn och ungefärliga platser från deras egna annonser. Den skickar aldrig meddelandetext, vem som pratar med vem, kanalnamn, dina kontakter eller din exakta position: platser avrundas till cirka 2 km, och din app får ett nytt slumpmässigt ID varje dag.'; + + @override + String get networkMap_whatWeCollect => 'Vad vi samlar in'; + + @override + String get networkMap_promptTitle => 'Hjälpa till att bygga nätverkskartan?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open kan dela vad din radio hör med den offentliga nätverkskartan på map.meshcoreopen.org, så att alla kan se vilka repeaters som finns och hur de hänger ihop.\n\nDen skickar aldrig meddelandetext, vem som pratar med vem, kanalnamn, dina kontakter eller din exakta position. Platser avrundas till cirka 2 km.'; + + @override + String get networkMap_promptSettingsHint => + 'Du kan ändra detta när som helst under Inställningar → Appinställningar → Nätverkskarta.'; + + @override + String get networkMap_promptAccept => 'Dela'; + + @override + String get networkMap_promptDecline => 'Nej tack'; + + @override + String get networkMap_statusOff => 'Av. Inget skickas.'; + + @override + String get networkMap_statusWaiting => 'På. Väntar på radioanslutning.'; + + @override + String get networkMap_statusNothingSent => 'På. Inget skickat ännu.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Senast skickat $time. $count paket idag.'; + } + + @override + String get networkMap_sourceLocal => 'Lokal'; + + @override + String get networkMap_sourceOnline => 'Online'; + + @override + String get networkMap_sourceBoth => 'Båda'; + + @override + String get networkMap_zoomInHint => + 'Zooma in för att se nätverkskartan online'; + + @override + String get networkMap_loadFailed => + 'Det gick inte att ladda nätverkskartan online'; + + @override + String get networkMap_inYourContacts => 'I dina kontakter'; + + @override + String get networkMap_status => 'Status'; + + @override + String get networkMap_statusActive => 'Aktiv den senaste timmen'; + + @override + String get networkMap_statusRecent => 'Hörd under det senaste dygnet'; + + @override + String get networkMap_statusStale => 'Inte hörd på sistone'; + + @override + String get networkMap_confirmed => 'Bekräftad'; + + @override + String get networkMap_singleSource => 'Enskild källa, ännu inte bekräftad'; + + @override + String get networkMap_reports => 'Rapporter'; + + @override + String get networkMap_locationEstimated => + 'Ungefärlig plats, uppskattad utifrån vilka som hörde den'; + + @override + String get networkMap_locationAdvertised => + 'Ungefärlig plats, från dess egen annons'; + + @override + String get networkMap_heardByRadio => 'Hörd av din radio'; + + @override + String get networkMap_inYourArea => 'I ditt område'; + + @override + String get networkMap_farAway => 'Långt bort. Hantering når inte dit.'; + + @override + String get networkMap_addToContacts => 'Lägg till i kontakter'; + + @override + String get networkMap_manage => 'Hantera'; + + @override + String get networkMap_addedToContacts => 'Tillagd i kontakter'; + + @override + String get networkMap_addFailed => 'Det gick inte att lägga till i kontakter'; + + @override + String get networkMap_unnamed => 'Namnlös repeater'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 4d57e40e..ebd6d5eb 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -359,6 +359,20 @@ class AppLocalizationsUk extends AppLocalizations { @override String get scanner_enableBluetooth => 'Увімкніть Bluetooth'; + @override + String get scanner_getNodeTitle => 'Потрібна нова нода?'; + + @override + String get scanner_getNodeBody => + 'Розміром з гаманець, працює на MeshCore, дводіапазонний GPS, водонепроникна, батареї вистачає на 5 днів.'; + + @override + String get scanner_getNodeAction => 'Придбати тут'; + + @override + String get scanner_getNodeDisclosure => + 'Партнерське посилання: кожна покупка підтримує MeshCore Open.'; + @override String get scanner_bluetoothWebUnsupported => 'Bluetooth недоступний у браузері. Підключіться через USB.'; @@ -6202,4 +6216,123 @@ class AppLocalizationsUk extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hoursгод $minutesхв'; } + + @override + String get networkMap_settingsSection => 'Карта мережі'; + + @override + String get networkMap_uploadTitle => 'Ділитися тим, що чує мій радіомодуль'; + + @override + String get networkMap_uploadExplanation => + 'Коли це ввімкнено і радіомодуль підключено, застосунок надсилає на карту мережі MeshCore Open короткий підсумок пакетів, які чує ваш радіомодуль, щоб усі могли бачити, які ретранслятори існують і як вони пов\'язані. Надсилаються тип, маршрут, кількість хопів, рівень сигналу та розмір кожного пакета, а також назви ретрансляторів і їхнє приблизне розташування з їхніх власних оголошень. Ніколи не надсилаються текст повідомлень, хто з ким спілкується, назви каналів, ваші контакти та ваше точне розташування: координати округлюються приблизно до 2 км, а застосунок щодня отримує новий випадковий ID.'; + + @override + String get networkMap_whatWeCollect => 'Що ми збираємо'; + + @override + String get networkMap_promptTitle => 'Допомогти побудувати карту мережі?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open може ділитися тим, що чує ваш радіомодуль, з публічною картою мережі на map.meshcoreopen.org, щоб усі могли бачити, які ретранслятори існують і як вони пов\'язані.\n\nНіколи не надсилаються текст повідомлень, хто з ким спілкується, назви каналів, ваші контакти та ваше точне розташування. Координати округлюються приблизно до 2 км.'; + + @override + String get networkMap_promptSettingsHint => + 'Це можна змінити будь-коли: Налаштування → Налаштування застосунку → Карта мережі.'; + + @override + String get networkMap_promptAccept => 'Ділитися'; + + @override + String get networkMap_promptDecline => 'Ні, дякую'; + + @override + String get networkMap_statusOff => 'Вимкнено. Нічого не надсилається.'; + + @override + String get networkMap_statusWaiting => + 'Ввімкнено. Очікування підключення радіомодуля.'; + + @override + String get networkMap_statusNothingSent => + 'Ввімкнено. Поки що нічого не надіслано.'; + + @override + String networkMap_statusLastSent(String time, int count) { + return 'Останнє надсилання: $time. Пакетів сьогодні: $count.'; + } + + @override + String get networkMap_sourceLocal => 'Локальна'; + + @override + String get networkMap_sourceOnline => 'Онлайн'; + + @override + String get networkMap_sourceBoth => 'Обидві'; + + @override + String get networkMap_zoomInHint => + 'Наблизьте, щоб побачити онлайн-карту мережі'; + + @override + String get networkMap_loadFailed => + 'Не вдалося завантажити онлайн-карту мережі'; + + @override + String get networkMap_inYourContacts => 'У ваших контактах'; + + @override + String get networkMap_status => 'Статус'; + + @override + String get networkMap_statusActive => 'Активний за останню годину'; + + @override + String get networkMap_statusRecent => 'Чутно за останню добу'; + + @override + String get networkMap_statusStale => 'Давно не чутно'; + + @override + String get networkMap_confirmed => 'Підтверджено'; + + @override + String get networkMap_singleSource => 'Одне джерело, ще не підтверджено'; + + @override + String get networkMap_reports => 'Звіти'; + + @override + String get networkMap_locationEstimated => + 'Приблизне розташування, оцінене за тими, хто його чув'; + + @override + String get networkMap_locationAdvertised => + 'Приблизне розташування, з власного оголошення'; + + @override + String get networkMap_heardByRadio => 'Чує ваш радіомодуль'; + + @override + String get networkMap_inYourArea => 'У вашому районі'; + + @override + String get networkMap_farAway => 'Далеко. Керування недоступне.'; + + @override + String get networkMap_addToContacts => 'Додати до контактів'; + + @override + String get networkMap_manage => 'Керувати'; + + @override + String get networkMap_addedToContacts => 'Додано до контактів'; + + @override + String get networkMap_addFailed => 'Не вдалося додати до контактів'; + + @override + String get networkMap_unnamed => 'Ретранслятор без назви'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 471da3d8..703a27fe 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -341,6 +341,18 @@ class AppLocalizationsZh extends AppLocalizations { @override String get scanner_enableBluetooth => '启用蓝牙'; + @override + String get scanner_getNodeTitle => '需要新节点吗?'; + + @override + String get scanner_getNodeBody => '钱包大小,运行 MeshCore,双频 GPS,防水,续航 5 天。'; + + @override + String get scanner_getNodeAction => '点此获取'; + + @override + String get scanner_getNodeDisclosure => '推广链接:每次购买都会支持 MeshCore Open。'; + @override String get scanner_bluetoothWebUnsupported => '浏览器不支持蓝牙,请改用 USB 连接。'; @@ -5760,4 +5772,116 @@ class AppLocalizationsZh extends AppLocalizations { String neighbors_durationHours(int hours, int minutes) { return '$hours小时$minutes分'; } + + @override + String get networkMap_settingsSection => '网络地图'; + + @override + String get networkMap_uploadTitle => '分享我的电台收到的信息'; + + @override + String get networkMap_uploadExplanation => + '开启后,当您的电台已连接时,应用会把电台收到的数据包的简要信息发送到 MeshCore Open 网络地图,让大家看到有哪些转发节点以及它们如何相连。发送内容包括每个数据包的类型、路由、跳数、信号强度和大小,以及转发节点自身广播中的名称和大致位置。绝不会发送消息内容、谁在和谁通信、频道名称、您的联系人或您的精确位置:位置会取整到约 2 公里,且应用每天都会使用新的随机 ID。'; + + @override + String get networkMap_whatWeCollect => '我们收集的内容'; + + @override + String get networkMap_promptTitle => '要帮助建设网络地图吗?'; + + @override + String get networkMap_promptBody => + 'MeshCore Open 可以把您的电台收到的信息分享到公开的网络地图 map.meshcoreopen.org,让大家看到有哪些转发节点以及它们如何相连。\n\n绝不会发送消息内容、谁在和谁通信、频道名称、您的联系人或您的精确位置。位置会取整到约 2 公里。'; + + @override + String get networkMap_promptSettingsHint => '您可以随时在 设置 → 应用设置 → 网络地图 中更改。'; + + @override + String get networkMap_promptAccept => '分享'; + + @override + String get networkMap_promptDecline => '不用了'; + + @override + String get networkMap_statusOff => '已关闭。不会发送任何内容。'; + + @override + String get networkMap_statusWaiting => '已开启。正在等待电台连接。'; + + @override + String get networkMap_statusNothingSent => '已开启。尚未发送任何内容。'; + + @override + String networkMap_statusLastSent(String time, int count) { + return '上次发送 $time。今天 $count 个数据包。'; + } + + @override + String get networkMap_sourceLocal => '本地'; + + @override + String get networkMap_sourceOnline => '在线'; + + @override + String get networkMap_sourceBoth => '两者'; + + @override + String get networkMap_zoomInHint => '放大以查看在线网络地图'; + + @override + String get networkMap_loadFailed => '无法加载在线网络地图'; + + @override + String get networkMap_inYourContacts => '在您的联系人中'; + + @override + String get networkMap_status => '状态'; + + @override + String get networkMap_statusActive => '最近一小时内活跃'; + + @override + String get networkMap_statusRecent => '最近一天内收到过'; + + @override + String get networkMap_statusStale => '近期未收到'; + + @override + String get networkMap_confirmed => '已确认'; + + @override + String get networkMap_singleSource => '单一来源,尚未确认'; + + @override + String get networkMap_reports => '报告'; + + @override + String get networkMap_locationEstimated => '大致位置,根据接收到它的节点估算'; + + @override + String get networkMap_locationAdvertised => '大致位置,来自其自身广播'; + + @override + String get networkMap_heardByRadio => '您的电台收到过'; + + @override + String get networkMap_inYourArea => '在您所在区域'; + + @override + String get networkMap_farAway => '距离太远,无法管理。'; + + @override + String get networkMap_addToContacts => '添加到联系人'; + + @override + String get networkMap_manage => '管理'; + + @override + String get networkMap_addedToContacts => '已添加到联系人'; + + @override + String get networkMap_addFailed => '无法添加到联系人'; + + @override + String get networkMap_unnamed => '未命名转发节点'; } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index fcacaa94..4f7d8d61 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -3161,5 +3161,55 @@ "usbChooseSerialPort": "Seriële poort kiezen", "neighbors_durationSeconds": "{seconds}s", "neighbors_durationMinutes": "{minutes}m {seconds}s", - "neighbors_durationHours": "{hours}u {minutes}m" + "neighbors_durationHours": "{hours}u {minutes}m", + "scanner_getNodeTitle": "Een nieuwe node nodig?", + "scanner_getNodeBody": "Zo klein als een portemonnee, draait MeshCore, dual-band GPS, waterdicht, 5 dagen accuduur.", + "scanner_getNodeAction": "Haal er hier een", + "scanner_getNodeDisclosure": "Affiliatelink: elke aankoop steunt MeshCore Open.", + "networkMap_settingsSection": "Netwerkkaart", + "networkMap_uploadTitle": "Delen wat mijn radio hoort", + "networkMap_uploadExplanation": "Als dit aan staat en je radio verbonden is, stuurt de app een korte samenvatting van de pakketten die je radio hoort naar de MeshCore Open-netwerkkaart, zodat iedereen kan zien welke repeaters er zijn en hoe ze met elkaar verbonden zijn. Per pakket wordt het type, de route, het aantal hops, de signaalsterkte en de grootte verstuurd, plus repeaternamen en globale locaties uit hun eigen adverts. Er worden nooit berichttekst, wie met wie praat, kanaalnamen, je contacten of je exacte positie verstuurd: locaties worden afgerond op ongeveer 2 km en je app krijgt elke dag een nieuw willekeurig ID.", + "networkMap_whatWeCollect": "Wat we verzamelen", + "networkMap_promptTitle": "Helpen de netwerkkaart te bouwen?", + "networkMap_promptBody": "MeshCore Open kan delen wat je radio hoort met de openbare netwerkkaart op map.meshcoreopen.org, zodat iedereen kan zien welke repeaters er zijn en hoe ze met elkaar verbonden zijn.\n\nEr worden nooit berichttekst, wie met wie praat, kanaalnamen, je contacten of je exacte positie verstuurd. Locaties worden afgerond op ongeveer 2 km.", + "networkMap_promptSettingsHint": "Je kunt dit op elk moment wijzigen via Instellingen → App Instellingen → Netwerkkaart.", + "networkMap_promptAccept": "Delen", + "networkMap_promptDecline": "Nee, bedankt", + "networkMap_statusOff": "Uit. Er wordt niets verstuurd.", + "networkMap_statusWaiting": "Aan. Wachten op een radioverbinding.", + "networkMap_statusNothingSent": "Aan. Nog niets verstuurd.", + "networkMap_statusLastSent": "Laatst verstuurd {time}. {count} pakketten vandaag.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Lokaal", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Beide", + "networkMap_zoomInHint": "Zoom in om de online netwerkkaart te zien", + "networkMap_loadFailed": "Kan de online netwerkkaart niet laden", + "networkMap_inYourContacts": "In je contacten", + "networkMap_status": "Status", + "networkMap_statusActive": "Actief in het laatste uur", + "networkMap_statusRecent": "Gehoord in de afgelopen dag", + "networkMap_statusStale": "Onlangs niet gehoord", + "networkMap_confirmed": "Bevestigd", + "networkMap_singleSource": "Eén bron, nog niet bevestigd", + "networkMap_reports": "Meldingen", + "networkMap_locationEstimated": "Globale locatie, geschat op basis van wie het hoorde", + "networkMap_locationAdvertised": "Globale locatie, uit zijn eigen advert", + "networkMap_heardByRadio": "Gehoord door je radio", + "networkMap_inYourArea": "In jouw omgeving", + "networkMap_farAway": "Ver weg. Beheer bereikt het niet.", + "networkMap_addToContacts": "Toevoegen aan contacten", + "networkMap_manage": "Beheren", + "networkMap_addedToContacts": "Toegevoegd aan contacten", + "networkMap_addFailed": "Kan niet aan contacten toevoegen", + "networkMap_unnamed": "Naamloze repeater" } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index f6b82399..77ca42b7 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3293,5 +3293,55 @@ "usbChooseSerialPort": "Wybierz port szeregowy", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} min {seconds} s", - "neighbors_durationHours": "{hours} godz. {minutes} min" + "neighbors_durationHours": "{hours} godz. {minutes} min", + "scanner_getNodeTitle": "Potrzebujesz nowego węzła?", + "scanner_getNodeBody": "Wielkości portfela, z MeshCore, dwuzakresowy GPS, wodoodporny, bateria na 5 dni.", + "scanner_getNodeAction": "Kup tutaj", + "scanner_getNodeDisclosure": "Link partnerski: każdy zakup wspiera MeshCore Open.", + "networkMap_settingsSection": "Mapa sieci", + "networkMap_uploadTitle": "Udostępniaj to, co słyszy moje radio", + "networkMap_uploadExplanation": "Gdy ta opcja jest włączona, a radio połączone, aplikacja wysyła krótkie podsumowanie pakietów słyszanych przez radio do mapy sieci MeshCore Open, aby każdy mógł zobaczyć, jakie repeatery istnieją i jak się łączą. Wysyłany jest typ, trasa, liczba skoków, siła sygnału i rozmiar każdego pakietu oraz nazwy repeaterów i przybliżone lokalizacje z ich własnych rozgłoszeń. Nigdy nie wysyła treści wiadomości, informacji o tym, kto z kim rozmawia, nazw kanałów, Twoich kontaktów ani Twojej dokładnej pozycji: lokalizacje są zaokrąglane do około 2 km, a aplikacja co dzień dostaje nowy losowy identyfikator.", + "networkMap_whatWeCollect": "Co zbieramy", + "networkMap_promptTitle": "Pomóc w budowie mapy sieci?", + "networkMap_promptBody": "MeshCore Open może udostępniać to, co słyszy Twoje radio, publicznej mapie sieci na map.meshcoreopen.org, aby każdy mógł zobaczyć, jakie repeatery istnieją i jak się łączą.\n\nNigdy nie wysyła treści wiadomości, informacji o tym, kto z kim rozmawia, nazw kanałów, Twoich kontaktów ani Twojej dokładnej pozycji. Lokalizacje są zaokrąglane do około 2 km.", + "networkMap_promptSettingsHint": "Możesz to zmienić w dowolnym momencie w Ustawienia → Ustawienia aplikacji → Mapa sieci.", + "networkMap_promptAccept": "Udostępnij", + "networkMap_promptDecline": "Nie, dziękuję", + "networkMap_statusOff": "Wyłączone. Nic nie jest wysyłane.", + "networkMap_statusWaiting": "Włączone. Oczekiwanie na połączenie z radiem.", + "networkMap_statusNothingSent": "Włączone. Nic jeszcze nie wysłano.", + "networkMap_statusLastSent": "Ostatnio wysłano {time}. Pakiety dzisiaj: {count}.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Lokalna", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Obie", + "networkMap_zoomInHint": "Przybliż, aby zobaczyć mapę sieci online", + "networkMap_loadFailed": "Nie udało się wczytać mapy sieci online", + "networkMap_inYourContacts": "W Twoich kontaktach", + "networkMap_status": "Stan", + "networkMap_statusActive": "Aktywny w ostatniej godzinie", + "networkMap_statusRecent": "Słyszany w ostatniej dobie", + "networkMap_statusStale": "Dawno niesłyszany", + "networkMap_confirmed": "Potwierdzony", + "networkMap_singleSource": "Jedno źródło, jeszcze niepotwierdzone", + "networkMap_reports": "Raporty", + "networkMap_locationEstimated": "Przybliżona lokalizacja, oszacowana na podstawie tego, kto go słyszał", + "networkMap_locationAdvertised": "Przybliżona lokalizacja, z jego własnego rozgłoszenia", + "networkMap_heardByRadio": "Słyszany przez Twoje radio", + "networkMap_inYourArea": "W Twojej okolicy", + "networkMap_farAway": "Daleko. Zarządzanie tam nie dotrze.", + "networkMap_addToContacts": "Dodaj do kontaktów", + "networkMap_manage": "Zarządzaj", + "networkMap_addedToContacts": "Dodano do kontaktów", + "networkMap_addFailed": "Nie udało się dodać do kontaktów", + "networkMap_unnamed": "Repeater bez nazwy" } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 960562d5..d211e265 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3260,5 +3260,55 @@ "usbChooseSerialPort": "Escolher porta serial", "neighbors_durationSeconds": "{seconds}s", "neighbors_durationMinutes": "{minutes}m {seconds}s", - "neighbors_durationHours": "{hours}h {minutes}m" + "neighbors_durationHours": "{hours}h {minutes}m", + "scanner_getNodeTitle": "Precisa de um novo nó?", + "scanner_getNodeBody": "Do tamanho de uma carteira, roda MeshCore, GPS dual-band, à prova d'água, bateria para 5 dias.", + "scanner_getNodeAction": "Compre aqui", + "scanner_getNodeDisclosure": "Link de afiliado: cada compra apoia o MeshCore Open.", + "networkMap_settingsSection": "Mapa da rede", + "networkMap_uploadTitle": "Compartilhar o que meu rádio ouve", + "networkMap_uploadExplanation": "Quando isto está ativado e o seu rádio está conectado, o app envia um breve resumo dos pacotes que o seu rádio ouve para o mapa da rede do MeshCore Open, para que todos possam ver quais repetidores existem e como se conectam. Ele envia o tipo, a rota, os saltos, a intensidade do sinal e o tamanho de cada pacote, além dos nomes e localizações aproximadas dos repetidores, obtidos dos próprios anúncios. Nunca envia o texto das mensagens, quem fala com quem, nomes de canais, seus contactos nem a sua posição exata: as localizações são arredondadas para cerca de 2 km, e o seu app recebe um novo ID aleatório todos os dias.", + "networkMap_whatWeCollect": "O que coletamos", + "networkMap_promptTitle": "Ajudar a construir o mapa da rede?", + "networkMap_promptBody": "O MeshCore Open pode compartilhar o que o seu rádio ouve com o mapa público da rede em map.meshcoreopen.org, para que todos possam ver quais repetidores existem e como se conectam.\n\nNunca envia o texto das mensagens, quem fala com quem, nomes de canais, seus contactos nem a sua posição exata. As localizações são arredondadas para cerca de 2 km.", + "networkMap_promptSettingsHint": "Você pode mudar isso a qualquer momento em Configurações → Configurações do App → Mapa da rede.", + "networkMap_promptAccept": "Compartilhar", + "networkMap_promptDecline": "Não, obrigado", + "networkMap_statusOff": "Desativado. Nada é enviado.", + "networkMap_statusWaiting": "Ativado. Aguardando conexão com o rádio.", + "networkMap_statusNothingSent": "Ativado. Nada enviado ainda.", + "networkMap_statusLastSent": "Último envio {time}. {count} pacotes hoje.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Local", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Ambos", + "networkMap_zoomInHint": "Aproxime o zoom para ver o mapa da rede online", + "networkMap_loadFailed": "Não foi possível carregar o mapa da rede online", + "networkMap_inYourContacts": "Nos seus contactos", + "networkMap_status": "Estado", + "networkMap_statusActive": "Ativo na última hora", + "networkMap_statusRecent": "Ouvido no último dia", + "networkMap_statusStale": "Não ouvido recentemente", + "networkMap_confirmed": "Confirmado", + "networkMap_singleSource": "Fonte única, ainda não confirmado", + "networkMap_reports": "Relatórios", + "networkMap_locationEstimated": "Localização aproximada, estimada a partir de quem o ouviu", + "networkMap_locationAdvertised": "Localização aproximada, do próprio anúncio", + "networkMap_heardByRadio": "Ouvido pelo seu rádio", + "networkMap_inYourArea": "Na sua área", + "networkMap_farAway": "Muito longe. A gestão não chegará até ele.", + "networkMap_addToContacts": "Adicionar aos contactos", + "networkMap_manage": "Gerenciar", + "networkMap_addedToContacts": "Adicionado aos contactos", + "networkMap_addFailed": "Não foi possível adicionar aos contactos", + "networkMap_unnamed": "Repetidor sem nome" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 564d72f8..f2d3baeb 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -2557,5 +2557,55 @@ "usbChooseSerialPort": "Выберите последовательный порт", "neighbors_durationSeconds": "{seconds}с", "neighbors_durationMinutes": "{minutes}м {seconds}с", - "neighbors_durationHours": "{hours}ч {minutes}м" + "neighbors_durationHours": "{hours}ч {minutes}м", + "scanner_getNodeTitle": "Нужна новая нода?", + "scanner_getNodeBody": "Размером с кошелёк, работает на MeshCore, двухдиапазонный GPS, водонепроницаемая, батареи хватает на 5 дней.", + "scanner_getNodeAction": "Купить здесь", + "scanner_getNodeDisclosure": "Партнёрская ссылка: каждая покупка поддерживает MeshCore Open.", + "networkMap_settingsSection": "Карта сети", + "networkMap_uploadTitle": "Делиться тем, что слышит мой радиомодуль", + "networkMap_uploadExplanation": "Когда это включено и радиомодуль подключён, приложение отправляет на карту сети MeshCore Open краткую сводку о пакетах, которые слышит ваш радиомодуль, чтобы все могли видеть, какие репитеры существуют и как они связаны. Отправляются тип, маршрут, число хопов, уровень сигнала и размер каждого пакета, а также названия репитеров и их примерное местоположение из их собственных анонсов. Никогда не отправляются текст сообщений, кто с кем общается, названия каналов, ваши контакты и ваше точное местоположение: координаты округляются примерно до 2 км, а приложение каждый день получает новый случайный ID.", + "networkMap_whatWeCollect": "Что мы собираем", + "networkMap_promptTitle": "Помочь построить карту сети?", + "networkMap_promptBody": "MeshCore Open может делиться тем, что слышит ваш радиомодуль, с публичной картой сети на map.meshcoreopen.org, чтобы все могли видеть, какие репитеры существуют и как они связаны.\n\nНикогда не отправляются текст сообщений, кто с кем общается, названия каналов, ваши контакты и ваше точное местоположение. Координаты округляются примерно до 2 км.", + "networkMap_promptSettingsHint": "Это можно изменить в любой момент: Настройки → Настройки приложения → Карта сети.", + "networkMap_promptAccept": "Делиться", + "networkMap_promptDecline": "Нет, спасибо", + "networkMap_statusOff": "Выключено. Ничего не отправляется.", + "networkMap_statusWaiting": "Включено. Ожидание подключения радиомодуля.", + "networkMap_statusNothingSent": "Включено. Пока ничего не отправлено.", + "networkMap_statusLastSent": "Последняя отправка: {time}. Пакетов сегодня: {count}.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Локальная", + "networkMap_sourceOnline": "Онлайн", + "networkMap_sourceBoth": "Обе", + "networkMap_zoomInHint": "Приблизьте, чтобы увидеть онлайн-карту сети", + "networkMap_loadFailed": "Не удалось загрузить онлайн-карту сети", + "networkMap_inYourContacts": "В ваших контактах", + "networkMap_status": "Статус", + "networkMap_statusActive": "Активен за последний час", + "networkMap_statusRecent": "Слышен за последние сутки", + "networkMap_statusStale": "Давно не слышен", + "networkMap_confirmed": "Подтверждён", + "networkMap_singleSource": "Один источник, пока не подтверждён", + "networkMap_reports": "Отчёты", + "networkMap_locationEstimated": "Примерное местоположение, оценено по тем, кто его слышал", + "networkMap_locationAdvertised": "Примерное местоположение, из собственного анонса", + "networkMap_heardByRadio": "Слышен вашим радиомодулем", + "networkMap_inYourArea": "В вашем районе", + "networkMap_farAway": "Далеко. Управление недоступно.", + "networkMap_addToContacts": "Добавить в контакты", + "networkMap_manage": "Управлять", + "networkMap_addedToContacts": "Добавлено в контакты", + "networkMap_addFailed": "Не удалось добавить в контакты", + "networkMap_unnamed": "Репитер без имени" } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index e3de5e7e..d2525a42 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3261,5 +3261,55 @@ "usbChooseSerialPort": "Vyberte sériový port", "neighbors_durationSeconds": "{seconds}s", "neighbors_durationMinutes": "{minutes}m {seconds}s", - "neighbors_durationHours": "{hours}h {minutes}m" + "neighbors_durationHours": "{hours}h {minutes}m", + "scanner_getNodeTitle": "Potrebujete nový uzol?", + "scanner_getNodeBody": "Veľkosti peňaženky, beží na MeshCore, dvojpásmové GPS, vodotesný, batéria vydrží 5 dní.", + "scanner_getNodeAction": "Kúpte si ho tu", + "scanner_getNodeDisclosure": "Partnerský odkaz: každý nákup podporuje MeshCore Open.", + "networkMap_settingsSection": "Sieťová mapa", + "networkMap_uploadTitle": "Zdieľať, čo počuje moje rádio", + "networkMap_uploadExplanation": "Keď je to zapnuté a rádio je pripojené, aplikácia odosiela na sieťovú mapu MeshCore Open stručný súhrn paketov, ktoré vaše rádio počuje, aby každý videl, aké opakovače existujú a ako sú prepojené. Odosiela typ, trasu, počet skokov, silu signálu a veľkosť každého paketu, ako aj názvy opakovačov a ich približnú polohu z ich vlastných inzerátov. Nikdy neodosiela text správ, kto s kým komunikuje, názvy kanálov, vaše kontakty ani vašu presnú polohu: polohy sa zaokrúhľujú na približne 2 km a aplikácia dostáva nové náhodné ID každý deň.", + "networkMap_whatWeCollect": "Čo zbierame", + "networkMap_promptTitle": "Pomôcť budovať sieťovú mapu?", + "networkMap_promptBody": "MeshCore Open môže zdieľať, čo vaše rádio počuje, s verejnou sieťovou mapou na map.meshcoreopen.org, aby každý videl, aké opakovače existujú a ako sú prepojené.\n\nNikdy neodosiela text správ, kto s kým komunikuje, názvy kanálov, vaše kontakty ani vašu presnú polohu. Polohy sa zaokrúhľujú na približne 2 km.", + "networkMap_promptSettingsHint": "Môžete to kedykoľvek zmeniť v Nastavenia → Nastavenia aplikácie → Sieťová mapa.", + "networkMap_promptAccept": "Zdieľať", + "networkMap_promptDecline": "Nie, ďakujem", + "networkMap_statusOff": "Vypnuté. Nič sa neodosiela.", + "networkMap_statusWaiting": "Zapnuté. Čaká sa na pripojenie rádia.", + "networkMap_statusNothingSent": "Zapnuté. Zatiaľ nič neodoslané.", + "networkMap_statusLastSent": "Naposledy odoslané {time}. Dnes paketov: {count}.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Lokálna", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Obe", + "networkMap_zoomInHint": "Priblížte, aby ste videli online sieťovú mapu", + "networkMap_loadFailed": "Online sieťovú mapu sa nepodarilo načítať", + "networkMap_inYourContacts": "Vo vašich kontaktoch", + "networkMap_status": "Stav", + "networkMap_statusActive": "Aktívny za poslednú hodinu", + "networkMap_statusRecent": "Počuť za posledný deň", + "networkMap_statusStale": "Dlho nepočuť", + "networkMap_confirmed": "Potvrdený", + "networkMap_singleSource": "Jeden zdroj, zatiaľ nepotvrdený", + "networkMap_reports": "Hlásenia", + "networkMap_locationEstimated": "Približná poloha, odhadnutá podľa toho, kto ho počul", + "networkMap_locationAdvertised": "Približná poloha, z vlastného inzerátu", + "networkMap_heardByRadio": "Počuté vaším rádiom", + "networkMap_inYourArea": "Vo vašej oblasti", + "networkMap_farAway": "Ďaleko. Správa ho nedosiahne.", + "networkMap_addToContacts": "Pridať do kontaktov", + "networkMap_manage": "Spravovať", + "networkMap_addedToContacts": "Pridané do kontaktov", + "networkMap_addFailed": "Nepodarilo sa pridať do kontaktov", + "networkMap_unnamed": "Nepomenovaný opakovač" } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 97e5cc06..5bc612a0 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3261,5 +3261,55 @@ "usbChooseSerialPort": "Izberite serijska vrata", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} min {seconds} s", - "neighbors_durationHours": "{hours} h {minutes} min" + "neighbors_durationHours": "{hours} h {minutes} min", + "scanner_getNodeTitle": "Potrebujete nov node?", + "scanner_getNodeBody": "Velikosti denarnice, poganja MeshCore, dvopasovni GPS, vodoodporen, baterija za 5 dni.", + "scanner_getNodeAction": "Oglejte si ga tukaj", + "scanner_getNodeDisclosure": "Partnerska povezava: vsak nakup podpira MeshCore Open.", + "networkMap_settingsSection": "Omrežni zemljevid", + "networkMap_uploadTitle": "Deli, kaj sliši moj radio", + "networkMap_uploadExplanation": "Ko je to vklopljeno in je radio povezan, aplikacija na omrežni zemljevid MeshCore Open pošlje kratek povzetek paketov, ki jih sliši vaš radio, tako da vsi vidijo, kateri repeaterji obstajajo in kako so povezani. Pošlje vrsto, pot, število skokov, moč signala in velikost vsakega paketa ter imena in približne lokacije repeaterjev iz njihovih lastnih advertov. Nikoli ne pošlje besedila sporočil, kdo se s kom pogovarja, imen kanalov, vaših stikov ali vašega natančnega položaja: lokacije so zaokrožene na približno 2 km, aplikacija pa vsak dan dobi nov naključni ID.", + "networkMap_whatWeCollect": "Kaj zbiramo", + "networkMap_promptTitle": "Pomagate graditi omrežni zemljevid?", + "networkMap_promptBody": "MeshCore Open lahko deli, kaj sliši vaš radio, z javnim omrežnim zemljevidom na map.meshcoreopen.org, tako da vsi vidijo, kateri repeaterji obstajajo in kako so povezani.\n\nNikoli ne pošlje besedila sporočil, kdo se s kom pogovarja, imen kanalov, vaših stikov ali vašega natančnega položaja. Lokacije so zaokrožene na približno 2 km.", + "networkMap_promptSettingsHint": "To lahko kadar koli spremenite v Nastavitve → Nastavitve aplikacije → Omrežni zemljevid.", + "networkMap_promptAccept": "Deli", + "networkMap_promptDecline": "Ne, hvala", + "networkMap_statusOff": "Izklopljeno. Nič se ne pošilja.", + "networkMap_statusWaiting": "Vklopljeno. Čakanje na povezavo z radiem.", + "networkMap_statusNothingSent": "Vklopljeno. Še nič poslanega.", + "networkMap_statusLastSent": "Nazadnje poslano {time}. Paketov danes: {count}.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Lokalno", + "networkMap_sourceOnline": "Na spletu", + "networkMap_sourceBoth": "Oboje", + "networkMap_zoomInHint": "Povečajte, da vidite spletni omrežni zemljevid", + "networkMap_loadFailed": "Spletnega omrežnega zemljevida ni bilo mogoče naložiti", + "networkMap_inYourContacts": "V vaših stikih", + "networkMap_status": "Stanje", + "networkMap_statusActive": "Aktiven v zadnji uri", + "networkMap_statusRecent": "Slišan v zadnjem dnevu", + "networkMap_statusStale": "V zadnjem času ni bil slišan", + "networkMap_confirmed": "Potrjeno", + "networkMap_singleSource": "En vir, še ni potrjeno", + "networkMap_reports": "Poročila", + "networkMap_locationEstimated": "Približna lokacija, ocenjena glede na to, kdo ga je slišal", + "networkMap_locationAdvertised": "Približna lokacija, iz njegovega lastnega adverta", + "networkMap_heardByRadio": "Sliši ga vaš radio", + "networkMap_inYourArea": "V vaši bližini", + "networkMap_farAway": "Daleč stran. Upravljanje ne bo doseglo.", + "networkMap_addToContacts": "Dodaj med stike", + "networkMap_manage": "Upravljaj", + "networkMap_addedToContacts": "Dodano med stike", + "networkMap_addFailed": "Dodajanje med stike ni uspelo", + "networkMap_unnamed": "Repeater brez imena" } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 7b469c00..1857b8a5 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3255,5 +3255,55 @@ "usbChooseSerialPort": "Välj serieport", "neighbors_durationSeconds": "{seconds} s", "neighbors_durationMinutes": "{minutes} min {seconds} s", - "neighbors_durationHours": "{hours} h {minutes} min" + "neighbors_durationHours": "{hours} h {minutes} min", + "scanner_getNodeTitle": "Behöver du en ny nod?", + "scanner_getNodeBody": "Plånboksstorlek, kör MeshCore, GPS med dubbla band, vattentät, 5 dagars batteritid.", + "scanner_getNodeAction": "Skaffa en här", + "scanner_getNodeDisclosure": "Affiliatelänk: varje köp stöder MeshCore Open.", + "networkMap_settingsSection": "Nätverkskarta", + "networkMap_uploadTitle": "Dela vad min radio hör", + "networkMap_uploadExplanation": "När detta är på och din radio är ansluten skickar appen en kort sammanfattning av paketen som din radio hör till MeshCore Opens nätverkskarta, så att alla kan se vilka repeaters som finns och hur de hänger ihop. Den skickar varje pakets typ, rutt, antal hopp, signalstyrka och storlek, plus repeaternamn och ungefärliga platser från deras egna annonser. Den skickar aldrig meddelandetext, vem som pratar med vem, kanalnamn, dina kontakter eller din exakta position: platser avrundas till cirka 2 km, och din app får ett nytt slumpmässigt ID varje dag.", + "networkMap_whatWeCollect": "Vad vi samlar in", + "networkMap_promptTitle": "Hjälpa till att bygga nätverkskartan?", + "networkMap_promptBody": "MeshCore Open kan dela vad din radio hör med den offentliga nätverkskartan på map.meshcoreopen.org, så att alla kan se vilka repeaters som finns och hur de hänger ihop.\n\nDen skickar aldrig meddelandetext, vem som pratar med vem, kanalnamn, dina kontakter eller din exakta position. Platser avrundas till cirka 2 km.", + "networkMap_promptSettingsHint": "Du kan ändra detta när som helst under Inställningar → Appinställningar → Nätverkskarta.", + "networkMap_promptAccept": "Dela", + "networkMap_promptDecline": "Nej tack", + "networkMap_statusOff": "Av. Inget skickas.", + "networkMap_statusWaiting": "På. Väntar på radioanslutning.", + "networkMap_statusNothingSent": "På. Inget skickat ännu.", + "networkMap_statusLastSent": "Senast skickat {time}. {count} paket idag.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Lokal", + "networkMap_sourceOnline": "Online", + "networkMap_sourceBoth": "Båda", + "networkMap_zoomInHint": "Zooma in för att se nätverkskartan online", + "networkMap_loadFailed": "Det gick inte att ladda nätverkskartan online", + "networkMap_inYourContacts": "I dina kontakter", + "networkMap_status": "Status", + "networkMap_statusActive": "Aktiv den senaste timmen", + "networkMap_statusRecent": "Hörd under det senaste dygnet", + "networkMap_statusStale": "Inte hörd på sistone", + "networkMap_confirmed": "Bekräftad", + "networkMap_singleSource": "Enskild källa, ännu inte bekräftad", + "networkMap_reports": "Rapporter", + "networkMap_locationEstimated": "Ungefärlig plats, uppskattad utifrån vilka som hörde den", + "networkMap_locationAdvertised": "Ungefärlig plats, från dess egen annons", + "networkMap_heardByRadio": "Hörd av din radio", + "networkMap_inYourArea": "I ditt område", + "networkMap_farAway": "Långt bort. Hantering når inte dit.", + "networkMap_addToContacts": "Lägg till i kontakter", + "networkMap_manage": "Hantera", + "networkMap_addedToContacts": "Tillagd i kontakter", + "networkMap_addFailed": "Det gick inte att lägga till i kontakter", + "networkMap_unnamed": "Namnlös repeater" } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 7a8fe6f9..d8d3b7db 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3240,5 +3240,55 @@ "usbChooseSerialPort": "Виберіть послідовний порт", "neighbors_durationSeconds": "{seconds}с", "neighbors_durationMinutes": "{minutes}хв {seconds}с", - "neighbors_durationHours": "{hours}год {minutes}хв" + "neighbors_durationHours": "{hours}год {minutes}хв", + "scanner_getNodeTitle": "Потрібна нова нода?", + "scanner_getNodeBody": "Розміром з гаманець, працює на MeshCore, дводіапазонний GPS, водонепроникна, батареї вистачає на 5 днів.", + "scanner_getNodeAction": "Придбати тут", + "scanner_getNodeDisclosure": "Партнерське посилання: кожна покупка підтримує MeshCore Open.", + "networkMap_settingsSection": "Карта мережі", + "networkMap_uploadTitle": "Ділитися тим, що чує мій радіомодуль", + "networkMap_uploadExplanation": "Коли це ввімкнено і радіомодуль підключено, застосунок надсилає на карту мережі MeshCore Open короткий підсумок пакетів, які чує ваш радіомодуль, щоб усі могли бачити, які ретранслятори існують і як вони пов'язані. Надсилаються тип, маршрут, кількість хопів, рівень сигналу та розмір кожного пакета, а також назви ретрансляторів і їхнє приблизне розташування з їхніх власних оголошень. Ніколи не надсилаються текст повідомлень, хто з ким спілкується, назви каналів, ваші контакти та ваше точне розташування: координати округлюються приблизно до 2 км, а застосунок щодня отримує новий випадковий ID.", + "networkMap_whatWeCollect": "Що ми збираємо", + "networkMap_promptTitle": "Допомогти побудувати карту мережі?", + "networkMap_promptBody": "MeshCore Open може ділитися тим, що чує ваш радіомодуль, з публічною картою мережі на map.meshcoreopen.org, щоб усі могли бачити, які ретранслятори існують і як вони пов'язані.\n\nНіколи не надсилаються текст повідомлень, хто з ким спілкується, назви каналів, ваші контакти та ваше точне розташування. Координати округлюються приблизно до 2 км.", + "networkMap_promptSettingsHint": "Це можна змінити будь-коли: Налаштування → Налаштування застосунку → Карта мережі.", + "networkMap_promptAccept": "Ділитися", + "networkMap_promptDecline": "Ні, дякую", + "networkMap_statusOff": "Вимкнено. Нічого не надсилається.", + "networkMap_statusWaiting": "Ввімкнено. Очікування підключення радіомодуля.", + "networkMap_statusNothingSent": "Ввімкнено. Поки що нічого не надіслано.", + "networkMap_statusLastSent": "Останнє надсилання: {time}. Пакетів сьогодні: {count}.", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "Локальна", + "networkMap_sourceOnline": "Онлайн", + "networkMap_sourceBoth": "Обидві", + "networkMap_zoomInHint": "Наблизьте, щоб побачити онлайн-карту мережі", + "networkMap_loadFailed": "Не вдалося завантажити онлайн-карту мережі", + "networkMap_inYourContacts": "У ваших контактах", + "networkMap_status": "Статус", + "networkMap_statusActive": "Активний за останню годину", + "networkMap_statusRecent": "Чутно за останню добу", + "networkMap_statusStale": "Давно не чутно", + "networkMap_confirmed": "Підтверджено", + "networkMap_singleSource": "Одне джерело, ще не підтверджено", + "networkMap_reports": "Звіти", + "networkMap_locationEstimated": "Приблизне розташування, оцінене за тими, хто його чув", + "networkMap_locationAdvertised": "Приблизне розташування, з власного оголошення", + "networkMap_heardByRadio": "Чує ваш радіомодуль", + "networkMap_inYourArea": "У вашому районі", + "networkMap_farAway": "Далеко. Керування недоступне.", + "networkMap_addToContacts": "Додати до контактів", + "networkMap_manage": "Керувати", + "networkMap_addedToContacts": "Додано до контактів", + "networkMap_addFailed": "Не вдалося додати до контактів", + "networkMap_unnamed": "Ретранслятор без назви" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 7fa7bbd0..410b3a42 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3265,5 +3265,55 @@ "usbChooseSerialPort": "选择串口", "neighbors_durationSeconds": "{seconds}秒", "neighbors_durationMinutes": "{minutes}分{seconds}秒", - "neighbors_durationHours": "{hours}小时{minutes}分" + "neighbors_durationHours": "{hours}小时{minutes}分", + "scanner_getNodeTitle": "需要新节点吗?", + "scanner_getNodeBody": "钱包大小,运行 MeshCore,双频 GPS,防水,续航 5 天。", + "scanner_getNodeAction": "点此获取", + "scanner_getNodeDisclosure": "推广链接:每次购买都会支持 MeshCore Open。", + "networkMap_settingsSection": "网络地图", + "networkMap_uploadTitle": "分享我的电台收到的信息", + "networkMap_uploadExplanation": "开启后,当您的电台已连接时,应用会把电台收到的数据包的简要信息发送到 MeshCore Open 网络地图,让大家看到有哪些转发节点以及它们如何相连。发送内容包括每个数据包的类型、路由、跳数、信号强度和大小,以及转发节点自身广播中的名称和大致位置。绝不会发送消息内容、谁在和谁通信、频道名称、您的联系人或您的精确位置:位置会取整到约 2 公里,且应用每天都会使用新的随机 ID。", + "networkMap_whatWeCollect": "我们收集的内容", + "networkMap_promptTitle": "要帮助建设网络地图吗?", + "networkMap_promptBody": "MeshCore Open 可以把您的电台收到的信息分享到公开的网络地图 map.meshcoreopen.org,让大家看到有哪些转发节点以及它们如何相连。\n\n绝不会发送消息内容、谁在和谁通信、频道名称、您的联系人或您的精确位置。位置会取整到约 2 公里。", + "networkMap_promptSettingsHint": "您可以随时在 设置 → 应用设置 → 网络地图 中更改。", + "networkMap_promptAccept": "分享", + "networkMap_promptDecline": "不用了", + "networkMap_statusOff": "已关闭。不会发送任何内容。", + "networkMap_statusWaiting": "已开启。正在等待电台连接。", + "networkMap_statusNothingSent": "已开启。尚未发送任何内容。", + "networkMap_statusLastSent": "上次发送 {time}。今天 {count} 个数据包。", + "@networkMap_statusLastSent": { + "placeholders": { + "time": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "networkMap_sourceLocal": "本地", + "networkMap_sourceOnline": "在线", + "networkMap_sourceBoth": "两者", + "networkMap_zoomInHint": "放大以查看在线网络地图", + "networkMap_loadFailed": "无法加载在线网络地图", + "networkMap_inYourContacts": "在您的联系人中", + "networkMap_status": "状态", + "networkMap_statusActive": "最近一小时内活跃", + "networkMap_statusRecent": "最近一天内收到过", + "networkMap_statusStale": "近期未收到", + "networkMap_confirmed": "已确认", + "networkMap_singleSource": "单一来源,尚未确认", + "networkMap_reports": "报告", + "networkMap_locationEstimated": "大致位置,根据接收到它的节点估算", + "networkMap_locationAdvertised": "大致位置,来自其自身广播", + "networkMap_heardByRadio": "您的电台收到过", + "networkMap_inYourArea": "在您所在区域", + "networkMap_farAway": "距离太远,无法管理。", + "networkMap_addToContacts": "添加到联系人", + "networkMap_manage": "管理", + "networkMap_addedToContacts": "已添加到联系人", + "networkMap_addFailed": "无法添加到联系人", + "networkMap_unnamed": "未命名转发节点" } diff --git a/lib/main.dart b/lib/main.dart index f5f54751..430d63d7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -23,6 +23,7 @@ import 'services/storage_service.dart'; import 'services/message_retry_service.dart'; import 'services/path_history_service.dart'; import 'services/app_settings_service.dart'; +import 'services/network_map/network_map_upload_service.dart'; import 'services/notification_service.dart'; import 'services/ble_debug_log_service.dart'; import 'services/app_debug_log_service.dart'; @@ -164,6 +165,11 @@ void main() async { onImageSenderPrefix: (prefix) => imageReassembler.selfPrefix = prefix, ); + final networkMapUploadService = NetworkMapUploadService( + connector: connector, + settings: appSettingsService, + ); + await connector.loadContactCache(); await connector.loadChannelSettings(); await connector.loadCachedChannels(); @@ -189,6 +195,7 @@ void main() async { imageCodecService: imageCodecService, receivedImageStore: receivedImageStore, imageReassembler: imageReassembler, + networkMapUploadService: networkMapUploadService, ), ); } @@ -324,6 +331,7 @@ class MeshCoreApp extends StatefulWidget { final ImageCodecService imageCodecService; final ReceivedImageStore receivedImageStore; final ImageStreamReassembler imageReassembler; + final NetworkMapUploadService networkMapUploadService; const MeshCoreApp({ super.key, @@ -342,6 +350,7 @@ class MeshCoreApp extends StatefulWidget { required this.imageCodecService, required this.receivedImageStore, required this.imageReassembler, + required this.networkMapUploadService, }); @override @@ -424,6 +433,7 @@ class _MeshCoreAppState extends State with WidgetsBindingObserver { ChangeNotifierProvider.value(value: widget.timeoutPredictionService), ChangeNotifierProvider.value(value: widget.imageCodecService), ChangeNotifierProvider.value(value: widget.receivedImageStore), + ChangeNotifierProvider.value(value: widget.networkMapUploadService), ], child: Consumer( builder: (context, settingsService, child) { diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index ef954f28..b3632585 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -131,6 +131,12 @@ class AppSettings { final bool jumpToOldestUnread; final bool imageMessagesEnabled; + /// Opt-in upload of header-only packet records to the network map. + final bool networkMapUploadEnabled; + + /// Whether the one-time network map opt-in dialog has been shown. + final bool networkMapPromptShown; + /// Whether a received image is decoded as soon as it is reassembled. /// /// Off by default and deliberately so: a decode peaks around 2.16 GiB @@ -239,6 +245,8 @@ class AppSettings { this.tcpServerPort = 0, this.jumpToOldestUnread = false, this.imageMessagesEnabled = false, + this.networkMapUploadEnabled = false, + this.networkMapPromptShown = false, this.imageProcessAutomatically = false, this.imageCodecEnabled = false, this.imageCodecSelectedModelId, @@ -321,6 +329,8 @@ class AppSettings { 'tcp_server_port': tcpServerPort, 'jump_to_oldest_unread': jumpToOldestUnread, 'image_messages_enabled': imageMessagesEnabled, + 'network_map_upload_enabled': networkMapUploadEnabled, + 'network_map_prompt_shown': networkMapPromptShown, 'image_process_automatically': imageProcessAutomatically, 'image_codec_enabled': imageCodecEnabled, 'image_codec_selected_model_id': imageCodecSelectedModelId, @@ -428,6 +438,9 @@ class AppSettings { tcpServerPort: json['tcp_server_port'] as int? ?? 0, jumpToOldestUnread: json['jump_to_oldest_unread'] as bool? ?? false, imageMessagesEnabled: json['image_messages_enabled'] as bool? ?? false, + networkMapUploadEnabled: + json['network_map_upload_enabled'] as bool? ?? false, + networkMapPromptShown: json['network_map_prompt_shown'] as bool? ?? false, imageProcessAutomatically: json['image_process_automatically'] as bool? ?? false, imageCodecEnabled: json['image_codec_enabled'] as bool? ?? false, @@ -548,6 +561,8 @@ class AppSettings { int? tcpServerPort, bool? jumpToOldestUnread, bool? imageMessagesEnabled, + bool? networkMapUploadEnabled, + bool? networkMapPromptShown, bool? imageProcessAutomatically, bool? imageCodecEnabled, Object? imageCodecSelectedModelId = _unset, @@ -633,6 +648,10 @@ class AppSettings { tcpServerPort: tcpServerPort ?? this.tcpServerPort, jumpToOldestUnread: jumpToOldestUnread ?? this.jumpToOldestUnread, imageMessagesEnabled: imageMessagesEnabled ?? this.imageMessagesEnabled, + networkMapUploadEnabled: + networkMapUploadEnabled ?? this.networkMapUploadEnabled, + networkMapPromptShown: + networkMapPromptShown ?? this.networkMapPromptShown, imageProcessAutomatically: imageProcessAutomatically ?? this.imageProcessAutomatically, imageCodecEnabled: imageCodecEnabled ?? this.imageCodecEnabled, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 0570724a..4516731c 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -18,6 +18,7 @@ import '../widgets/cyr2lat_profile_dialog.dart'; import '../widgets/language_picker_sheet.dart'; import '../widgets/mesh_nav_tile.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/network_map_settings_section.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/translation_settings_section.dart'; import '../helpers/snack_bar_builder.dart'; @@ -99,6 +100,13 @@ class AppSettingsScreen extends StatelessWidget { child: _settingsCard(_buildMapContent), ), + // NETWORK MAP + SectionHeader(context.l10n.networkMap_settingsSection), + const MeshCard( + padding: EdgeInsets.zero, + child: NetworkMapSettingsSection(), + ), + // TRANSLATION (non-web only) if (!kIsWeb) ...[ SectionHeader(context.l10n.translation_title), diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 655f7af1..308ecdf1 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -24,6 +24,7 @@ import '../utils/route_transitions.dart'; import '../widgets/list_filter_widget.dart'; import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; +import '../widgets/network_map_opt_in_dialog.dart'; import '../widgets/qr_code_display.dart'; import '../widgets/quick_switch_bar.dart'; import '../widgets/sync_progress_overlay.dart'; @@ -66,6 +67,7 @@ class _ChannelsScreenState extends State WidgetsBinding.instance.addPostFrameCallback((_) { context.read().getChannels(); _loadCommunities(); + maybeShowNetworkMapOptInDialog(context); }); } diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index c6279c34..d2d74bb9 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -23,6 +23,8 @@ import '../services/app_settings_service.dart'; import '../services/path_history_service.dart'; import '../services/map_marker_service.dart'; import '../services/map_tile_cache_service.dart'; +import '../services/network_map/network_map_api_client.dart'; +import '../services/ui_view_state_service.dart'; import '../storage/prefs_manager.dart'; import '../utils/contact_search.dart'; import '../utils/disconnect_navigation_mixin.dart'; @@ -30,6 +32,7 @@ import '../utils/battery_utils.dart'; import '../utils/route_transitions.dart'; import '../widgets/map_poi_cluster.dart'; import '../widgets/marker_label_dialog.dart'; +import '../widgets/network_map_online_layer.dart'; import '../widgets/quick_switch_bar.dart'; import '../widgets/sync_progress_overlay.dart'; import '../icons/los_icon.dart'; @@ -80,6 +83,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { final MapController _mapController = MapController(); final MapMarkerService _markerService = MapMarkerService(); + final NetworkMapOnlineController _online = NetworkMapOnlineController(); final Set _hiddenMarkerIds = {}; Set _removedMarkerIds = {}; bool _isBuildingPathTrace = false; @@ -152,6 +156,8 @@ class _MapScreenState extends State with DisconnectNavigationMixin { @override void dispose() { _ageTimer?.cancel(); + _online.removeListener(_onOnlineChanged); + _online.dispose(); _saveLastCamera(); _searchController.dispose(); _searchFocus.dispose(); @@ -209,10 +215,49 @@ class _MapScreenState extends State with DisconnectNavigationMixin { }); } + void _onOnlineChanged() { + if (mounted) setState(() {}); + } + + bool _showsOnline(MapSourceOption source) => source != MapSourceOption.local; + + void _requestOnlineData() { + try { + _online.requestBounds(_mapController.camera.visibleBounds); + } catch (_) { + // Camera not ready yet; onMapReady requests once it is. + } + } + + void _setMapSource(MapSourceOption source) { + context.read().setMapSource(source); + if (_showsOnline(source)) { + _requestOnlineData(); + } else { + _online.cancel(); + } + } + + void _showOnlineRepeater( + BuildContext context, + MeshCoreConnector connector, + NetworkMapRepeater repeater, + ) { + showNetworkMapRepeaterSheet( + context, + connector: connector, + repeater: repeater, + onManage: (contact) => contact.type == advTypeRoom + ? _showRoomLogin(context, contact, manage: true) + : _showRepeaterLogin(context, contact), + ); + } + @override void initState() { super.initState(); _loadRemovedMarkers(); + _online.addListener(_onOnlineChanged); _ageTimer = Timer.periodic(const Duration(seconds: 60), (_) { if (mounted) setState(() {}); }); @@ -456,6 +501,11 @@ class _MapScreenState extends State with DisconnectNavigationMixin { final pathHistoryVersion = context.select( (service) => service.version, ); + final mapSource = context.select( + (service) => service.mapSource, + ); + final showLocal = mapSource != MapSourceOption.online; + final showOnline = _showsOnline(mapSource); final settingsService = context.read(); final pathHistory = context.read(); final tileCache = context.read(); @@ -834,10 +884,16 @@ class _MapScreenState extends State with DisconnectNavigationMixin { onSecondaryTap: (_, latLng) { _handleMapContextPress(context, connector, latLng); }, + onMapReady: () { + if (showOnline) _requestOnlineData(); + }, onMapEvent: (event) { if (event is MapEventMoveEnd || - event is MapEventFlingAnimationEnd) { + event is MapEventFlingAnimationEnd || + event is MapEventScrollWheelZoom || + event is MapEventDoubleTapZoomEnd) { _saveLastCamera(); + if (showOnline) _requestOnlineData(); } }, onPositionChanged: (camera, hasGesture) { @@ -860,6 +916,15 @@ class _MapScreenState extends State with DisconnectNavigationMixin { PolylineLayer(polylines: _polylines), if (sharedMarkerPolylines.isNotEmpty) PolylineLayer(polylines: sharedMarkerPolylines), + if (showOnline) + ...buildNetworkMapOnlineLayers( + controller: _online, + localMarkerKeys: showLocal + ? {for (final c in visibleContacts) c.publicKeyHex} + : const {}, + onTap: (repeater) => + _showOnlineRepeater(context, connector, repeater), + ), MarkerLayer( markers: [ if (highlightPosition != null) @@ -892,31 +957,33 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ), ), ), - if (!settings.mapShowOverlaps && + if (showLocal && + !settings.mapShowOverlaps && (_zoom >= _guessedZoomThreshold || _isBuildingPathTrace)) ..._buildGuessedMarker( guessedLocations, showLabels: _showNodeLabels, ), - ..._buildNodeMarkersCached( - visibleContacts, - settings, - connectorSnapshot.contactsSignature, - connectorSnapshot.batterySignature, - _freshness, - settings.mapTimeFilterHours, - settings.mapKeyPrefixEnabled, - settings.mapKeyPrefix, - settings.mapShowDiscoveryContacts, - Object.hashAllUnordered( - settings.batteryChemistryByRepeaterId.entries.map( - (entry) => Object.hash(entry.key, entry.value), + if (showLocal) + ..._buildNodeMarkersCached( + visibleContacts, + settings, + connectorSnapshot.contactsSignature, + connectorSnapshot.batterySignature, + _freshness, + settings.mapTimeFilterHours, + settings.mapKeyPrefixEnabled, + settings.mapKeyPrefix, + settings.mapShowDiscoveryContacts, + Object.hashAllUnordered( + settings.batteryChemistryByRepeaterId.entries.map( + (entry) => Object.hash(entry.key, entry.value), + ), ), + showLabels: _showNodeLabels, + selectedContact: selectedContact, ), - showLabels: _showNodeLabels, - selectedContact: selectedContact, - ), ..._buildPoiAndSelfMarkers( sharedMarkers, selfPosition: @@ -954,6 +1021,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { if (!_isBuildingPathTrace) _buildTopOverlay( context, + mapSource: mapSource, connector: connector, settingsService: settingsService, allContacts: allContacts, @@ -970,7 +1038,14 @@ class _MapScreenState extends State with DisconnectNavigationMixin { pinCount: sharedMarkers.length, ), if (_isBuildingPathTrace) _buildPathTraceOverlay(), - if (contactsWithLocation.isEmpty && + if (showOnline && + !_isBuildingPathTrace && + selectedContact == null && + (_online.state == NetworkMapLoadState.zoomIn || + _online.state == NetworkMapLoadState.error)) + _buildOnlineHint(context, _online.state) + else if (showLocal && + contactsWithLocation.isEmpty && selectedContact == null && !_isBuildingPathTrace) Positioned( @@ -1823,6 +1898,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { Widget _buildTopOverlay( BuildContext context, { + required MapSourceOption mapSource, required MeshCoreConnector connector, required AppSettingsService settingsService, required List allContacts, @@ -1945,6 +2021,8 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ], ), const SizedBox(height: 6), + _buildMapSourceSwitch(context, mapSource), + const SizedBox(height: 6), LayoutBuilder( builder: (context, constraints) { final chips = [ @@ -2028,6 +2106,76 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } + Widget _buildMapSourceSwitch(BuildContext context, MapSourceOption source) { + final l10n = context.l10n; + return Material( + color: _overlayPanelColor, + shape: StadiumBorder(side: BorderSide(color: _overlayBorderColor)), + clipBehavior: Clip.antiAlias, + child: SegmentedButton( + showSelectedIcon: false, + style: SegmentedButton.styleFrom( + minimumSize: const Size(0, 46), + side: BorderSide.none, + foregroundColor: _overlaySecondaryTextColor, + selectedForegroundColor: _overlayPrimaryTextColor, + selectedBackgroundColor: MapPalette.selected.withValues(alpha: 0.34), + textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w700), + ), + segments: [ + ButtonSegment( + value: MapSourceOption.local, + icon: const Icon(Icons.radio, size: 20), + label: Text(l10n.networkMap_sourceLocal), + ), + ButtonSegment( + value: MapSourceOption.online, + icon: const Icon(Icons.public, size: 20), + label: Text(l10n.networkMap_sourceOnline), + ), + ButtonSegment( + value: MapSourceOption.both, + icon: const Icon(Icons.layers, size: 20), + label: Text(l10n.networkMap_sourceBoth), + ), + ], + selected: {source}, + onSelectionChanged: (selection) { + HapticFeedback.selectionClick(); + _setMapSource(selection.first); + }, + ), + ); + } + + Widget _buildOnlineHint(BuildContext context, NetworkMapLoadState state) { + final zoomIn = state == NetworkMapLoadState.zoomIn; + return Positioned( + left: 16, + right: 88, + bottom: 16, + child: Card( + child: Padding( + padding: const EdgeInsets.all(14), + child: Row( + children: [ + Icon(zoomIn ? Icons.zoom_in : Icons.cloud_off, size: 26), + const SizedBox(width: 12), + Expanded( + child: Text( + zoomIn + ? context.l10n.networkMap_zoomInHint + : context.l10n.networkMap_loadFailed, + style: Theme.of(context).textTheme.bodyLarge, + ), + ), + ], + ), + ), + ), + ); + } + Widget _mapChip({ required String label, required bool selected, diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart index a1ecbed3..e621d059 100644 --- a/lib/screens/scanner_screen.dart +++ b/lib/screens/scanner_screen.dart @@ -13,6 +13,7 @@ import '../utils/app_logger.dart'; import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/device_tile.dart'; import '../widgets/empty_state.dart'; +import '../widgets/get_node_banner.dart'; import '../widgets/mesh_ui.dart'; import '../helpers/snack_bar_builder.dart'; import '../review_mode/review_mode_entry.dart'; @@ -168,6 +169,7 @@ class _ScannerScreenState extends State { }, ), ), + bottomNavigationBar: const GetNodeBanner(), floatingActionButton: Consumer( builder: (context, connector, child) { final isScanning = diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 5a810588..3cf9e7d9 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -317,6 +317,14 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(imageMessagesEnabled: value)); } + Future setNetworkMapUploadEnabled(bool value) async { + await updateSettings(_settings.copyWith(networkMapUploadEnabled: value)); + } + + Future setNetworkMapPromptShown(bool value) async { + await updateSettings(_settings.copyWith(networkMapPromptShown: value)); + } + /// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into /// `ReceivedImageStore.processAutomatically` on every settings change; the /// store applies it to future arrivals only, so flipping it does not diff --git a/lib/services/network_map/network_map_api_client.dart b/lib/services/network_map/network_map_api_client.dart new file mode 100644 index 00000000..7ba3cebb --- /dev/null +++ b/lib/services/network_map/network_map_api_client.dart @@ -0,0 +1,236 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:latlong2/latlong.dart'; + +const String networkMapBaseUrl = 'https://map.meshcoreopen.org'; + +/// Largest bbox span the read endpoints accept, in degrees. +const double networkMapMaxBboxSpan = 20.0; + +class NetworkMapBbox { + final double minLon; + final double minLat; + final double maxLon; + final double maxLat; + + const NetworkMapBbox({ + required this.minLon, + required this.minLat, + required this.maxLon, + required this.maxLat, + }); + + bool get isWithinLimit => + maxLon - minLon <= networkMapMaxBboxSpan && + maxLat - minLat <= networkMapMaxBboxSpan; + + String get query => [ + minLon, + minLat, + maxLon, + maxLat, + ].map((v) => v.toStringAsFixed(5)).join(','); +} + +/// An H3 cell as the server describes it. [boundary] is the open polygon +/// (usually six points), so clients need no H3 library. +class NetworkMapCell { + final String cell; + final LatLng center; + final List boundary; + + const NetworkMapCell({ + required this.cell, + required this.center, + required this.boundary, + }); + + factory NetworkMapCell.fromJson(Map json) { + return NetworkMapCell( + cell: json['cell'] as String, + center: LatLng( + (json['lat'] as num).toDouble(), + (json['lon'] as num).toDouble(), + ), + boundary: [ + for (final point in (json['boundary'] as List? ?? const [])) + LatLng( + ((point as List)[0] as num).toDouble(), + (point[1] as num).toDouble(), + ), + ], + ); + } +} + +enum NetworkMapRepeaterStatus { active, recent, stale } + +class NetworkMapRepeater { + final String key; + final String? name; + final int type; + final NetworkMapCell cell; + final String locationSource; + final double confidence; + final NetworkMapRepeaterStatus status; + final bool confirmed; + final int sightings; + final DateTime? firstSeen; + final DateTime? lastSeen; + + // Only present on the single-repeater endpoint. + final int? links; + final int? coverageCells; + final String? reachableArea; + + const NetworkMapRepeater({ + required this.key, + required this.name, + required this.type, + required this.cell, + required this.locationSource, + required this.confidence, + required this.status, + required this.confirmed, + required this.sightings, + required this.firstSeen, + required this.lastSeen, + this.links, + this.coverageCells, + this.reachableArea, + }); + + bool get isEstimated => locationSource == 'estimated'; + + factory NetworkMapRepeater.fromJson(Map json) { + return NetworkMapRepeater( + key: (json['key'] as String).toLowerCase(), + name: json['name'] as String?, + type: (json['type'] as num?)?.toInt() ?? 2, + cell: NetworkMapCell.fromJson(json['cell'] as Map), + locationSource: json['locationSource'] as String? ?? 'advert', + confidence: (json['confidence'] as num?)?.toDouble() ?? 0, + status: NetworkMapRepeaterStatus.values.firstWhere( + (s) => s.name == json['status'], + orElse: () => NetworkMapRepeaterStatus.stale, + ), + confirmed: json['confirmed'] as bool? ?? false, + sightings: (json['sightings'] as num?)?.toInt() ?? 0, + firstSeen: _parseTime(json['firstSeen']), + lastSeen: _parseTime(json['lastSeen']), + links: (json['links'] as num?)?.toInt(), + coverageCells: (json['coverageCells'] as num?)?.toInt(), + reachableArea: json['reachableArea'] as String?, + ); + } +} + +class NetworkMapLink { + final String a; + final String b; + final NetworkMapCell aCell; + final NetworkMapCell bCell; + final int packets; + final double? snr; + final bool confirmed; + + const NetworkMapLink({ + required this.a, + required this.b, + required this.aCell, + required this.bCell, + required this.packets, + required this.snr, + required this.confirmed, + }); + + factory NetworkMapLink.fromJson(Map json) { + return NetworkMapLink( + a: (json['a'] as String).toLowerCase(), + b: (json['b'] as String).toLowerCase(), + aCell: NetworkMapCell.fromJson(json['aCell'] as Map), + bCell: NetworkMapCell.fromJson(json['bCell'] as Map), + packets: (json['packets'] as num?)?.toInt() ?? 0, + snr: (json['snr'] as num?)?.toDouble(), + confirmed: json['confirmed'] as bool? ?? false, + ); + } +} + +DateTime? _parseTime(Object? value) => + value is String ? DateTime.tryParse(value) : null; + +class NetworkMapApiException implements Exception { + final int statusCode; + + const NetworkMapApiException(this.statusCode); + + @override + String toString() => 'NetworkMapApiException($statusCode)'; +} + +/// Read-only client for the network map. Viewing never requires the upload +/// opt-in and sends nothing about the radio. +class NetworkMapApiClient { + final http.Client _client; + final String baseUrl; + + NetworkMapApiClient({http.Client? client, this.baseUrl = networkMapBaseUrl}) + : _client = client ?? http.Client(); + + static const Duration _timeout = Duration(seconds: 20); + + Future> fetchRepeaters(NetworkMapBbox bbox) async { + final json = await _get('/v1/repeaters', { + 'bbox': bbox.query, + 'includeUnconfirmed': 'true', + }); + return [ + for (final item in (json['repeaters'] as List? ?? const [])) + NetworkMapRepeater.fromJson(item as Map), + ]; + } + + /// Null when the repeater is unknown or hidden (404). + Future fetchRepeater(String key) async { + try { + return NetworkMapRepeater.fromJson( + await _get('/v1/repeaters/${key.toLowerCase()}', const {}), + ); + } on NetworkMapApiException catch (e) { + if (e.statusCode == 404) return null; + rethrow; + } + } + + Future> fetchLinks( + NetworkMapBbox bbox, { + String window = '7d', + }) async { + final json = await _get('/v1/links', { + 'bbox': bbox.query, + 'window': window, + }); + return [ + for (final item in (json['links'] as List? ?? const [])) + NetworkMapLink.fromJson(item as Map), + ]; + } + + Future> _get( + String path, + Map query, + ) async { + final uri = Uri.parse( + '$baseUrl$path', + ).replace(queryParameters: query.isEmpty ? null : query); + final response = await _client.get(uri).timeout(_timeout); + if (response.statusCode != 200) { + throw NetworkMapApiException(response.statusCode); + } + return jsonDecode(utf8.decode(response.bodyBytes)) as Map; + } + + void close() => _client.close(); +} diff --git a/lib/services/network_map/network_map_gzip.dart b/lib/services/network_map/network_map_gzip.dart new file mode 100644 index 00000000..4645cdfc --- /dev/null +++ b/lib/services/network_map/network_map_gzip.dart @@ -0,0 +1,2 @@ +export 'network_map_gzip_stub.dart' + if (dart.library.io) 'network_map_gzip_io.dart'; diff --git a/lib/services/network_map/network_map_gzip_io.dart b/lib/services/network_map/network_map_gzip_io.dart new file mode 100644 index 00000000..8ce79773 --- /dev/null +++ b/lib/services/network_map/network_map_gzip_io.dart @@ -0,0 +1,3 @@ +import 'dart:io'; + +List? gzipEncode(List bytes) => gzip.encode(bytes); diff --git a/lib/services/network_map/network_map_gzip_stub.dart b/lib/services/network_map/network_map_gzip_stub.dart new file mode 100644 index 00000000..b5728f9e --- /dev/null +++ b/lib/services/network_map/network_map_gzip_stub.dart @@ -0,0 +1,2 @@ +/// No gzip on web; the server accepts an uncompressed body. +List? gzipEncode(List bytes) => null; diff --git a/lib/services/network_map/network_map_records.dart b/lib/services/network_map/network_map_records.dart new file mode 100644 index 00000000..aeefb432 --- /dev/null +++ b/lib/services/network_map/network_map_records.dart @@ -0,0 +1,414 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:cryptography/cryptography.dart'; + +import '../../connector/meshcore_protocol.dart'; +import '../../connector/raw_packet.dart'; +import '../../utils/location_grid.dart'; + +/// Records uploaded to the network map (see the server's API contract). +/// +/// Everything here is built from the packet header, path and signal values +/// only. Payloads, MACs, channel hashes, DM hashes, transport codes and exact +/// coordinates never make it into a record. + +const String hiddenNodeMarker = '\u{1F6AB}'; +const int _maxUploadPathBytes = 64; +const int _maxAdvertNameBytes = 32; +const int _advertPubKeySize = 32; +const int _advertSignatureSize = 64; +const int _maxAdvertDataSize = 32; + +class NetworkMapLoc { + final double lat; + final double lon; + + const NetworkMapLoc(this.lat, this.lon); + + factory NetworkMapLoc.snapped(double lat, double lon) { + final snapped = snapToLocationGrid(lat, lon); + return NetworkMapLoc(snapped.lat, snapped.lon); + } + + Map toJson() => {'lat': lat, 'lon': lon}; +} + +class NetworkMapPreset { + final int freqKhz; + final double bwKhz; + final int sf; + final int cr; + + const NetworkMapPreset({ + required this.freqKhz, + required this.bwKhz, + required this.sf, + required this.cr, + }); + + static const List _allowedBwKhz = [ + 7.8, + 10.4, + 15.6, + 20.8, + 31.25, + 41.7, + 62.5, + 125, + 250, + 500, + ]; + + /// From the radio's self-info values; null when any is missing or outside + /// what the server accepts. Firmware reports frequency in kHz, bandwidth in + /// Hz and coding rate as 1–4 or 5–8. + static NetworkMapPreset? fromRadio({ + int? freqKhz, + int? bwHz, + int? sf, + int? cr, + }) { + if (freqKhz == null || bwHz == null || sf == null || cr == null) { + return null; + } + final bwKhz = _allowedBwKhz.where((bw) => (bw * 1000 - bwHz).abs() < 1); + final codingRate = cr <= 4 ? cr + 4 : cr; + if (freqKhz < 100000 || + freqKhz > 1100000 || + bwKhz.isEmpty || + sf < 5 || + sf > 12 || + codingRate < 5 || + codingRate > 8) { + return null; + } + return NetworkMapPreset( + freqKhz: freqKhz, + bwKhz: bwKhz.first, + sf: sf, + cr: codingRate, + ); + } + + Map toJson() => { + 'freqKhz': freqKhz, + 'bwKhz': bwKhz, + 'sf': sf, + 'cr': cr, + }; +} + +class NetworkMapPacketRecord { + final int t; + final int pt; + final int rt; + final int hw; + final String path; + final double snr; + final int rssi; + final int size; + final String h; + final bool scoped; + + const NetworkMapPacketRecord({ + required this.t, + required this.pt, + required this.rt, + required this.hw, + required this.path, + required this.snr, + required this.rssi, + required this.size, + required this.h, + required this.scoped, + }); + + Map toJson() => { + 't': t, + 'pt': pt, + 'rt': rt, + 'hw': hw, + 'path': path, + 'snr': snr, + 'rssi': rssi, + 'size': size, + 'h': h, + 'scoped': scoped, + }; +} + +class NetworkMapAdvertRecord { + final int t; + final String key; + final int type; + final String? name; + final NetworkMapLoc? loc; + final bool hidden; + final double snr; + final int rssi; + final int rt; + final int hw; + final String path; + + const NetworkMapAdvertRecord({ + required this.t, + required this.key, + required this.type, + required this.name, + required this.loc, + required this.hidden, + required this.snr, + required this.rssi, + required this.rt, + required this.hw, + required this.path, + }); + + Map toJson() => { + 't': t, + 'key': key, + 'type': type, + 'name': name, + 'loc': loc?.toJson(), + 'hidden': hidden, + 'snr': snr, + 'rssi': rssi, + 'rt': rt, + 'hw': hw, + 'path': path, + }; +} + +/// Header, path and signal fields of a `PUSH_CODE_LOG_RX_DATA` frame. +class _RxFrame { + final double snr; + final int rssi; + final int rawLength; + final int routeType; + final int payloadType; + final int hashWidth; + final Uint8List pathBytes; + final Uint8List payload; + + _RxFrame({ + required this.snr, + required this.rssi, + required this.rawLength, + required this.routeType, + required this.payloadType, + required this.hashWidth, + required this.pathBytes, + required this.payload, + }); + + bool get scoped => routeType == 0 || routeType == 3; + + String get pathHex => _hex(pathBytes); +} + +_RxFrame? _parseRxFrame(Uint8List frame) { + if (frame.isEmpty || frame[0] != pushCodeLogRxData) return null; + try { + final reader = BufferReader(frame); + reader.skipBytes(1); + final snr = reader.readInt8() / 4.0; + final rssi = reader.readInt8(); + final rawLength = reader.remaining; + final header = reader.readByte(); + final routeType = header & 0x03; + final payloadType = (header >> 2) & 0x0F; + if (routeType == 0 || routeType == 3) { + reader.skipBytes(4); // transport codes: never uploaded + } + final pathLenRaw = reader.readByte(); + final hashWidth = decodePathHashWidth(pathLenRaw); + final pathBytes = reader.readBytes(decodePathByteLen(pathLenRaw)); + final payload = reader.readBytes(reader.remaining); + if (hashWidth > 3 || pathBytes.length > _maxUploadPathBytes) return null; + return _RxFrame( + snr: snr.clamp(-32.0, 32.0).toDouble(), + rssi: rssi.clamp(-200, 0).toInt(), + rawLength: rawLength, + routeType: routeType, + payloadType: payloadType, + hashWidth: hashWidth, + pathBytes: pathBytes, + payload: payload, + ); + } catch (_) { + return null; + } +} + +/// Unix seconds rounded down to the minute. +int networkMapMinute(DateTime time) { + final seconds = time.millisecondsSinceEpoch ~/ 1000; + return seconds - seconds % 60; +} + +/// Raw packet length rounded up to a multiple of 16, capped at 256. +int roundUpPacketSize(int length) { + final rounded = ((length + 15) ~/ 16) * 16; + return rounded > 256 ? 256 : rounded; +} + +/// Header-only packet record for a received 0x88 frame, or null when the +/// frame is malformed or outside what the server accepts. +NetworkMapPacketRecord? buildPacketRecord( + Uint8List frame, + DateTime receivedAt, +) { + final rx = _parseRxFrame(frame); + if (rx == null) return null; + return NetworkMapPacketRecord( + t: networkMapMinute(receivedAt), + pt: rx.payloadType, + rt: rx.routeType, + hw: rx.hashWidth, + path: rx.pathHex, + snr: rx.snr, + rssi: rx.rssi, + size: roundUpPacketSize(rx.rawLength), + h: computePacketHash(rx.payloadType, rx.payload), + scoped: rx.scoped, + ); +} + +/// Advert record for a received repeater or room server advert whose Ed25519 +/// signature verifies. Chat and sensor adverts, unsigned or malformed adverts +/// and anything that isn't an advert return null. +Future buildAdvertRecord( + Uint8List frame, + DateTime receivedAt, +) async { + final rx = _parseRxFrame(frame); + if (rx == null || rx.payloadType != payloadTypeADVERT) return null; + final payload = rx.payload; + const appDataStart = _advertPubKeySize + 4 + _advertSignatureSize; + if (payload.length <= appDataStart) return null; + + final appData = payload.sublist(appDataStart); + final flags = appData[0]; + final type = flags & 0x0F; + if (type != advTypeRepeater && type != advTypeRoom) return null; + + final publicKey = payload.sublist(0, _advertPubKeySize); + if (!await _verifyAdvertSignature(payload, publicKey)) return null; + + // Same layout as the firmware's AdvertDataParser. + var i = 1; + NetworkMapLoc? loc; + if (flags & 0x10 != 0) { + if (appData.length < i + 8) return null; + final view = ByteData.sublistView(appData); + final lat = view.getInt32(i, Endian.little) / 1e6; + final lon = view.getInt32(i + 4, Endian.little) / 1e6; + i += 8; + if (_isPlausibleLocation(lat, lon)) loc = NetworkMapLoc.snapped(lat, lon); + } + if (flags & 0x20 != 0) i += 2; + if (flags & 0x40 != 0) i += 2; + String? name; + if (flags & 0x80 != 0 && appData.length > i) { + var nameBytes = appData.sublist(i); + final nul = nameBytes.indexOf(0); + if (nul >= 0) nameBytes = nameBytes.sublist(0, nul); + final decoded = utf8.decode(nameBytes, allowMalformed: true); + if (decoded.isNotEmpty) name = decoded; + } + + final hidden = name != null && name.contains(hiddenNodeMarker); + return NetworkMapAdvertRecord( + t: networkMapMinute(receivedAt), + key: _hex(publicKey), + type: type, + name: hidden || name == null + ? null + : _truncateUtf8(name, _maxAdvertNameBytes), + loc: hidden ? null : loc, + hidden: hidden, + snr: rx.snr, + rssi: rx.rssi, + rt: rx.routeType, + hw: rx.hashWidth, + path: rx.pathHex, + ); +} + +/// The firmware signs pubkey ‖ timestamp ‖ app_data (app_data capped at +/// MAX_ADVERT_DATA_SIZE), see Mesh::createAdvert. +Future _verifyAdvertSignature( + Uint8List payload, + Uint8List publicKey, +) async { + const sigStart = _advertPubKeySize + 4; + const appDataStart = sigStart + _advertSignatureSize; + var appDataEnd = payload.length; + if (appDataEnd - appDataStart > _maxAdvertDataSize) { + appDataEnd = appDataStart + _maxAdvertDataSize; + } + final message = [ + ...payload.sublist(0, sigStart), + ...payload.sublist(appDataStart, appDataEnd), + ]; + try { + return await Ed25519().verify( + message, + signature: Signature( + payload.sublist(sigStart, appDataStart), + publicKey: SimplePublicKey(publicKey, type: KeyPairType.ed25519), + ), + ); + } catch (_) { + return false; + } +} + +bool _isPlausibleLocation(double lat, double lon) { + const epsilon = 1e-6; + return (lat.abs() > epsilon || lon.abs() > epsilon) && + lat >= -90 && + lat <= 90 && + lon >= -180 && + lon <= 180; +} + +String _truncateUtf8(String value, int maxBytes) { + if (utf8.encode(value).length <= maxBytes) return value; + final buffer = StringBuffer(); + var used = 0; + for (final rune in value.runes) { + final char = String.fromCharCode(rune); + final length = utf8.encode(char).length; + if (used + length > maxBytes) break; + buffer.write(char); + used += length; + } + return buffer.toString(); +} + +String _hex(List bytes) => + bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); + +/// The `POST /v1/upload` body. Field names and nesting follow the contract +/// exactly; the server rejects unknown fields. +Map buildUploadBody({ + required String installId, + required String app, + required NetworkMapLoc? loc, + required NetworkMapPreset? preset, + required int listenSeconds, + required List packets, + required List adverts, +}) => { + 'v': 1, + 'installId': installId, + 'token': null, + 'app': app, + 'loc': loc?.toJson(), + 'preset': preset?.toJson(), + 'listenSeconds': listenSeconds.clamp(0, 600), + 'packets': [for (final p in packets) p.toJson()], + 'adverts': [for (final a in adverts) a.toJson()], +}; diff --git a/lib/services/network_map/network_map_upload_service.dart b/lib/services/network_map/network_map_upload_service.dart new file mode 100644 index 00000000..54dae384 --- /dev/null +++ b/lib/services/network_map/network_map_upload_service.dart @@ -0,0 +1,389 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:math'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../connector/meshcore_connector.dart'; +import '../../connector/meshcore_protocol.dart'; +import '../../storage/prefs_manager.dart'; +import '../../utils/app_logger.dart'; +import '../app_settings_service.dart'; +import 'network_map_api_client.dart'; +import 'network_map_gzip.dart'; +import 'network_map_records.dart'; + +/// Random per-install identifier, regenerated every 24 h and never derived +/// from the radio key. +class NetworkMapInstallId { + static const _keyId = 'network_map_install_id'; + static const _keyCreatedAt = 'network_map_install_id_created_at'; + static const Duration lifetime = Duration(hours: 24); + + final SharedPreferences _prefs; + final DateTime Function() _now; + final Random _random; + + NetworkMapInstallId(this._prefs, {DateTime Function()? now, Random? random}) + : _now = now ?? DateTime.now, + _random = random ?? Random.secure(); + + String current() { + final now = _now(); + final id = _prefs.getString(_keyId); + final createdMs = _prefs.getInt(_keyCreatedAt); + if (id != null && createdMs != null) { + final age = now.difference( + DateTime.fromMillisecondsSinceEpoch(createdMs), + ); + if (!age.isNegative && age < lifetime) return id; + } + final bytes = Uint8List.fromList( + List.generate(16, (_) => _random.nextInt(256)), + ); + final fresh = base64Url.encode(bytes).replaceAll('=', ''); + unawaited(_prefs.setString(_keyId, fresh)); + unawaited(_prefs.setInt(_keyCreatedAt, now.millisecondsSinceEpoch)); + return fresh; + } +} + +class _Queued { + final DateTime queuedAt; + final T record; + + _Queued(this.queuedAt, this.record); +} + +/// Records waiting for upload, with the contract's batch caps and age limit. +class NetworkMapUploadQueue { + static const int maxPacketsPerBatch = 2000; + static const int maxAdvertsPerBatch = 200; + static const Duration maxQueueAge = Duration(hours: 1); + + /// The server drops records more than 65 min old, so anything past an hour + /// is not worth sending. + static const Duration maxRecordAge = Duration(minutes: 60); + + // Bounds memory if uploads keep failing for the full hour. + static const int _maxQueuedPackets = maxPacketsPerBatch * 5; + + final List<_Queued> _packets = []; + final List<_Queued> _adverts = []; + + bool get isEmpty => _packets.isEmpty && _adverts.isEmpty; + int get packetCount => _packets.length; + int get advertCount => _adverts.length; + + void addPacket(NetworkMapPacketRecord record, DateTime now) { + _packets.add(_Queued(now, record)); + if (_packets.length > _maxQueuedPackets) _packets.removeAt(0); + } + + void addAdvert(NetworkMapAdvertRecord record, DateTime now) { + // Only the latest advert per key is useful within one batch window. + _adverts.removeWhere((q) => q.record.key == record.key); + _adverts.add(_Queued(now, record)); + } + + void dropExpired(DateTime now) { + final cutoffSeconds = networkMapMinute(now.subtract(maxRecordAge)); + bool expired(DateTime queuedAt, int t) => + now.difference(queuedAt) > maxQueueAge || t < cutoffSeconds; + _packets.removeWhere((q) => expired(q.queuedAt, q.record.t)); + _adverts.removeWhere((q) => expired(q.queuedAt, q.record.t)); + } + + void clear() { + _packets.clear(); + _adverts.clear(); + } + + /// The oldest records up to the per-batch caps. They stay queued until + /// [remove] confirms the upload. + ({List packets, List adverts}) + peekBatch() => ( + packets: [for (final q in _packets.take(maxPacketsPerBatch)) q.record], + adverts: [for (final q in _adverts.take(maxAdvertsPerBatch)) q.record], + ); + + void remove(int packets, int adverts) { + _packets.removeRange(0, min(packets, _packets.length)); + _adverts.removeRange(0, min(adverts, _adverts.length)); + } +} + +/// Opt-in uploader for the network map. +/// +/// Listens to raw RX log frames only while the user has opted in and a radio +/// is connected, and uploads header-only records in batches. +class NetworkMapUploadService extends ChangeNotifier { + static const Duration uploadInterval = Duration(seconds: 60); + static const Duration heartbeatInterval = Duration(minutes: 5); + static const Duration maxBackoff = Duration(minutes: 15); + static const int _maxJitterMs = 10000; + + static const _keySentDay = 'network_map_sent_day'; + static const _keySentCount = 'network_map_sent_count'; + static const _keyLastUpload = 'network_map_last_upload'; + + final MeshCoreConnector _connector; + final AppSettingsService _settings; + final http.Client _client; + final String baseUrl; + final Random _random = Random(); + final NetworkMapUploadQueue _queue = NetworkMapUploadQueue(); + + StreamSubscription? _frameSub; + Timer? _timer; + bool _uploading = false; + int _failures = 0; + Duration _retryAfter = Duration.zero; + Duration _nextInterval = uploadInterval; + DateTime? _listenMark; + int _listenSeconds = 0; + DateTime? _lastUploadAt; + DateTime? _lastAttemptAt; + int _packetsSentToday = 0; + String? _appId; + + NetworkMapUploadService({ + required MeshCoreConnector connector, + required AppSettingsService settings, + http.Client? client, + this.baseUrl = networkMapBaseUrl, + }) : _connector = connector, + _settings = settings, + _client = client ?? http.Client() { + _loadStatus(); + _connector.addListener(_sync); + _settings.addListener(_sync); + _sync(); + } + + bool get enabled => _settings.settings.networkMapUploadEnabled; + + /// True while frames are being collected. + bool get isActive => _frameSub != null; + DateTime? get lastUploadAt => _lastUploadAt; + int get packetsSentToday { + final prefs = PrefsManager.instance; + return prefs.getString(_keySentDay) == _dayKey(DateTime.now()) + ? _packetsSentToday + : 0; + } + + Future setEnabled(bool value) => + _settings.setNetworkMapUploadEnabled(value); + + void _loadStatus() { + final prefs = PrefsManager.instance; + final lastMs = prefs.getInt(_keyLastUpload); + if (lastMs != null) { + _lastUploadAt = DateTime.fromMillisecondsSinceEpoch(lastMs); + } + _packetsSentToday = prefs.getInt(_keySentCount) ?? 0; + } + + void _sync() { + if (!enabled) _queue.clear(); + // The store-review demo radio is simulated; its traffic must not reach + // the real map. + final shouldListen = + enabled && _connector.isConnected && !_connector.isReviewMode; + if (shouldListen == isActive) return; + if (shouldListen) { + _frameSub = _connector.receivedFrames.listen(_onFrame); + _listenMark = DateTime.now(); + _lastAttemptAt ??= DateTime.now(); + _schedule(uploadInterval); + } else { + _accrueListenTime(); + _listenMark = null; + unawaited(_frameSub?.cancel()); + _frameSub = null; + _timer?.cancel(); + _timer = null; + } + notifyListeners(); + } + + void _onFrame(Uint8List frame) { + if (frame.isEmpty || frame[0] != pushCodeLogRxData) return; + final now = DateTime.now(); + final packet = buildPacketRecord(frame, now); + if (packet == null) return; + _queue.addPacket(packet, now); + if (packet.pt == payloadTypeADVERT) { + unawaited( + buildAdvertRecord(frame, now).then((advert) { + if (advert != null && isActive) _queue.addAdvert(advert, now); + }), + ); + } + } + + void _accrueListenTime() { + final mark = _listenMark; + if (mark == null) return; + final now = DateTime.now(); + _listenSeconds += now.difference(mark).inSeconds; + _listenMark = now; + } + + void _schedule(Duration base) { + _timer?.cancel(); + final jitter = Duration(milliseconds: _random.nextInt(_maxJitterMs + 1)); + _timer = Timer(base + jitter, _tick); + } + + Future _tick() async { + if (!isActive || _uploading) return; + final now = DateTime.now(); + _queue.dropExpired(now); + final sinceLast = now.difference(_lastAttemptAt ?? now); + if (_queue.isEmpty && sinceLast < heartbeatInterval) { + _schedule(_nextInterval); + return; + } + await _upload(); + if (isActive) { + _schedule(_failures == 0 ? _nextInterval : _backoffDelay); + } + } + + Duration get _backoffDelay { + final exp = uploadInterval * pow(2, _failures - 1).toInt(); + final delay = exp > maxBackoff ? maxBackoff : exp; + return _retryAfter > delay ? _retryAfter : delay; + } + + Future _upload() async { + _uploading = true; + _lastAttemptAt = DateTime.now(); + try { + _accrueListenTime(); + final batch = _queue.peekBatch(); + final lat = _connector.selfLatitude; + final lon = _connector.selfLongitude; + final hasPosition = + lat != null && + lon != null && + (lat.abs() > 1e-6 || lon.abs() > 1e-6) && + lat.abs() <= 90 && + lon.abs() <= 180; + final body = buildUploadBody( + installId: NetworkMapInstallId(PrefsManager.instance).current(), + app: await _appString(), + loc: hasPosition ? NetworkMapLoc.snapped(lat, lon) : null, + preset: NetworkMapPreset.fromRadio( + freqKhz: _connector.currentFreqHz, + bwHz: _connector.currentBwHz, + sf: _connector.currentSf, + cr: _connector.currentCr, + ), + listenSeconds: min(_listenSeconds, 600), + packets: batch.packets, + adverts: batch.adverts, + ); + final jsonBytes = utf8.encode(jsonEncode(body)); + final gzipped = gzipEncode(jsonBytes); + final response = await _client + .post( + Uri.parse('$baseUrl/v1/upload'), + headers: { + 'Content-Type': 'application/json', + if (gzipped != null) 'Content-Encoding': 'gzip', + }, + body: gzipped ?? jsonBytes, + ) + .timeout(const Duration(seconds: 30)); + final status = response.statusCode; + if (status == 202 || status == 200) { + _queue.remove(batch.packets.length, batch.adverts.length); + _onUploaded(batch.packets.length, response.body); + } else if (status == 429 || status >= 500) { + _onFailed(response.headers['retry-after'], response.body); + } else { + // 400/413/415: resending the same batch can never succeed. + appLogger.warn( + 'Network map upload rejected ($status): ${response.body}', + tag: 'NetworkMap', + ); + _queue.remove(batch.packets.length, batch.adverts.length); + _listenSeconds = 0; + _failures = 0; + } + } catch (e) { + appLogger.warn('Network map upload failed: $e', tag: 'NetworkMap'); + _onFailed(null, null); + } finally { + _uploading = false; + notifyListeners(); + } + } + + void _onUploaded(int packetCount, String body) { + final now = DateTime.now(); + _failures = 0; + _retryAfter = Duration.zero; + _listenSeconds = 0; + _lastUploadAt = now; + _nextInterval = uploadInterval; + try { + final next = (jsonDecode(body) as Map)['nextUploadSeconds']; + if (next is num && next >= 30 && next <= 900) { + _nextInterval = Duration(seconds: next.toInt()); + } + } catch (_) {} + + final prefs = PrefsManager.instance; + final today = _dayKey(now); + if (prefs.getString(_keySentDay) != today) _packetsSentToday = 0; + _packetsSentToday += packetCount; + unawaited(prefs.setString(_keySentDay, today)); + unawaited(prefs.setInt(_keySentCount, _packetsSentToday)); + unawaited(prefs.setInt(_keyLastUpload, now.millisecondsSinceEpoch)); + } + + void _onFailed(String? retryAfterHeader, String? body) { + _failures++; + var retryAfter = int.tryParse(retryAfterHeader?.trim() ?? ''); + if (retryAfter == null && body != null) { + try { + final value = (jsonDecode(body) as Map)['retryAfterSeconds']; + if (value is num) retryAfter = value.toInt(); + } catch (_) {} + } + _retryAfter = retryAfter == null + ? Duration.zero + : Duration(seconds: min(retryAfter, maxBackoff.inSeconds)); + } + + Future _appString() async { + if (_appId != null) return _appId!; + var version = ''; + try { + version = (await PackageInfo.fromPlatform()).version; + } catch (_) {} + final cleaned = version.replaceAll(RegExp(r'[^\x21-\x7E]'), ''); + final id = cleaned.isEmpty ? 'meshcore-open' : 'meshcore-open/$cleaned'; + return _appId = id.length > 64 ? id.substring(0, 64) : id; + } + + static String _dayKey(DateTime time) => + '${time.year}-${time.month}-${time.day}'; + + @override + void dispose() { + _connector.removeListener(_sync); + _settings.removeListener(_sync); + _timer?.cancel(); + unawaited(_frameSub?.cancel()); + _client.close(); + super.dispose(); + } +} diff --git a/lib/services/ui_view_state_service.dart b/lib/services/ui_view_state_service.dart index 7f2a03af..46ae0a3b 100644 --- a/lib/services/ui_view_state_service.dart +++ b/lib/services/ui_view_state_service.dart @@ -9,6 +9,10 @@ const String contactsAllGroupsValue = '__all__'; enum ChannelSortOption { manual, name, latestMessages, unread } +/// Which nodes the map draws: the radio's own contacts, the online network +/// map, or both. +enum MapSourceOption { local, online, both } + class UiViewStateService extends ChangeNotifier { static const _keyContactsSelectedGroupName = 'ui_contacts_selected_group'; static const _keyContactsSortOption = 'ui_contacts_sort_option'; @@ -16,6 +20,7 @@ class UiViewStateService extends ChangeNotifier { static const _keyContactsTypeFilter = 'ui_contacts_type_filter'; static const _keyChannelsSortOption = 'ui_channels_sort_option'; static const _keyChannelsSortIndexLegacy = 'ui_channels_sort_index'; + static const _keyMapSource = 'ui_map_source'; String _contactsSelectedGroupName = contactsAllGroupsValue; String _contactsSearchText = ''; @@ -26,6 +31,7 @@ class UiViewStateService extends ChangeNotifier { String _channelsSearchText = ''; ChannelSortOption _channelsSortOption = ChannelSortOption.manual; + MapSourceOption _mapSource = MapSourceOption.local; String get contactsSelectedGroupName => _contactsSelectedGroupName; String get contactsSearchText => _contactsSearchText; @@ -35,6 +41,7 @@ class UiViewStateService extends ChangeNotifier { ContactTypeFilter get contactsTypeFilter => _contactsTypeFilter; String get channelsSearchText => _channelsSearchText; ChannelSortOption get channelsSortOption => _channelsSortOption; + MapSourceOption get mapSource => _mapSource; Future initialize() async { final prefs = PrefsManager.instance; @@ -63,6 +70,14 @@ class UiViewStateService extends ChangeNotifier { ); } + final mapSourceStr = prefs.getString(_keyMapSource); + if (mapSourceStr != null) { + _mapSource = MapSourceOption.values.firstWhere( + (e) => e.name == mapSourceStr, + orElse: () => MapSourceOption.local, + ); + } + final channelSortStr = prefs.getString(_keyChannelsSortOption); if (channelSortStr != null) { _channelsSortOption = ChannelSortOption.values.firstWhere( @@ -151,4 +166,11 @@ class UiViewStateService extends ChangeNotifier { PrefsManager.instance.setString(_keyChannelsSortOption, value.name), ); } + + void setMapSource(MapSourceOption value) { + if (_mapSource == value) return; + _mapSource = value; + notifyListeners(); + unawaited(PrefsManager.instance.setString(_keyMapSource, value.name)); + } } diff --git a/lib/utils/location_grid.dart b/lib/utils/location_grid.dart new file mode 100644 index 00000000..5769c820 --- /dev/null +++ b/lib/utils/location_grid.dart @@ -0,0 +1,22 @@ +import 'dart:math' as math; + +/// Grid spacing in degrees (~2.2 km north–south). Shared with the network map +/// server, which rejects any uploaded coordinate that is not a grid center. +const double locationGridSize = 0.02; + +/// Snaps a coordinate to the center of its network-map grid cell. +/// +/// Every coordinate that leaves the phone goes through this. The algorithm is +/// fixed by the network map API contract; snapping a center returns the same +/// center. +({double lat, double lon}) snapToLocationGrid(double lat, double lon) { + const g = locationGridSize; + final latIdx = (lat / g).floor(); + final latC = ((latIdx + 0.5) * g).clamp(-89.99, 89.99).toDouble(); + final step = g / math.max(math.cos(latC * math.pi / 180), 0.1); + final lonIdx = ((lon + 180) / step).floor(); + final lonC = -180 + (lonIdx + 0.5) * step; + return (lat: _round6(latC), lon: _round6(lonC)); +} + +double _round6(double value) => (value * 1e6).round() / 1e6; diff --git a/lib/widgets/get_node_banner.dart b/lib/widgets/get_node_banner.dart new file mode 100644 index 00000000..5060ae72 --- /dev/null +++ b/lib/widgets/get_node_banner.dart @@ -0,0 +1,98 @@ +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../l10n/l10n.dart'; +import '../theme/mesh_theme.dart'; + +/// Affiliate link for the SenseCAP MeshTracker X1. +const getNodeUrl = + 'https://www.seeedstudio.com/sensecap-meshtracker-x1-meshtastic-gps-tracker-p-6935.html' + '?sensecap_affiliate=JFWID0g&referring_service=link'; + +/// Bottom banner on the connect screen pointing new users at a node to buy. +class GetNodeBanner extends StatelessWidget { + const GetNodeBanner({super.key}); + + void _open() => + launchUrl(Uri.parse(getNodeUrl), mode: LaunchMode.externalApplication); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + + return SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 4, 12, 12), + child: Material( + color: scheme.primaryContainer, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + side: BorderSide(color: scheme.primary.withValues(alpha: 0.4)), + ), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: _open, + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Icon( + Icons.router_outlined, + size: 28, + color: scheme.onPrimaryContainer, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + l10n.scanner_getNodeTitle, + style: textTheme.titleMedium?.copyWith( + color: scheme.onPrimaryContainer, + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + l10n.scanner_getNodeBody, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onPrimaryContainer, + height: 1.35, + ), + ), + const SizedBox(height: 10), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: _open, + icon: const Icon(Icons.shopping_cart_outlined, size: 22), + label: Text(l10n.scanner_getNodeAction), + ), + ), + const SizedBox(height: 6), + Center( + child: Text( + l10n.scanner_getNodeDisclosure, + textAlign: TextAlign.center, + style: textTheme.bodySmall?.copyWith( + color: scheme.onPrimaryContainer.withValues(alpha: 0.8), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/network_map_online_layer.dart b/lib/widgets/network_map_online_layer.dart new file mode 100644 index 00000000..750bbc58 --- /dev/null +++ b/lib/widgets/network_map_online_layer.dart @@ -0,0 +1,493 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import '../services/network_map/network_map_api_client.dart'; +import '../theme/mesh_theme.dart'; +import 'mesh_ui.dart'; + +enum NetworkMapLoadState { idle, loading, ready, zoomIn, error } + +/// Fetches the online network map for the visible area. +/// +/// Requests are debounced while the map moves; a response that arrives after +/// a newer request started is dropped. +class NetworkMapOnlineController extends ChangeNotifier { + static const Duration _debounce = Duration(milliseconds: 600); + + final NetworkMapApiClient _client; + final LayerHitNotifier hitNotifier = ValueNotifier(null); + + List _repeaters = const []; + List _links = const []; + NetworkMapLoadState _state = NetworkMapLoadState.idle; + Timer? _timer; + int _generation = 0; + bool _disposed = false; + + NetworkMapOnlineController({NetworkMapApiClient? client}) + : _client = client ?? NetworkMapApiClient(); + + List get repeaters => _repeaters; + List get links => _links; + NetworkMapLoadState get state => _state; + + void requestBounds(LatLngBounds bounds) { + _timer?.cancel(); + _timer = Timer(_debounce, () => _load(bounds)); + } + + /// Drops any pending or in-flight request (the online layer was hidden). + void cancel() { + _timer?.cancel(); + _generation++; + } + + Future _load(LatLngBounds bounds) async { + final bbox = NetworkMapBbox( + minLon: bounds.west.clamp(-180.0, 180.0), + minLat: bounds.south.clamp(-90.0, 90.0), + maxLon: bounds.east.clamp(-180.0, 180.0), + maxLat: bounds.north.clamp(-90.0, 90.0), + ); + final generation = ++_generation; + if (!bbox.isWithinLimit) { + _setState(NetworkMapLoadState.zoomIn); + return; + } + _setState(NetworkMapLoadState.loading); + try { + final results = await Future.wait([ + _client.fetchRepeaters(bbox), + _client.fetchLinks(bbox), + ]); + if (_disposed || generation != _generation) return; + _repeaters = results[0] as List; + _links = results[1] as List; + _setState(NetworkMapLoadState.ready); + } catch (_) { + if (_disposed || generation != _generation) return; + _setState(NetworkMapLoadState.error); + } + } + + void _setState(NetworkMapLoadState value) { + _state = value; + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _timer?.cancel(); + hitNotifier.dispose(); + _client.close(); + super.dispose(); + } +} + +Color networkMapStatusColor(NetworkMapRepeaterStatus status) { + return switch (status) { + NetworkMapRepeaterStatus.active => MapPalette.online, + NetworkMapRepeaterStatus.recent => MapPalette.stale, + NetworkMapRepeaterStatus.stale => MapPalette.offline, + }; +} + +/// Map layers for the online network: links, repeater hexagons and a +/// tappable center marker so small cells stay visible when zoomed out. +/// +/// Keys in [localMarkerKeys] are already drawn by the local layer, so only +/// their hexagon outline is added. +List buildNetworkMapOnlineLayers({ + required NetworkMapOnlineController controller, + required Set localMarkerKeys, + required ValueChanged onTap, +}) { + final repeaters = controller.repeaters; + return [ + PolylineLayer( + polylines: [ + for (final link in controller.links) + Polyline( + points: [link.aCell.center, link.bCell.center], + strokeWidth: link.confirmed ? 3.5 : 2.5, + color: MapPalette.router.withValues( + alpha: link.confirmed ? 0.85 : 0.6, + ), + borderStrokeWidth: 1, + borderColor: MapPalette.markerOutline.withValues(alpha: 0.7), + pattern: link.confirmed + ? const StrokePattern.solid() + : StrokePattern.dashed(segments: const [10, 8]), + ), + ], + ), + GestureDetector( + onTap: () { + final hits = controller.hitNotifier.value?.hitValues; + if (hits != null && hits.isNotEmpty) onTap(hits.first); + }, + child: PolygonLayer( + hitNotifier: controller.hitNotifier, + polygons: [ + for (final repeater in repeaters) + if (repeater.cell.boundary.length >= 3) + Polygon( + points: repeater.cell.boundary, + hitValue: repeater, + color: localMarkerKeys.contains(repeater.key) + ? null + : networkMapStatusColor( + repeater.status, + ).withValues(alpha: 0.22), + borderColor: networkMapStatusColor(repeater.status), + borderStrokeWidth: 2.5, + pattern: repeater.confirmed + ? const StrokePattern.solid() + : StrokePattern.dashed(segments: const [8, 6]), + ), + ], + ), + ), + MarkerLayer( + markers: [ + for (final repeater in repeaters) + if (!localMarkerKeys.contains(repeater.key)) + Marker( + point: repeater.cell.center, + width: 34, + height: 34, + child: GestureDetector( + onTap: () => onTap(repeater), + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: networkMapStatusColor(repeater.status), + border: Border.all( + color: MapPalette.markerOutline, + width: 2.5, + ), + boxShadow: const [ + BoxShadow( + color: MapPalette.markerShadow, + blurRadius: 6, + offset: Offset(0, 2), + ), + ], + ), + child: Icon( + repeater.type == advTypeRoom + ? Icons.meeting_room + : Icons.router, + color: MapPalette.markerOutline, + size: 20, + ), + ), + ), + ), + ], + ), + ]; +} + +enum NetworkMapReach { heard, nearby, far } + +/// Distance under which a repeater counts as "in your area". +const double networkMapNearbyKm = 50; + +NetworkMapReach networkMapReachFor({ + required bool heardByRadio, + required LatLng? self, + required LatLng cell, +}) { + if (heardByRadio) return NetworkMapReach.heard; + if (self != null && + const Distance().as(LengthUnit.Kilometer, self, cell) <= + networkMapNearbyKm) { + return NetworkMapReach.nearby; + } + return NetworkMapReach.far; +} + +/// Details for a repeater from the online map, with "Add to contacts" and +/// "Manage". [onManage] runs the regular login → repeater hub flow. +Future showNetworkMapRepeaterSheet( + BuildContext context, { + required MeshCoreConnector connector, + required NetworkMapRepeater repeater, + required void Function(Contact contact) onManage, +}) { + return showMeshSheet( + context, + builder: (sheetContext) => _NetworkMapRepeaterSheet( + connector: connector, + repeater: repeater, + onManage: (contact) { + Navigator.pop(sheetContext); + onManage(contact); + }, + ), + ); +} + +class _NetworkMapRepeaterSheet extends StatefulWidget { + final MeshCoreConnector connector; + final NetworkMapRepeater repeater; + final void Function(Contact contact) onManage; + + const _NetworkMapRepeaterSheet({ + required this.connector, + required this.repeater, + required this.onManage, + }); + + @override + State<_NetworkMapRepeaterSheet> createState() => + _NetworkMapRepeaterSheetState(); +} + +class _NetworkMapRepeaterSheetState extends State<_NetworkMapRepeaterSheet> { + static const Duration _recentlyHeard = Duration(hours: 24); + bool _busy = false; + + NetworkMapRepeater get _repeater => widget.repeater; + + Contact? get _savedContact => + widget.connector.getContactByPubKeyHex(_repeater.key); + + bool get _heardByRadio { + if (_savedContact != null) return true; + final cutoff = DateTime.now().subtract(_recentlyHeard); + return widget.connector.discoveredContacts.any( + (c) => c.publicKeyHex == _repeater.key && c.lastSeen.isAfter(cutoff), + ); + } + + /// The saved contact, adding it first if needed. Null (with a message) when + /// it cannot be added. + Future _ensureContact() async { + final existing = _savedContact; + if (existing != null) return existing; + final connector = widget.connector; + final l10n = context.l10n; + if (!connector.isConnected) { + _snack(l10n.settings_notConnectedError); + return null; + } + if (connector.contactsStorageFull || + connector.contacts.length >= connector.maxContacts) { + _snack(l10n.contacts_storageFull); + return null; + } + // Flood route, no location (the cell is only an approximation) and an + // unknown advert time so the firmware's replay guard accepts the next + // real advert. + final contact = Contact( + publicKey: hexToPubKey(_repeater.key), + name: _repeater.name ?? _repeater.key.substring(0, 8), + type: _repeater.type, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0, isUtc: true), + ); + setState(() => _busy = true); + final ok = await connector.importDiscoveredContact(contact); + if (!mounted) return null; + setState(() => _busy = false); + if (!ok) { + _snack(l10n.networkMap_addFailed); + return null; + } + return _savedContact ?? contact; + } + + void _snack(String message) { + showDismissibleSnackBar(context, content: Text(message)); + } + + Future _add() async { + final contact = await _ensureContact(); + if (contact != null && mounted) { + _snack(context.l10n.networkMap_addedToContacts); + } + } + + Future _manage() async { + final contact = await _ensureContact(); + if (contact != null && mounted) widget.onManage(contact); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + final repeater = _repeater; + final inContacts = _savedContact != null; + final statusColor = networkMapStatusColor(repeater.status); + final selfLat = widget.connector.selfLatitude; + final selfLon = widget.connector.selfLongitude; + final reach = networkMapReachFor( + heardByRadio: _heardByRadio, + self: selfLat != null && selfLon != null && (selfLat != 0 || selfLon != 0) + ? LatLng(selfLat, selfLon) + : null, + cell: repeater.cell.center, + ); + final (reachLabel, reachColor, reachIcon) = switch (reach) { + NetworkMapReach.heard => ( + l10n.networkMap_heardByRadio, + MapPalette.online, + Icons.hearing, + ), + NetworkMapReach.nearby => ( + l10n.networkMap_inYourArea, + MapPalette.selected, + Icons.near_me, + ), + NetworkMapReach.far => ( + l10n.networkMap_farAway, + MapPalette.stale, + Icons.warning_amber_rounded, + ), + }; + final statusLabel = switch (repeater.status) { + NetworkMapRepeaterStatus.active => l10n.networkMap_statusActive, + NetworkMapRepeaterStatus.recent => l10n.networkMap_statusRecent, + NetworkMapRepeaterStatus.stale => l10n.networkMap_statusStale, + }; + final lastSeen = repeater.lastSeen; + + Widget row(String label, String value) => Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Text( + value, + style: textTheme.bodyLarge?.copyWith(color: scheme.onSurface), + ), + ], + ), + ); + + return SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + BottomSheetHeader( + title: repeater.name ?? l10n.networkMap_unnamed, + subtitle: repeater.type == advTypeRoom + ? l10n.contact_typeRoom + : l10n.contact_typeRepeater, + trailing: Icon( + repeater.type == advTypeRoom + ? Icons.meeting_room + : Icons.router, + color: statusColor, + size: 26, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + StatusChip( + label: reachLabel, + color: reachColor, + icon: reachIcon, + fontSize: 15, + ), + if (inContacts) + StatusChip( + label: l10n.networkMap_inYourContacts, + color: MapPalette.repeater, + icon: Icons.check_circle, + fontSize: 15, + ), + ], + ), + const SizedBox(height: 8), + row(l10n.networkMap_status, statusLabel), + row( + l10n.networkMap_reports, + repeater.confirmed + ? l10n.networkMap_confirmed + : l10n.networkMap_singleSource, + ), + if (lastSeen != null) + row( + l10n.map_lastSeen, + networkMapTimeAgo(context, lastSeen), + ), + row( + l10n.map_location, + repeater.isEstimated + ? l10n.networkMap_locationEstimated + : l10n.networkMap_locationAdvertised, + ), + const SizedBox(height: 16), + if (!inContacts) ...[ + SizedBox( + width: double.infinity, + child: FilledButton.tonalIcon( + onPressed: _busy ? null : _add, + icon: const Icon(Icons.person_add_alt_1, size: 22), + label: Text(l10n.networkMap_addToContacts), + ), + ), + const SizedBox(height: 10), + ], + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: _busy ? null : _manage, + icon: const Icon(Icons.admin_panel_settings, size: 22), + label: Text(l10n.networkMap_manage), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +/// "Just now", "5m ago", "3h ago", "2d ago". +String networkMapTimeAgo(BuildContext context, DateTime time) { + final l10n = context.l10n; + final difference = DateTime.now().difference(time); + if (difference.inSeconds < 60) return l10n.time_justNow; + if (difference.inMinutes < 60) { + return l10n.time_minutesAgo(difference.inMinutes); + } + if (difference.inHours < 24) return l10n.time_hoursAgo(difference.inHours); + return l10n.time_daysAgo(difference.inDays); +} diff --git a/lib/widgets/network_map_opt_in_dialog.dart b/lib/widgets/network_map_opt_in_dialog.dart new file mode 100644 index 00000000..0b84b8e9 --- /dev/null +++ b/lib/widgets/network_map_opt_in_dialog.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../services/app_settings_service.dart'; +import '../services/network_map/network_map_api_client.dart'; + +/// Asks once whether to share what the radio hears with the network map. +/// +/// Shows nothing when uploading is already on, the prompt was shown before, +/// or the app is in review mode. The prompt counts as shown as soon as it +/// opens, so dismissing it never brings it back. +Future maybeShowNetworkMapOptInDialog(BuildContext context) async { + final settingsService = context.read(); + final connector = context.read(); + final settings = settingsService.settings; + if (settings.networkMapPromptShown || + settings.networkMapUploadEnabled || + connector.isReviewMode || + !connector.isConnected) { + return; + } + + await settingsService.setNetworkMapPromptShown(true); + if (!context.mounted) return; + + final accepted = await showDialog( + context: context, + builder: (dialogContext) => const _NetworkMapOptInDialog(), + ); + if (accepted == true) { + await settingsService.setNetworkMapUploadEnabled(true); + } +} + +class _NetworkMapOptInDialog extends StatelessWidget { + const _NetworkMapOptInDialog(); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final textTheme = Theme.of(context).textTheme; + final scheme = Theme.of(context).colorScheme; + + return AlertDialog( + icon: Icon(Icons.public, size: 36, color: scheme.primary), + title: Text(l10n.networkMap_promptTitle), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.networkMap_promptBody, + style: textTheme.bodyLarge?.copyWith(height: 1.4), + ), + const SizedBox(height: 12), + Text( + l10n.networkMap_promptSettingsHint, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + height: 1.4, + ), + ), + const SizedBox(height: 4), + Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton.icon( + style: TextButton.styleFrom(padding: EdgeInsets.zero), + icon: const Icon(Icons.open_in_new, size: 20), + label: Text(l10n.networkMap_whatWeCollect), + onPressed: () => launchUrl( + Uri.parse('$networkMapBaseUrl/privacy'), + mode: LaunchMode.externalApplication, + ), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text(l10n.networkMap_promptDecline), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: Text(l10n.networkMap_promptAccept), + ), + ], + ); + } +} diff --git a/lib/widgets/network_map_settings_section.dart b/lib/widgets/network_map_settings_section.dart new file mode 100644 index 00000000..f7c0d91d --- /dev/null +++ b/lib/widgets/network_map_settings_section.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../l10n/l10n.dart'; +import '../services/network_map/network_map_api_client.dart'; +import '../services/network_map/network_map_upload_service.dart'; +import 'mesh_nav_tile.dart'; +import 'network_map_online_layer.dart'; + +/// Opt-in toggle, plain-language explanation and status for network map +/// uploads. +class NetworkMapSettingsSection extends StatelessWidget { + const NetworkMapSettingsSection({super.key}); + + @override + Widget build(BuildContext context) { + final service = context.watch(); + final l10n = context.l10n; + final textTheme = Theme.of(context).textTheme; + final scheme = Theme.of(context).colorScheme; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.public, size: 24), + title: Text(l10n.networkMap_uploadTitle), + subtitle: Text(_status(context, service)), + value: service.enabled, + onChanged: service.setEnabled, + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), + child: Text( + l10n.networkMap_uploadExplanation, + style: textTheme.bodyMedium?.copyWith( + color: scheme.onSurface, + height: 1.4, + ), + ), + ), + const Divider(height: 1, indent: 16), + MeshNavTile( + icon: Icons.privacy_tip_outlined, + title: l10n.networkMap_whatWeCollect, + trailing: const Icon(Icons.open_in_new, size: 22), + showChevron: false, + onTap: () => launchUrl( + Uri.parse('$networkMapBaseUrl/privacy'), + mode: LaunchMode.externalApplication, + ), + ), + ], + ); + } + + String _status(BuildContext context, NetworkMapUploadService service) { + final l10n = context.l10n; + if (!service.enabled) return l10n.networkMap_statusOff; + final last = service.lastUploadAt; + if (last != null) { + return l10n.networkMap_statusLastSent( + networkMapTimeAgo(context, last), + service.packetsSentToday, + ); + } + if (!service.isActive) return l10n.networkMap_statusWaiting; + return l10n.networkMap_statusNothingSent; + } +} diff --git a/test/services/network_map/network_map_api_client_test.dart b/test/services/network_map/network_map_api_client_test.dart new file mode 100644 index 00000000..8492ef41 --- /dev/null +++ b/test/services/network_map/network_map_api_client_test.dart @@ -0,0 +1,191 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/services/network_map/network_map_api_client.dart'; + +const _cell = { + 'cell': '872830828ffffff', + 'lat': 33.45, + 'lon': -112.08, + 'boundary': [ + [33.46, -112.09], + [33.45, -112.07], + [33.44, -112.07], + [33.43, -112.08], + [33.44, -112.10], + [33.45, -112.10], + ], +}; + +final _repeater = { + 'key': 'AB' * 32, + 'name': 'Hilltop RPT', + 'type': 2, + 'cell': _cell, + 'locationSource': 'advert', + 'confidence': 1.0, + 'status': 'active', + 'confirmed': true, + 'sightings': 14, + 'firstSeen': '2026-10-01T12:00:00Z', + 'lastSeen': '2026-10-11T18:41:00Z', +}; + +const _bbox = NetworkMapBbox( + minLon: -113, + minLat: 33, + maxLon: -112, + maxLat: 34, +); + +void main() { + test('parses repeaters and sends bbox', () async { + late Uri requested; + final client = NetworkMapApiClient( + client: MockClient((request) async { + requested = request.url; + return http.Response( + jsonEncode({ + 'repeaters': [ + _repeater, + { + ..._repeater, + 'key': 'cd' * 32, + 'name': null, + 'type': 3, + 'locationSource': 'estimated', + 'confidence': 0.4, + 'status': 'stale', + 'confirmed': false, + }, + ], + }), + 200, + ); + }), + ); + final repeaters = await client.fetchRepeaters(_bbox); + expect(requested.path, '/v1/repeaters'); + expect(requested.host, 'map.meshcoreopen.org'); + expect( + requested.queryParameters['bbox'], + '-113.00000,33.00000,-112.00000,34.00000', + ); + expect(requested.queryParameters['includeUnconfirmed'], 'true'); + + expect(repeaters, hasLength(2)); + final first = repeaters.first; + expect(first.key, 'ab' * 32); + expect(first.name, 'Hilltop RPT'); + expect(first.type, 2); + expect(first.cell.cell, '872830828ffffff'); + expect(first.cell.center.latitude, 33.45); + expect(first.cell.boundary, hasLength(6)); + expect(first.cell.boundary.first.latitude, 33.46); + expect(first.cell.boundary.first.longitude, -112.09); + expect(first.status, NetworkMapRepeaterStatus.active); + expect(first.confirmed, isTrue); + expect(first.isEstimated, isFalse); + expect(first.sightings, 14); + expect(first.lastSeen, DateTime.utc(2026, 10, 11, 18, 41)); + + final second = repeaters.last; + expect(second.name, isNull); + expect(second.type, 3); + expect(second.isEstimated, isTrue); + expect(second.status, NetworkMapRepeaterStatus.stale); + expect(second.confirmed, isFalse); + }); + + test('parses a single repeater and treats 404 as unknown', () async { + final client = NetworkMapApiClient( + client: MockClient((request) async { + if (request.url.path.endsWith('ab' * 32)) { + return http.Response( + jsonEncode({ + ..._repeater, + 'links': 4, + 'coverageCells': 12, + 'reachableArea': '852830bffffffff', + }), + 200, + ); + } + return http.Response('{"error":"not_found"}', 404); + }), + ); + final repeater = (await client.fetchRepeater('AB' * 32))!; + expect(repeater.links, 4); + expect(repeater.coverageCells, 12); + expect(repeater.reachableArea, '852830bffffffff'); + expect(await client.fetchRepeater('ef' * 32), isNull); + }); + + test('parses links', () async { + late Uri requested; + final client = NetworkMapApiClient( + client: MockClient((request) async { + requested = request.url; + return http.Response( + jsonEncode({ + 'links': [ + { + 'a': 'ab' * 32, + 'b': 'cd' * 32, + 'aCell': _cell, + 'bCell': _cell, + 'packets': 120, + 'snr': 6.5, + 'confirmed': true, + }, + { + 'a': 'ab' * 32, + 'b': 'ef' * 32, + 'aCell': _cell, + 'bCell': _cell, + 'packets': 3, + 'snr': null, + 'confirmed': false, + }, + ], + }), + 200, + ); + }), + ); + final links = await client.fetchLinks(_bbox, window: '24h'); + expect(requested.path, '/v1/links'); + expect(requested.queryParameters['window'], '24h'); + expect(links, hasLength(2)); + expect(links.first.packets, 120); + expect(links.first.snr, 6.5); + expect(links.first.confirmed, isTrue); + expect(links.first.aCell.boundary, hasLength(6)); + expect(links.last.snr, isNull); + }); + + test('errors surface the status code', () async { + final client = NetworkMapApiClient( + client: MockClient((_) async => http.Response('bad', 400)), + ); + expect( + () => client.fetchRepeaters(_bbox), + throwsA(isA()), + ); + }); + + test('bbox limit is 20 degrees per side', () { + expect(_bbox.isWithinLimit, isTrue); + expect( + const NetworkMapBbox( + minLon: -130, + minLat: 30, + maxLon: -105, + maxLat: 40, + ).isWithinLimit, + isFalse, + ); + }); +} diff --git a/test/services/network_map/network_map_records_test.dart b/test/services/network_map/network_map_records_test.dart new file mode 100644 index 00000000..441f09f4 --- /dev/null +++ b/test/services/network_map/network_map_records_test.dart @@ -0,0 +1,378 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:cryptography/cryptography.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/connector/raw_packet.dart'; +import 'package:meshcore_open/services/network_map/network_map_records.dart'; + +const _packetFields = { + 't', + 'pt', + 'rt', + 'hw', + 'path', + 'snr', + 'rssi', + 'size', + 'h', + 'scoped', +}; + +const _advertFields = { + 't', + 'key', + 'type', + 'name', + 'loc', + 'hidden', + 'snr', + 'rssi', + 'rt', + 'hw', + 'path', +}; + +final _receivedAt = DateTime.utc(2026, 10, 11, 18, 41, 37); +const _transportCodes = [0xDE, 0xAD, 0xBE, 0xEF]; + +String _hex(List bytes) => + bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); + +/// `[0x88][snr*4][rssi][header][transport?][path_len][path][payload]`. +Uint8List _rxFrame({ + required int payloadType, + int routeType = 1, + int snrQuarters = 29, + int rssi = -92, + int pathLenRaw = 0, + List path = const [], + required List payload, +}) { + return Uint8List.fromList([ + pushCodeLogRxData, + snrQuarters & 0xFF, + rssi & 0xFF, + (payloadType << 2) | routeType, + if (routeType == 0 || routeType == 3) ..._transportCodes, + pathLenRaw, + ...path, + ...payload, + ]); +} + +/// Payload whose every 3-byte window is distinctive, so any leak of it into +/// a record would show up as a substring. +List _secretPayload(int length) => + List.generate(length, (i) => (0x5A + i * 37) & 0xFF); + +Future> _signedAdvertPayload({ + required SimpleKeyPair keyPair, + required int type, + double? lat, + double? lon, + String? name, + bool corruptSignature = false, +}) async { + final publicKey = (await keyPair.extractPublicKey()).bytes; + final timestamp = [0x10, 0x20, 0x30, 0x40]; + var flags = type; + final appData = []; + if (lat != null && lon != null) { + flags |= 0x10; + final loc = ByteData(8) + ..setInt32(0, (lat * 1e6).round(), Endian.little) + ..setInt32(4, (lon * 1e6).round(), Endian.little); + appData.addAll(loc.buffer.asUint8List()); + } + if (name != null) { + flags |= 0x80; + appData.addAll(utf8.encode(name)); + } + appData.insert(0, flags); + final signature = await Ed25519().sign([ + ...publicKey, + ...timestamp, + ...appData, + ], keyPair: keyPair); + final sigBytes = List.from(signature.bytes); + if (corruptSignature) sigBytes[10] ^= 0x01; + return [...publicKey, ...timestamp, ...sigBytes, ...appData]; +} + +void main() { + group('packet records', () { + test('every payload type yields header-only fields', () { + for (var pt = 0; pt < 16; pt++) { + for (final rt in [0, 1, 2, 3]) { + final payload = _secretPayload(40); + final frame = _rxFrame( + payloadType: pt, + routeType: rt, + pathLenRaw: 0x42, // 2 hops, 2-byte hashes + path: const [0xA1, 0xA2, 0xB1, 0xB2], + payload: payload, + ); + final record = buildPacketRecord(frame, _receivedAt)!; + final json = record.toJson(); + expect(json.keys.toSet(), _packetFields); + expect(json['pt'], pt); + expect(json['rt'], rt); + expect(json['hw'], 2); + expect(json['path'], 'a1a2b1b2'); + expect(json['scoped'], rt == 0 || rt == 3); + expect(json['h'], computePacketHash(pt, Uint8List.fromList(payload))); + + // Nothing outside the hash may carry payload or transport bytes. + final withoutHash = jsonEncode({...json}..remove('h')); + expect(withoutHash, isNot(contains('dead'))); + expect(withoutHash, isNot(contains('beef'))); + for (var i = 0; i + 3 <= payload.length; i++) { + expect( + withoutHash, + isNot(contains(_hex(payload.sublist(i, i + 3)))), + ); + } + } + } + }); + + test('group text: channel hash and MAC never appear', () { + // [channel_hash][MAC x2][ciphertext] + final payload = [0x7C, 0x3E, 0x91, ..._secretPayload(32)]; + final record = buildPacketRecord( + _rxFrame(payloadType: payloadTypeGRPTXT, payload: payload), + _receivedAt, + )!; + final json = jsonEncode(record.toJson()..remove('h')); + expect(json, isNot(contains('7c'))); + expect(json, isNot(contains('3e91'))); + expect(record.path, ''); + }); + + test('direct message: source and destination hashes never appear', () { + // [dest_hash][src_hash][MAC x2][ciphertext] + final payload = [0xD7, 0x5C, 0x11, 0x22, ..._secretPayload(24)]; + final record = buildPacketRecord( + _rxFrame( + payloadType: payloadTypeTXTMSG, + routeType: 2, + payload: payload, + ), + _receivedAt, + )!; + final json = jsonEncode(record.toJson()..remove('h')); + expect(json, isNot(contains('d7'))); + expect(json, isNot(contains('5c'))); + }); + + test('snr is reported in quarter-dB steps and rssi passes through', () { + final record = buildPacketRecord( + _rxFrame(payloadType: 2, snrQuarters: -23, rssi: -110, payload: [1]), + _receivedAt, + )!; + expect(record.snr, -5.75); + expect(record.rssi, -110); + }); + + test('t is rounded down to the minute', () { + final record = buildPacketRecord( + _rxFrame(payloadType: 2, payload: [1]), + _receivedAt, + )!; + expect(record.t % 60, 0); + expect( + record.t, + DateTime.utc(2026, 10, 11, 18, 41).millisecondsSinceEpoch ~/ 1000, + ); + }); + + test('size is the raw packet length rounded up to 16', () { + expect(roundUpPacketSize(0), 0); + expect(roundUpPacketSize(1), 16); + expect(roundUpPacketSize(16), 16); + expect(roundUpPacketSize(17), 32); + expect(roundUpPacketSize(48), 48); + expect(roundUpPacketSize(49), 64); + expect(roundUpPacketSize(255), 256); + + // header + path_len + 30 payload bytes = 32 raw bytes. + final record = buildPacketRecord( + _rxFrame(payloadType: 2, payload: _secretPayload(30)), + _receivedAt, + )!; + expect(record.size, 32); + final scoped = buildPacketRecord( + _rxFrame(payloadType: 2, routeType: 0, payload: _secretPayload(30)), + _receivedAt, + )!; + expect(scoped.size, 48); // + 4 transport bytes = 36 + }); + + test('hash matches the firmware packet hash', () { + final payload = Uint8List.fromList(_secretPayload(20)); + final digest = crypto.sha256.convert([5, ...payload]).bytes; + final record = buildPacketRecord( + _rxFrame(payloadType: 5, payload: payload), + _receivedAt, + )!; + expect(record.h, _hex(digest.sublist(0, 8))); + expect(record.h, computePacketHash(5, payload)); + expect(RegExp(r'^[0-9a-f]{16}$').hasMatch(record.h), isTrue); + }); + + test('unsupported hash width, oversized path and other frames dropped', () { + // Hash width code 3 -> 4-byte hashes. + expect( + buildPacketRecord( + _rxFrame( + payloadType: 2, + pathLenRaw: 0xC1, + path: const [1, 2, 3, 4], + payload: [1], + ), + _receivedAt, + ), + isNull, + ); + // 22 hops of 3 bytes = 66 bytes > 64. + expect( + buildPacketRecord( + _rxFrame( + payloadType: 2, + pathLenRaw: 0x80 | 22, + path: List.filled(66, 7), + payload: [1], + ), + _receivedAt, + ), + isNull, + ); + expect( + buildPacketRecord(Uint8List.fromList([0x80, 1, 2, 3]), _receivedAt), + isNull, + ); + expect( + buildPacketRecord( + Uint8List.fromList([pushCodeLogRxData, 1]), + _receivedAt, + ), + isNull, + ); + }); + }); + + group('advert records', () { + late SimpleKeyPair keyPair; + late String keyHex; + + setUpAll(() async { + keyPair = await Ed25519().newKeyPairFromSeed(List.filled(32, 7)); + keyHex = _hex((await keyPair.extractPublicKey()).bytes); + }); + + Future advertFrame({ + required int type, + double? lat, + double? lon, + String? name, + bool corrupt = false, + }) async { + return _rxFrame( + payloadType: payloadTypeADVERT, + pathLenRaw: 0x01, + path: const [0xA1], + payload: await _signedAdvertPayload( + keyPair: keyPair, + type: type, + lat: lat, + lon: lon, + name: name, + corruptSignature: corrupt, + ), + ); + } + + test('verified repeater advert: snapped location, name, key', () async { + final frame = await advertFrame( + type: advTypeRepeater, + lat: 33.448376, + lon: -112.074036, + name: 'Hilltop RPT', + ); + final advert = (await buildAdvertRecord(frame, _receivedAt))!; + final json = advert.toJson(); + expect(json.keys.toSet(), _advertFields); + expect(json['key'], keyHex); + expect(json['type'], 2); + expect(json['name'], 'Hilltop RPT'); + expect(json['loc'], {'lat': 33.45, 'lon': -112.080261}); + expect(json['hidden'], false); + expect(json['snr'], 7.25); + expect(json['rssi'], -92); + expect(json['rt'], 1); + expect(json['hw'], 1); + expect(json['path'], 'a1'); + expect(json['t'] % 60, 0); + // Exact coordinates never leave the phone. + expect(jsonEncode(json), isNot(contains('448376'))); + + // The same frame still produces a header-only packet record. + expect(buildPacketRecord(frame, _receivedAt)!.pt, payloadTypeADVERT); + }); + + test('room server adverts are uploaded too', () async { + final frame = await advertFrame(type: advTypeRoom, name: 'Room'); + final advert = (await buildAdvertRecord(frame, _receivedAt))!; + expect(advert.type, 3); + expect(advert.loc, isNull); + }); + + test('chat and sensor adverts are packet records only', () async { + for (final type in [advTypeChat, advTypeSensor]) { + final frame = await advertFrame( + type: type, + lat: 47.6, + lon: -122.3, + name: 'Alice', + ); + expect(await buildAdvertRecord(frame, _receivedAt), isNull); + final packet = buildPacketRecord(frame, _receivedAt)!; + final json = jsonEncode(packet.toJson()); + expect(json, isNot(contains(keyHex.substring(0, 6)))); + expect(json, isNot(contains('Alice'))); + } + }); + + test('names containing the no-entry sign are hidden', () async { + final frame = await advertFrame( + type: advTypeRepeater, + lat: 47.6, + lon: -122.3, + name: 'Secret \u{1F6AB}', + ); + final advert = (await buildAdvertRecord(frame, _receivedAt))!; + final json = advert.toJson(); + expect(json['hidden'], true); + expect(json['name'], isNull); + expect(json['loc'], isNull); + expect(json['key'], keyHex); + }); + + test('adverts with a bad signature are dropped', () async { + final frame = await advertFrame( + type: advTypeRepeater, + name: 'Forged', + corrupt: true, + ); + expect(await buildAdvertRecord(frame, _receivedAt), isNull); + }); + + test('non-advert packets never produce adverts', () async { + final frame = _rxFrame(payloadType: 5, payload: _secretPayload(120)); + expect(await buildAdvertRecord(frame, _receivedAt), isNull); + }); + }); +} diff --git a/test/services/network_map/network_map_upload_service_test.dart b/test/services/network_map/network_map_upload_service_test.dart new file mode 100644 index 00000000..db7c0efe --- /dev/null +++ b/test/services/network_map/network_map_upload_service_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('off by default and never listens without a connected radio', () async { + final connector = MeshCoreConnector(); + final settings = AppSettingsService(); + await settings.loadSettings(); + var requests = 0; + final service = NetworkMapUploadService( + connector: connector, + settings: settings, + client: MockClient((_) async { + requests++; + return http.Response('{}', 202); + }), + ); + addTearDown(() { + service.dispose(); + connector.dispose(); + }); + + expect(service.enabled, isFalse); + expect(service.isActive, isFalse); + + await service.setEnabled(true); + expect(service.enabled, isTrue); + expect(settings.settings.networkMapUploadEnabled, isTrue); + expect(service.isActive, isFalse); + expect(service.lastUploadAt, isNull); + expect(service.packetsSentToday, 0); + expect(requests, 0); + }); +} diff --git a/test/services/network_map/network_map_upload_test.dart b/test/services/network_map/network_map_upload_test.dart new file mode 100644 index 00000000..9e0baba3 --- /dev/null +++ b/test/services/network_map/network_map_upload_test.dart @@ -0,0 +1,216 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/network_map/network_map_records.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +NetworkMapPacketRecord _packet(int t) => NetworkMapPacketRecord( + t: t, + pt: 5, + rt: 1, + hw: 1, + path: 'a1b2c3', + snr: 7.25, + rssi: -92, + size: 48, + h: '0123456789abcdef', + scoped: false, +); + +NetworkMapAdvertRecord _advert(int t, String key) => NetworkMapAdvertRecord( + t: t, + key: key, + type: 2, + name: 'Hilltop RPT', + loc: const NetworkMapLoc(33.47, -112.068234), + hidden: false, + snr: 9.5, + rssi: -80, + rt: 1, + hw: 1, + path: 'a1', +); + +void main() { + group('upload body', () { + test('matches the contract field-for-field', () { + final body = buildUploadBody( + installId: 'AAAAAAAAAAAAAAAAAAAAAA', + app: 'meshcore-open/9.5.0', + loc: NetworkMapLoc.snapped(33.448376, -112.074036), + preset: NetworkMapPreset.fromRadio( + freqKhz: 910525, + bwHz: 62500, + sf: 7, + cr: 5, + ), + listenSeconds: 60, + packets: [_packet(1791770400)], + adverts: [_advert(1791770400, 'ab' * 32)], + ); + final decoded = + jsonDecode(jsonEncode(body)) as Map; // round trip + expect(decoded, { + 'v': 1, + 'installId': 'AAAAAAAAAAAAAAAAAAAAAA', + 'token': null, + 'app': 'meshcore-open/9.5.0', + 'loc': {'lat': 33.45, 'lon': -112.080261}, + 'preset': {'freqKhz': 910525, 'bwKhz': 62.5, 'sf': 7, 'cr': 5}, + 'listenSeconds': 60, + 'packets': [ + { + 't': 1791770400, + 'pt': 5, + 'rt': 1, + 'hw': 1, + 'path': 'a1b2c3', + 'snr': 7.25, + 'rssi': -92, + 'size': 48, + 'h': '0123456789abcdef', + 'scoped': false, + }, + ], + 'adverts': [ + { + 't': 1791770400, + 'key': 'ab' * 32, + 'type': 2, + 'name': 'Hilltop RPT', + 'loc': {'lat': 33.47, 'lon': -112.068234}, + 'hidden': false, + 'snr': 9.5, + 'rssi': -80, + 'rt': 1, + 'hw': 1, + 'path': 'a1', + }, + ], + }); + }); + + test('heartbeat has null loc/preset and empty lists', () { + final body = buildUploadBody( + installId: 'x', + app: 'meshcore-open', + loc: null, + preset: null, + listenSeconds: 900, + packets: const [], + adverts: const [], + ); + expect(body['loc'], isNull); + expect(body['preset'], isNull); + expect(body['listenSeconds'], 600); + expect(body['packets'], isEmpty); + expect(body['adverts'], isEmpty); + }); + + test('preset maps radio units and rejects unknown values', () { + final preset = NetworkMapPreset.fromRadio( + freqKhz: 869525, + bwHz: 250000, + sf: 11, + cr: 1, + )!; + expect(preset.toJson(), { + 'freqKhz': 869525, + 'bwKhz': 250, + 'sf': 11, + 'cr': 5, + }); + expect( + NetworkMapPreset.fromRadio( + freqKhz: 869525, + bwHz: 41700, + sf: 8, + cr: 8, + )!.bwKhz, + 41.7, + ); + expect( + NetworkMapPreset.fromRadio(freqKhz: 869525, bwHz: 12345, sf: 7, cr: 5), + isNull, + ); + expect( + NetworkMapPreset.fromRadio(freqKhz: 50, bwHz: 62500, sf: 7, cr: 5), + isNull, + ); + expect(NetworkMapPreset.fromRadio(), isNull); + }); + }); + + group('install ID', () { + test('random, 16 bytes, rotated every 24 h', () async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + var now = DateTime(2026, 10, 11, 12); + final installId = NetworkMapInstallId(prefs, now: () => now); + + final first = installId.current(); + expect(first.contains('='), isFalse); + expect(RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(first), isTrue); + expect(base64Url.decode('$first=='), hasLength(16)); + + now = now.add(const Duration(hours: 23, minutes: 59)); + expect(installId.current(), first); + + now = now.add(const Duration(minutes: 2)); + final second = installId.current(); + expect(second, isNot(first)); + expect(base64Url.decode('$second=='), hasLength(16)); + + now = now.add(const Duration(hours: 1)); + expect(installId.current(), second); + }); + }); + + group('upload queue', () { + final now = DateTime.utc(2026, 10, 11, 18, 41, 30); + final minute = networkMapMinute(now); + + test('batches respect the contract caps', () { + final queue = NetworkMapUploadQueue(); + for (var i = 0; i < 2500; i++) { + queue.addPacket(_packet(minute), now); + } + for (var i = 0; i < 250; i++) { + queue.addAdvert( + _advert(minute, i.toRadixString(16).padLeft(64, '0')), + now, + ); + } + final batch = queue.peekBatch(); + expect(batch.packets, hasLength(2000)); + expect(batch.adverts, hasLength(200)); + + queue.remove(batch.packets.length, batch.adverts.length); + final rest = queue.peekBatch(); + expect(rest.packets, hasLength(500)); + expect(rest.adverts, hasLength(50)); + }); + + test('one advert per key is kept', () { + final queue = NetworkMapUploadQueue(); + queue.addAdvert(_advert(minute - 60, 'a' * 64), now); + queue.addAdvert(_advert(minute, 'a' * 64), now); + expect(queue.advertCount, 1); + expect(queue.peekBatch().adverts.single.t, minute); + }); + + test('drops data the server would reject or older than an hour', () { + final queue = NetworkMapUploadQueue(); + queue.addPacket(_packet(minute), now); + queue.addPacket(_packet(minute - 61 * 60), now); + queue.addPacket( + _packet(minute), + now.subtract(const Duration(hours: 1, minutes: 1)), + ); + queue.dropExpired(now); + expect(queue.packetCount, 1); + expect(queue.peekBatch().packets.single.t, minute); + }); + }); +} diff --git a/test/utils/location_grid_test.dart b/test/utils/location_grid_test.dart new file mode 100644 index 00000000..35fb2d88 --- /dev/null +++ b/test/utils/location_grid_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/utils/location_grid.dart'; + +void main() { + const vectors = [ + (33.448376, -112.074036, 33.45, -112.080261), + (47.606209, -122.332069, 47.61, -122.344218), + (-33.8688, 151.2093, -33.87, 151.215954), + (0.0, 0.0, 0.01, -0.009997), + (51.5007, -0.1246, 51.51, -0.125401), + ]; + + test('matches the API contract test vectors', () { + for (final (lat, lon, wantLat, wantLon) in vectors) { + final snapped = snapToLocationGrid(lat, lon); + expect(snapped.lat, closeTo(wantLat, 1e-9), reason: '$lat,$lon lat'); + expect(snapped.lon, closeTo(wantLon, 1e-9), reason: '$lat,$lon lon'); + } + }); + + test('snapping a center is idempotent', () { + for (final (lat, lon, _, _) in vectors) { + final once = snapToLocationGrid(lat, lon); + final twice = snapToLocationGrid(once.lat, once.lon); + expect(twice.lat, closeTo(once.lat, 1e-6)); + expect(twice.lon, closeTo(once.lon, 1e-6)); + } + }); +} diff --git a/test/widgets/get_node_banner_test.dart b/test/widgets/get_node_banner_test.dart new file mode 100644 index 00000000..5cb90bc9 --- /dev/null +++ b/test/widgets/get_node_banner_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/widgets/get_node_banner.dart'; + +void main() { + Future pumpBanner( + WidgetTester tester, { + required Size size, + required double textScale, + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: MediaQuery( + data: MediaQueryData( + size: size, + textScaler: TextScaler.linear(textScale), + ), + child: const Scaffold(bottomNavigationBar: GetNodeBanner()), + ), + ), + ); + } + + testWidgets('shows the pitch and affiliate link', (tester) async { + await pumpBanner(tester, size: const Size(390, 844), textScale: 1); + + expect(find.text('Need a new node?'), findsOneWidget); + expect(find.text('Get one here'), findsOneWidget); + expect(find.textContaining('Affiliate link'), findsOneWidget); + expect(getNodeUrl, contains('sensecap_affiliate=JFWID0g')); + // Leaves most of the screen for the device list. + expect( + tester.getSize(find.byType(GetNodeBanner)).height, + lessThan(844 * 0.4), + ); + }); + + testWidgets('lays out on a narrow phone with large text', (tester) async { + await pumpBanner(tester, size: const Size(320, 800), textScale: 1.5); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/widgets/network_map_opt_in_dialog_test.dart b/test/widgets/network_map_opt_in_dialog_test.dart new file mode 100644 index 00000000..0119b830 --- /dev/null +++ b/test/widgets/network_map_opt_in_dialog_test.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/widgets/network_map_opt_in_dialog.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _ConnectedConnector extends MeshCoreConnector { + @override + bool get isConnected => true; +} + +void main() { + late AppSettingsService settings; + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + settings = AppSettingsService(); + await settings.loadSettings(); + connector = _ConnectedConnector(); + }); + + tearDown(() => connector.dispose()); + + Future pumpHost(WidgetTester tester) async { + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: connector), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => TextButton( + onPressed: () => maybeShowNetworkMapOptInDialog(context), + child: const Text('open'), + ), + ), + ), + ), + ); + } + + testWidgets('Share turns uploading on and the prompt never returns', ( + tester, + ) async { + await pumpHost(tester); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.text('Help build the network map?'), findsOneWidget); + await tester.tap(find.text('Share')); + await tester.pumpAndSettle(); + + expect(settings.settings.networkMapUploadEnabled, isTrue); + expect(settings.settings.networkMapPromptShown, isTrue); + + await settings.setNetworkMapUploadEnabled(false); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Help build the network map?'), findsNothing); + }); + + testWidgets('No thanks leaves uploading off and is remembered', ( + tester, + ) async { + await pumpHost(tester); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + await tester.tap(find.text('No thanks')); + await tester.pumpAndSettle(); + + expect(settings.settings.networkMapUploadEnabled, isFalse); + expect(settings.settings.networkMapPromptShown, isTrue); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Help build the network map?'), findsNothing); + }); + + testWidgets('not shown while no radio is connected', (tester) async { + connector.dispose(); + connector = MeshCoreConnector(); + await pumpHost(tester); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.text('Help build the network map?'), findsNothing); + expect(settings.settings.networkMapPromptShown, isFalse); + }); +} From 49582d3f07321b310c6e4043627eed097ae524a4 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 22:05:29 -0700 Subject: [PATCH 6/8] Format tcp transport test for the current stable formatter --- .../tcp_transport_service_native_test.dart | 52 +++++++++---------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/test/services/tcp_transport_service_native_test.dart b/test/services/tcp_transport_service_native_test.dart index 3cb9629c..72edf22e 100644 --- a/test/services/tcp_transport_service_native_test.dart +++ b/test/services/tcp_transport_service_native_test.dart @@ -61,34 +61,30 @@ int _readIntOption(Socket socket, int level, int option) { } void main() { - test( - 'connect enables TCP keepalive with short probe timings', - () async { - final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); - final overrides = _CapturingConnectOverrides(); - final service = TcpTransportService(); - try { - await IOOverrides.runZoned( - () => service.connect( - host: InternetAddress.loopbackIPv4.address, - port: server.port, - ), - socketConnect: overrides.socketConnect, - ); - final socket = overrides.socket!; - // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, - // TCP_KEEPCNT 6. - expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); - } finally { - await service.disconnect(); - await server.close(); - } - }, - skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones', - ); + test('connect enables TCP keepalive with short probe timings', () async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final overrides = _CapturingConnectOverrides(); + final service = TcpTransportService(); + try { + await IOOverrides.runZoned( + () => service.connect( + host: InternetAddress.loopbackIPv4.address, + port: server.port, + ), + socketConnect: overrides.socketConnect, + ); + final socket = overrides.socket!; + // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, + // TCP_KEEPCNT 6. + expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); + } finally { + await service.disconnect(); + await server.close(); + } + }, skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones'); test('connect/disconnect updates TCP transport state', () async { final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); From e614fb32e27d1b7feab0e9173359ceefdf409f81 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 22:09:08 -0700 Subject: [PATCH 7/8] Address review: consent race, unsigned advert bytes, antimeridian - Uploads carry a consent generation: nothing is sent if sharing is turned off while a batch is being prepared, and a late response never touches a queue that was cleared and refilled - Parse only the signed 32 advert app-data bytes, as the firmware does, so appended unsigned bytes can't add the hidden marker or change the name - Split online map requests that cross the antimeridian into two valid boxes and merge the results - README: link the network map next to the website --- README.md | 2 +- .../network_map/network_map_api_client.dart | 26 ++++++ .../network_map/network_map_records.dart | 9 +- .../network_map_upload_service.dart | 26 +++++- lib/widgets/network_map_online_layer.dart | 27 +++--- .../network_map_api_client_test.dart | 45 ++++++++++ .../network_map/network_map_records_test.dart | 29 +++++- .../network_map_upload_service_test.dart | 89 +++++++++++++++++++ 8 files changed, 239 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 68b015a6..92d60fe4 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Open-source Flutter client for MeshCore LoRa mesh networking devices. MeshCore Open is a cross-platform application for communicating with MeshCore LoRa mesh radios over Bluetooth Low Energy (BLE), USB serial, or TCP. The app enables long-range, off-grid communication through peer-to-peer messaging, public channels, and mesh networking capabilities. -**Website:** [meshcoreopen.org](https://meshcoreopen.org/) +**Website:** [meshcoreopen.org](https://meshcoreopen.org/) · **Network map:** [map.meshcoreopen.org](https://map.meshcoreopen.org/) Get it on Obtainium diff --git a/lib/services/network_map/network_map_api_client.dart b/lib/services/network_map/network_map_api_client.dart index 7ba3cebb..ec549959 100644 --- a/lib/services/network_map/network_map_api_client.dart +++ b/lib/services/network_map/network_map_api_client.dart @@ -25,6 +25,32 @@ class NetworkMapBbox { maxLon - minLon <= networkMapMaxBboxSpan && maxLat - minLat <= networkMapMaxBboxSpan; + /// Valid request boxes for a visible area, or null when it is larger than + /// [networkMapMaxBboxSpan]. [west] and [east] may be unwrapped (beyond + /// ±180) or wrapped across the antimeridian (west > east); an area that + /// crosses ±180 is split into two boxes, one on each side. + static List? forVisibleArea({ + required double west, + required double south, + required double east, + required double north, + }) { + final minLat = south.clamp(-90.0, 90.0); + final maxLat = north.clamp(-90.0, 90.0); + var span = east - west; + if (span < 0) span += 360; + if (span > networkMapMaxBboxSpan || + maxLat - minLat > networkMapMaxBboxSpan) { + return null; + } + final w = (west + 180) % 360 - 180; // Dart % is non-negative here. + final e = w + span; + NetworkMapBbox box(double a, double b) => + NetworkMapBbox(minLon: a, minLat: minLat, maxLon: b, maxLat: maxLat); + if (e <= 180) return [box(w, e)]; + return [box(w, 180), box(-180, e - 360)]; + } + String get query => [ minLon, minLat, diff --git a/lib/services/network_map/network_map_records.dart b/lib/services/network_map/network_map_records.dart index aeefb432..dc1a8d93 100644 --- a/lib/services/network_map/network_map_records.dart +++ b/lib/services/network_map/network_map_records.dart @@ -1,3 +1,4 @@ +import 'dart:math'; import 'dart:convert'; import 'dart:typed_data'; @@ -288,7 +289,13 @@ Future buildAdvertRecord( const appDataStart = _advertPubKeySize + 4 + _advertSignatureSize; if (payload.length <= appDataStart) return null; - final appData = payload.sublist(appDataStart); + // Only the first 32 app-data bytes are signed (firmware Mesh.cpp truncates + // to MAX_ADVERT_DATA_SIZE before verifying and parsing), so bytes appended + // after them must never reach the name, location or 🚫 check. + final appData = payload.sublist( + appDataStart, + min(payload.length, appDataStart + _maxAdvertDataSize), + ); final flags = appData[0]; final type = flags & 0x0F; if (type != advTypeRepeater && type != advTypeRoom) return null; diff --git a/lib/services/network_map/network_map_upload_service.dart b/lib/services/network_map/network_map_upload_service.dart index 54dae384..2c6fa895 100644 --- a/lib/services/network_map/network_map_upload_service.dart +++ b/lib/services/network_map/network_map_upload_service.dart @@ -140,6 +140,12 @@ class NetworkMapUploadService extends ChangeNotifier { StreamSubscription? _frameSub; Timer? _timer; bool _uploading = false; + + /// Bumped whenever sharing is turned off. An upload started under an older + /// generation is never sent and its result is ignored, so nothing leaves the + /// phone after consent is withdrawn and a late response can't touch a queue + /// that was cleared and refilled in the meantime. + int _consentGeneration = 0; int _failures = 0; Duration _retryAfter = Duration.zero; Duration _nextInterval = uploadInterval; @@ -189,7 +195,10 @@ class NetworkMapUploadService extends ChangeNotifier { } void _sync() { - if (!enabled) _queue.clear(); + if (!enabled && (isActive || !_queue.isEmpty || _uploading)) { + _queue.clear(); + _consentGeneration++; + } // The store-review demo radio is simulated; its traffic must not reach // the real map. final shouldListen = @@ -263,6 +272,8 @@ class NetworkMapUploadService extends ChangeNotifier { Future _upload() async { _uploading = true; + final generation = _consentGeneration; + bool stale() => generation != _consentGeneration || !enabled; _lastAttemptAt = DateTime.now(); try { _accrueListenTime(); @@ -289,6 +300,7 @@ class NetworkMapUploadService extends ChangeNotifier { packets: batch.packets, adverts: batch.adverts, ); + if (stale()) return; final jsonBytes = utf8.encode(jsonEncode(body)); final gzipped = gzipEncode(jsonBytes); final response = await _client @@ -301,6 +313,7 @@ class NetworkMapUploadService extends ChangeNotifier { body: gzipped ?? jsonBytes, ) .timeout(const Duration(seconds: 30)); + if (stale()) return; final status = response.statusCode; if (status == 202 || status == 200) { _queue.remove(batch.packets.length, batch.adverts.length); @@ -318,6 +331,7 @@ class NetworkMapUploadService extends ChangeNotifier { _failures = 0; } } catch (e) { + if (stale()) return; appLogger.warn('Network map upload failed: $e', tag: 'NetworkMap'); _onFailed(null, null); } finally { @@ -363,6 +377,16 @@ class NetworkMapUploadService extends ChangeNotifier { : Duration(seconds: min(retryAfter, maxBackoff.inSeconds)); } + @visibleForTesting + int get queuedPacketCount => _queue.packetCount; + + @visibleForTesting + void queuePacketForTest(NetworkMapPacketRecord record) => + _queue.addPacket(record, DateTime.now()); + + @visibleForTesting + Future uploadNowForTest() => _upload(); + Future _appString() async { if (_appId != null) return _appId!; var version = ''; diff --git a/lib/widgets/network_map_online_layer.dart b/lib/widgets/network_map_online_layer.dart index 750bbc58..f3a0d5e9 100644 --- a/lib/widgets/network_map_online_layer.dart +++ b/lib/widgets/network_map_online_layer.dart @@ -52,26 +52,33 @@ class NetworkMapOnlineController extends ChangeNotifier { } Future _load(LatLngBounds bounds) async { - final bbox = NetworkMapBbox( - minLon: bounds.west.clamp(-180.0, 180.0), - minLat: bounds.south.clamp(-90.0, 90.0), - maxLon: bounds.east.clamp(-180.0, 180.0), - maxLat: bounds.north.clamp(-90.0, 90.0), + final boxes = NetworkMapBbox.forVisibleArea( + west: bounds.west, + south: bounds.south, + east: bounds.east, + north: bounds.north, ); final generation = ++_generation; - if (!bbox.isWithinLimit) { + if (boxes == null) { _setState(NetworkMapLoadState.zoomIn); return; } _setState(NetworkMapLoadState.loading); try { final results = await Future.wait([ - _client.fetchRepeaters(bbox), - _client.fetchLinks(bbox), + Future.wait(boxes.map(_client.fetchRepeaters)), + Future.wait(boxes.map((b) => _client.fetchLinks(b))), ]); if (_disposed || generation != _generation) return; - _repeaters = results[0] as List; - _links = results[1] as List; + // Two boxes (antimeridian) can both return items on the seam. + _repeaters = { + for (final r in results[0].expand((l) => l as List)) + r.key: r, + }.values.toList(); + _links = { + for (final l in results[1].expand((l) => l as List)) + '${l.a}:${l.b}': l, + }.values.toList(); _setState(NetworkMapLoadState.ready); } catch (_) { if (_disposed || generation != _generation) return; diff --git a/test/services/network_map/network_map_api_client_test.dart b/test/services/network_map/network_map_api_client_test.dart index 8492ef41..a35d861f 100644 --- a/test/services/network_map/network_map_api_client_test.dart +++ b/test/services/network_map/network_map_api_client_test.dart @@ -41,6 +41,51 @@ const _bbox = NetworkMapBbox( ); void main() { + group('visible area to request boxes', () { + List>? boxes(double w, double s, double e, double n) => + NetworkMapBbox.forVisibleArea( + west: w, + south: s, + east: e, + north: n, + )?.map((b) => [b.minLon, b.minLat, b.maxLon, b.maxLat]).toList(); + + test('normal area is one box', () { + expect(boxes(-112.5, 33, -111.5, 34), [ + [-112.5, 33, -111.5, 34], + ]); + }); + + test('wrapped across the antimeridian is split in two', () { + expect(boxes(179, -18, -179, -16), [ + [179, -18, 180, -16], + [-180, -18, -179, -16], + ]); + }); + + test('unwrapped longitudes beyond 180 are normalised and split', () { + expect(boxes(175, 0, 185, 5), [ + [175, 0, 180, 5], + [-180, 0, -175, 5], + ]); + expect(boxes(190, 0, 200, 5), [ + [-170, 0, -160, 5], + ]); + }); + + test('too large an area asks to zoom in', () { + expect(boxes(-130, 20, -60, 50), isNull); + expect(boxes(170, -40, -170, 40), isNull); + }); + + test('every box is valid for the server', () { + for (final b in boxes(179.5, 10, -170.25, 12)!) { + expect(b[0] < b[2], isTrue); + expect(b[0] >= -180 && b[2] <= 180, isTrue); + } + }); + }); + test('parses repeaters and sends bbox', () async { late Uri requested; final client = NetworkMapApiClient( diff --git a/test/services/network_map/network_map_records_test.dart b/test/services/network_map/network_map_records_test.dart index 441f09f4..320311a5 100644 --- a/test/services/network_map/network_map_records_test.dart +++ b/test/services/network_map/network_map_records_test.dart @@ -75,6 +75,7 @@ Future> _signedAdvertPayload({ double? lon, String? name, bool corruptSignature = false, + List unsignedSuffix = const [], }) async { final publicKey = (await keyPair.extractPublicKey()).bytes; final timestamp = [0x10, 0x20, 0x30, 0x40]; @@ -99,7 +100,13 @@ Future> _signedAdvertPayload({ ], keyPair: keyPair); final sigBytes = List.from(signature.bytes); if (corruptSignature) sigBytes[10] ^= 0x01; - return [...publicKey, ...timestamp, ...sigBytes, ...appData]; + return [ + ...publicKey, + ...timestamp, + ...sigBytes, + ...appData, + ...unsignedSuffix, + ]; } void main() { @@ -279,6 +286,7 @@ void main() { double? lon, String? name, bool corrupt = false, + List unsignedSuffix = const [], }) async { return _rxFrame( payloadType: payloadTypeADVERT, @@ -291,6 +299,7 @@ void main() { lon: lon, name: name, corruptSignature: corrupt, + unsignedSuffix: unsignedSuffix, ), ); } @@ -361,6 +370,24 @@ void main() { expect(json['key'], keyHex); }); + test('bytes after the signed 32 app-data bytes are ignored', () async { + // flags (1) + location (8) + 23-byte name fill the signed 32 bytes. + const name = 'Hilltop Repeater North1'; + expect(utf8.encode(name).length, 23); + final frame = await advertFrame( + type: advTypeRepeater, + lat: 47.6, + lon: -122.3, + name: name, + unsignedSuffix: utf8.encode(' \u{1F6AB} evil'), + ); + final advert = (await buildAdvertRecord(frame, _receivedAt))!; + final json = advert.toJson(); + expect(json['hidden'], false); + expect(json['name'], name); + expect(json['loc'], isNotNull); + }); + test('adverts with a bad signature are dropped', () async { final frame = await advertFrame( type: advTypeRepeater, diff --git a/test/services/network_map/network_map_upload_service_test.dart b/test/services/network_map/network_map_upload_service_test.dart index db7c0efe..39442f7c 100644 --- a/test/services/network_map/network_map_upload_service_test.dart +++ b/test/services/network_map/network_map_upload_service_test.dart @@ -3,7 +3,9 @@ import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_records.dart'; import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'dart:async'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -45,4 +47,91 @@ void main() { expect(service.packetsSentToday, 0); expect(requests, 0); }); + + group('withdrawing consent mid-upload', () { + NetworkMapPacketRecord packet() => NetworkMapPacketRecord( + t: DateTime.now().millisecondsSinceEpoch ~/ 60000 * 60, + pt: 5, + rt: 1, + hw: 1, + path: 'aa', + snr: 6.5, + rssi: -90, + size: 48, + h: '0011223344556677', + scoped: false, + ); + + Future<(NetworkMapUploadService, AppSettingsService)> setUpService( + MockClient client, + ) async { + final connector = _ConnectedConnector(); + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setNetworkMapUploadEnabled(true); + final service = NetworkMapUploadService( + connector: connector, + settings: settings, + client: client, + ); + addTearDown(() { + service.dispose(); + connector.dispose(); + }); + return (service, settings); + } + + test( + 'nothing is sent when sharing is turned off before the POST', + () async { + var requests = 0; + final (service, settings) = await setUpService( + MockClient((_) async { + requests++; + return http.Response('{}', 202); + }), + ); + service.queuePacketForTest(packet()); + final upload = service.uploadNowForTest(); + await settings.setNetworkMapUploadEnabled(false); + await upload; + + expect(requests, 0); + expect(service.queuedPacketCount, 0); + expect(service.lastUploadAt, isNull); + }, + ); + + test('a late response never touches the refilled queue', () async { + final response = Completer(); + final posted = Completer(); + final (service, settings) = await setUpService( + MockClient((_) { + posted.complete(); + return response.future; + }), + ); + service.queuePacketForTest(packet()); + final upload = service.uploadNowForTest(); + await posted.future; + + // Off and on again while the first POST is in flight, then new records. + await settings.setNetworkMapUploadEnabled(false); + await settings.setNetworkMapUploadEnabled(true); + service.queuePacketForTest(packet()); + service.queuePacketForTest(packet()); + + response.complete(http.Response('{}', 202)); + await upload; + + expect(service.queuedPacketCount, 2); + expect(service.lastUploadAt, isNull); + expect(service.packetsSentToday, 0); + }); + }); +} + +class _ConnectedConnector extends MeshCoreConnector { + @override + bool get isConnected => true; } From 3bee159c4fc954210578aa72236f58e14dedae6b Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 22:13:55 -0700 Subject: [PATCH 8/8] Update app version to 9.5.0+19 and mark version as BETA in settings screen --- lib/screens/settings_screen.dart | 2 +- pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 4656e8a4..dff41c0b 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -50,7 +50,7 @@ class _SettingsScreenState extends State { final packageInfo = await PackageInfo.fromPlatform(); if (!mounted) return; setState(() { - _appVersion = packageInfo.version; + _appVersion = '${packageInfo.version} BETA'; }); } diff --git a/pubspec.yaml b/pubspec.yaml index c27d3827..39df156b 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+18 +version: 9.5.0+19 environment: sdk: ^3.9.2