From 88dcc5943ff1b7a0341599fb7acce739158bb806 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 11 Oct 2026 15:17:01 -0700 Subject: [PATCH] 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); + }, + ); + } +}